SCGR commited on
Commit
dc509f9
·
1 Parent(s): 0a51a83

analytics nav fix

Browse files
py_backend/app/main.py CHANGED
@@ -17,7 +17,15 @@ from app.routers.prompts import router as prompts_router
17
  from app.routers.admin import router as admin_router
18
  from app.routers.schemas import router as schemas_router
19
 
20
- app = FastAPI(title="PromptAid Vision", redirect_slashes=False)
 
 
 
 
 
 
 
 
21
 
22
  app.add_middleware(
23
  CORSMiddleware,
@@ -28,6 +36,7 @@ app.add_middleware(
28
  allow_headers=["*"],
29
  )
30
 
 
31
  app.include_router(caption.router, prefix="/api", tags=["captions"])
32
  app.include_router(metadata.router, prefix="/api", tags=["metadata"])
33
  app.include_router(models.router, prefix="/api", tags=["models"])
@@ -37,6 +46,9 @@ app.include_router(prompts_router, prefix="/api/prompts", tags=["prompts"
37
  app.include_router(admin_router, prefix="/api/admin", tags=["admin"])
38
  app.include_router(schemas_router, prefix="/api", tags=["schemas"])
39
 
 
 
 
40
  @app.get("/health", include_in_schema=False, response_class=JSONResponse)
41
  async def health():
42
  return {"status": "ok"}
@@ -49,21 +61,44 @@ def root():
49
  <p>OK</p>
50
  <p><a href="/app/">Open UI</a> • <a href="/docs">API Docs</a></p>"""
51
 
 
52
  if os.path.exists("/app"):
53
  STATIC_DIR = "/app/static"
54
  else:
55
- STATIC_DIR = "../frontend/dist"
56
 
57
  print(f"Looking for static files in: {STATIC_DIR}")
58
 
59
  if os.path.isdir(STATIC_DIR):
60
  print(f"Static directory found: {STATIC_DIR}")
 
61
  app.mount("/app", StaticFiles(directory=STATIC_DIR, html=True), name="static")
 
62
  else:
63
  print(f"Static directory NOT found: {STATIC_DIR}")
64
  print(f"Current directory contents: {os.listdir(os.path.dirname(__file__))}")
65
  print(f"Parent directory contents: {os.listdir(os.path.dirname(os.path.dirname(__file__)))}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
 
67
  @app.get("/app/{full_path:path}", include_in_schema=False)
68
  def spa_fallback(full_path: str):
69
  index = os.path.join(STATIC_DIR, "index.html")
@@ -71,6 +106,20 @@ def spa_fallback(full_path: str):
71
  return FileResponse(index)
72
  raise HTTPException(status_code=404, detail="Not Found")
73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  @app.get("/debug")
75
  async def debug():
76
  return {
 
17
  from app.routers.admin import router as admin_router
18
  from app.routers.schemas import router as schemas_router
19
 
20
+ app = FastAPI(title="PromptAid Vision")
21
+
22
+ # Add request logging middleware
23
+ @app.middleware("http")
24
+ async def log_requests(request, call_next):
25
+ print(f"DEBUG: {request.method} {request.url.path}")
26
+ response = await call_next(request)
27
+ print(f"DEBUG: {request.method} {request.url.path} -> {response.status_code}")
28
+ return response
29
 
30
  app.add_middleware(
31
  CORSMiddleware,
 
36
  allow_headers=["*"],
37
  )
38
 
39
+ # API routes - must come BEFORE static file mounting
40
  app.include_router(caption.router, prefix="/api", tags=["captions"])
41
  app.include_router(metadata.router, prefix="/api", tags=["metadata"])
42
  app.include_router(models.router, prefix="/api", tags=["models"])
 
46
  app.include_router(admin_router, prefix="/api/admin", tags=["admin"])
47
  app.include_router(schemas_router, prefix="/api", tags=["schemas"])
48
 
49
+ # Remove the explicit route since it conflicts with the router
50
+ # The upload router already handles /api/images/ routes
51
+
52
  @app.get("/health", include_in_schema=False, response_class=JSONResponse)
53
  async def health():
54
  return {"status": "ok"}
 
61
  <p>OK</p>
62
  <p><a href="/app/">Open UI</a> • <a href="/docs">API Docs</a></p>"""
63
 
64
+ # Static file serving - must come AFTER API routes
65
  if os.path.exists("/app"):
66
  STATIC_DIR = "/app/static"
67
  else:
68
+ STATIC_DIR = "static" # Use relative path to py_backend/static
69
 
70
  print(f"Looking for static files in: {STATIC_DIR}")
71
 
72
  if os.path.isdir(STATIC_DIR):
73
  print(f"Static directory found: {STATIC_DIR}")
74
+ # Mount static files at /app to avoid conflicts with /api routes
75
  app.mount("/app", StaticFiles(directory=STATIC_DIR, html=True), name="static")
76
+ print(f"Static files mounted at /app from {STATIC_DIR}")
77
  else:
78
  print(f"Static directory NOT found: {STATIC_DIR}")
79
  print(f"Current directory contents: {os.listdir(os.path.dirname(__file__))}")
80
  print(f"Parent directory contents: {os.listdir(os.path.dirname(os.path.dirname(__file__)))}")
81
+ print(f"Attempting to find static directory...")
82
+
83
+ # Try to find static directory
84
+ possible_paths = [
85
+ "static",
86
+ "../static",
87
+ "py_backend/static",
88
+ "../py_backend/static"
89
+ ]
90
+
91
+ for path in possible_paths:
92
+ if os.path.isdir(path):
93
+ print(f"Found static directory at: {path}")
94
+ STATIC_DIR = path
95
+ app.mount("/app", StaticFiles(directory=STATIC_DIR, html=True), name="static")
96
+ print(f"Static files mounted at /app from {STATIC_DIR}")
97
+ break
98
+ else:
99
+ print("Could not find static directory - static file serving disabled")
100
 
101
+ # SPA fallback - must come AFTER static file mounting
102
  @app.get("/app/{full_path:path}", include_in_schema=False)
103
  def spa_fallback(full_path: str):
104
  index = os.path.join(STATIC_DIR, "index.html")
 
106
  return FileResponse(index)
107
  raise HTTPException(status_code=404, detail="Not Found")
108
 
109
+ # Debug route to show all registered routes
110
+ @app.get("/debug-routes", include_in_schema=False)
111
+ async def debug_routes():
112
+ """Show all registered routes for debugging"""
113
+ routes = []
114
+ for route in app.routes:
115
+ if hasattr(route, 'path'):
116
+ routes.append({
117
+ "path": route.path,
118
+ "name": getattr(route, 'name', 'N/A'),
119
+ "methods": list(route.methods) if hasattr(route, 'methods') else []
120
+ })
121
+ return {"routes": routes}
122
+
123
  @app.get("/debug")
124
  async def debug():
125
  return {
py_backend/app/routers/upload.py CHANGED
@@ -2,7 +2,6 @@ from fastapi import APIRouter, UploadFile, Form, Depends, HTTPException, Respons
2
  from pydantic import BaseModel
3
  import io
4
  from sqlalchemy.orm import Session
5
- from sqlalchemy import text
6
  from .. import crud, schemas, storage, database
7
  from ..config import settings
8
  from ..services.image_preprocessor import ImagePreprocessor
@@ -95,30 +94,13 @@ def convert_image_to_dict(img, image_url):
95
  @router.get("/", response_model=List[schemas.ImageOut])
96
  def list_images(db: Session = Depends(get_db)):
97
  """Get all images with their caption data"""
98
- try:
99
- print(f"DEBUG: Checking database connection")
100
- # Test database connection
101
- db.execute(text("SELECT 1"))
102
- print(f"DEBUG: Database connection OK")
103
-
104
- print(f"DEBUG: Fetching images from database")
105
- images = crud.get_images(db)
106
- print(f"DEBUG: Found {len(images)} images")
107
-
108
- result = []
109
- for img in images:
110
- try:
111
- img_dict = convert_image_to_dict(img, f"/api/images/{img.image_id}/file")
112
- result.append(schemas.ImageOut(**img_dict))
113
- except Exception as e:
114
- print(f"ERROR: Failed to process image {img.image_id}: {e}")
115
- continue
116
-
117
- print(f"DEBUG: Returning {len(result)} processed images")
118
- return result
119
- except Exception as e:
120
- print(f"ERROR: Failed to fetch images: {e}")
121
- raise HTTPException(status_code=500, detail=f"Failed to fetch images: {str(e)}")
122
 
123
  @router.get("/{image_id}", response_model=schemas.ImageOut)
124
  def get_image(image_id: str, db: Session = Depends(get_db)):
 
2
  from pydantic import BaseModel
3
  import io
4
  from sqlalchemy.orm import Session
 
5
  from .. import crud, schemas, storage, database
6
  from ..config import settings
7
  from ..services.image_preprocessor import ImagePreprocessor
 
94
  @router.get("/", response_model=List[schemas.ImageOut])
95
  def list_images(db: Session = Depends(get_db)):
96
  """Get all images with their caption data"""
97
+ images = crud.get_images(db)
98
+ result = []
99
+ for img in images:
100
+ img_dict = convert_image_to_dict(img, f"/api/images/{img.image_id}/file")
101
+ result.append(schemas.ImageOut(**img_dict))
102
+
103
+ return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
  @router.get("/{image_id}", response_model=schemas.ImageOut)
106
  def get_image(image_id: str, db: Session = Depends(get_db)):