-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
469 lines (380 loc) Β· 18.7 KB
/
main.py
File metadata and controls
469 lines (380 loc) Β· 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
from fastapi import FastAPI, File, UploadFile, HTTPException, BackgroundTasks
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import os
import tempfile
import shutil
from pathlib import Path
import logging
from typing import List, Optional
import uuid
# Local imports
from backend.database.supabase_client import supabase_client
from backend.models.yolo_processor import yolo_processor
from backend.core.processing_service import processing_service
from backend.core.video_processor import video_processor
from backend.core.stats_calculator import stats_calculator
from backend.api.endpoints import router as api_router
from backend.core.config import (
UPLOAD_DIR, FRAMES_DIR, CROPS_DIR,
SUPPORTED_VIDEO_FORMATS, SUPPORTED_IMAGE_FORMATS,
MAX_FILE_SIZE, TARGET_FPS, SUPABASE_IMAGES_BUCKET, SUPABASE_VIDEOS_BUCKET
)
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Create FastAPI app
app = FastAPI(title="Logo Detection API", version="1.0.0")
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000", "http://localhost:3001", "http://127.0.0.1:3000", "http://127.0.0.1:3001"], # React dev server
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include API routes
app.include_router(api_router)
# Create directories
os.makedirs(UPLOAD_DIR, exist_ok=True)
os.makedirs(FRAMES_DIR, exist_ok=True)
os.makedirs(CROPS_DIR, exist_ok=True)
# Global cache for processing results and progress
processing_results = {}
processing_progress = {}
@app.get("/")
async def root():
return {"message": "Logo Detection API is running"}
@app.get("/health")
async def health_check():
return {"status": "healthy", "model_loaded": yolo_processor.model is not None}
async def process_media_file(file_path: str, original_filename: str, file_type: str, session_id: str):
"""Background task to process uploaded media file"""
try:
logger.info(f"π Starting processing of {original_filename} with session {session_id}")
# Initialize progress
processing_progress[session_id] = {"progress": 0, "stage": "Starting processing"}
# Determine if it's video or image
file_extension = Path(original_filename).suffix.lower()
is_video = file_extension in SUPPORTED_VIDEO_FORMATS
logger.info(f"π File type: {'video' if is_video else 'image'}, extension: {file_extension}")
# Update progress
processing_progress[session_id] = {"progress": 10, "stage": "Analyzing file"}
if is_video:
# Process video
logger.info(f"π¬ Processing video: {original_filename}")
processing_progress[session_id] = {"progress": 20, "stage": "Extracting frames"}
result = await processing_service.process_video(file_path, original_filename, session_id)
else:
# Process image
logger.info(f"πΌοΈ Processing image: {original_filename}")
processing_progress[session_id] = {"progress": 20, "stage": "Processing image"}
result = await processing_service.process_image(file_path, original_filename, session_id)
# Update progress to completion
processing_progress[session_id] = {"progress": 100, "stage": "Completed"}
logger.info(f"β
Processing completed for {original_filename} - File ID: {result.get('file_id')}")
logger.info(f"π Result summary: {result.get('detections_count', 0)} detections, {len(result.get('brands_detected', []))} brands")
# Store result in memory cache (for session lookup)
processing_results[session_id] = result
logger.info(f"πΎ Result stored in cache for session {session_id}")
return result
except Exception as e:
logger.error(f"β Error processing file {original_filename}: {e}")
logger.error(f"π Full error details: {type(e).__name__}: {str(e)}")
# Store error in cache
processing_results[session_id] = {"error": str(e)}
logger.info(f"πΎ Error stored in cache for session {session_id}")
raise
@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
"""Upload and process image or video file synchronously"""
try:
# Validate file size
if file.size > MAX_FILE_SIZE:
raise HTTPException(status_code=413, detail="File too large")
# Validate file type
file_extension = Path(file.filename).suffix.lower()
if file_extension not in SUPPORTED_VIDEO_FORMATS + SUPPORTED_IMAGE_FORMATS:
raise HTTPException(
status_code=400,
detail=f"Unsupported file format. Supported formats: {SUPPORTED_VIDEO_FORMATS + SUPPORTED_IMAGE_FORMATS}"
)
# Save uploaded file temporarily
session_id = str(uuid.uuid4())
temp_dir = os.path.join(UPLOAD_DIR, session_id)
os.makedirs(temp_dir, exist_ok=True)
temp_file_path = os.path.join(temp_dir, file.filename)
with open(temp_file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
# Process file SYNCHRONOUSLY (no background task)
logger.info(f"Starting synchronous processing of {file.filename}")
# Determine if it's video or image
is_video = file_extension in SUPPORTED_VIDEO_FORMATS
if is_video:
# Process video
result = await processing_service.process_video(temp_file_path, file.filename, session_id)
else:
# Process image
result = await processing_service.process_image(temp_file_path, file.filename, session_id)
logger.info(f"Processing completed for {file.filename} - File ID: {result.get('file_id')}")
# Store result in memory cache (for backward compatibility)
processing_results[session_id] = result
# Return complete result with file_id immediately
return JSONResponse(content={
"message": "File uploaded and processed successfully",
"session_id": session_id,
"file_id": result.get("file_id"),
"filename": file.filename,
"file_size": file.size,
"file_type": "video" if is_video else "image",
"processing_status": "completed",
"detections_count": result.get("detections_count", 0),
"brands_detected": result.get("brands_detected", []),
"urls": {
"video_url": result.get("video_url"),
"image_url": result.get("image_url")
},
"statistics": result.get("statistics"),
"endpoints": {
"detections": f"/detections/{result.get('file_id')}",
"frame_captures": f"/frame-captures/{result.get('file_id')}",
"file_info": f"/file-info/{result.get('file_id')}"
}
})
except Exception as e:
logger.error(f"Error uploading and processing file: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.get("/processing-status/{session_id}")
async def get_processing_status(session_id: str):
"""Get processing status and results by session ID"""
try:
if session_id not in processing_results:
return JSONResponse(content={
"status": "processing",
"message": "File is still being processed or session not found",
"session_id": session_id,
"file_id": None
})
result = processing_results[session_id]
if "error" in result:
return JSONResponse(content={
"status": "error",
"error": result["error"],
"session_id": session_id,
"file_id": None
}, status_code=500)
return JSONResponse(content={
"status": "completed",
"session_id": session_id,
"file_id": result.get("file_id"),
"detections_count": result.get("detections_count", 0),
"brands_detected": result.get("brands_detected", []),
"video_url": result.get("video_url"),
"image_url": result.get("image_url"),
"result": result
})
except Exception as e:
logger.error(f"Error getting processing status: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/upload-async")
async def upload_file_async(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
"""Upload and process image or video file asynchronously (original behavior)"""
try:
# Validate file size
if file.size > MAX_FILE_SIZE:
raise HTTPException(status_code=413, detail="File too large")
# Validate file type
file_extension = Path(file.filename).suffix.lower()
if file_extension not in SUPPORTED_VIDEO_FORMATS + SUPPORTED_IMAGE_FORMATS:
raise HTTPException(
status_code=400,
detail=f"Unsupported file format. Supported formats: {SUPPORTED_VIDEO_FORMATS + SUPPORTED_IMAGE_FORMATS}"
)
# Save uploaded file temporarily
session_id = str(uuid.uuid4())
temp_dir = os.path.join(UPLOAD_DIR, session_id)
os.makedirs(temp_dir, exist_ok=True)
temp_file_path = os.path.join(temp_dir, file.filename)
with open(temp_file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
# Initialize processing status - file uploaded but not processed yet
processing_progress[session_id] = {"progress": 0, "stage": "File uploaded, ready for processing"}
logger.info(f"π File uploaded successfully for session: {session_id}")
logger.info(f"π File saved to: {temp_file_path}")
logger.info(f"π Total sessions in processing_progress: {len(processing_progress)}")
logger.info(f"π All session IDs: {list(processing_progress.keys())}")
logger.info(f"β³ Waiting for user to select logos before processing")
return JSONResponse(content={
"message": "File uploaded successfully, ready for processing",
"session_id": session_id,
"filename": file.filename,
"file_size": file.size
})
except Exception as e:
logger.error(f"Error uploading file: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/start-processing/{session_id}")
async def start_processing(session_id: str, background_tasks: BackgroundTasks):
"""Start processing for uploaded file after logo selection"""
try:
logger.info(f"π Starting processing for session: {session_id}")
logger.info(f"π Available sessions in processing_progress: {list(processing_progress.keys())}")
# Check if session already has a result (already processed)
if session_id in processing_results:
logger.info(f"β
Session {session_id} already processed, returning existing result")
return JSONResponse(content={
"message": "Processing already completed",
"session_id": session_id,
"filename": "already_processed"
})
# Check if session exists in progress tracking
if session_id not in processing_progress:
logger.error(f"β Session {session_id} not found in processing_progress")
raise HTTPException(status_code=404, detail="Session not found")
# Find the uploaded file for this session
session_dir = os.path.join(UPLOAD_DIR, session_id)
logger.info(f"π Looking for session directory: {session_dir}")
logger.info(f"π Directory exists: {os.path.exists(session_dir)}")
if not os.path.exists(session_dir):
logger.error(f"β Session directory not found: {session_dir}")
raise HTTPException(status_code=404, detail="Uploaded file not found")
# Get the first file in the session directory
files = os.listdir(session_dir)
logger.info(f"π Files in session directory: {files}")
if not files:
logger.error(f"β No files found in session directory: {session_dir}")
raise HTTPException(status_code=404, detail="No files found for session")
file_path = os.path.join(session_dir, files[0])
original_filename = files[0]
# Determine file type
file_extension = Path(original_filename).suffix.lower()
file_type = "video" if file_extension in SUPPORTED_VIDEO_FORMATS else "image"
logger.info(f"π Found file: {original_filename} (type: {file_type})")
# Start processing in background
background_tasks.add_task(
process_media_file,
file_path,
original_filename,
file_type,
session_id
)
# Update status
processing_progress[session_id] = {"progress": 5, "stage": "Processing started"}
logger.info(f"β
Processing started for session: {session_id}")
return JSONResponse(content={
"message": "Processing started successfully",
"session_id": session_id,
"filename": original_filename
})
except Exception as e:
logger.error(f"β Error starting processing: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.get("/upload-result/{session_id}")
async def get_upload_result(session_id: str):
"""Get simplified upload result for web interface"""
try:
logger.info(f"π Checking status for session: {session_id}")
logger.info(f"π Available sessions in cache: {list(processing_results.keys())}")
if session_id not in processing_results:
logger.info(f"β³ Session {session_id} not found in cache - still processing")
progress_info = processing_progress.get(session_id, {"progress": 0, "stage": "Starting processing"})
return JSONResponse(content={
"status": "processing",
"message": "File is still being processed",
"session_id": session_id,
"file_id": None,
"ready": False
})
result = processing_results[session_id]
logger.info(f"π Found result for session {session_id}: {type(result)}")
if "error" in result:
logger.error(f"β Error found in result for session {session_id}: {result['error']}")
return JSONResponse(content={
"status": "error",
"message": result["error"],
"session_id": session_id,
"file_id": None,
"ready": True
}, status_code=500)
logger.info(f"β
Returning completed result for session {session_id}")
return JSONResponse(content={
"status": "completed",
"message": "File processed successfully",
"session_id": session_id,
"file_id": result.get("file_id"),
"detections_count": result.get("detections_count", 0),
"brands_detected": result.get("brands_detected", []),
"ready": True,
"urls": {
"video_url": result.get("video_url"),
"image_url": result.get("image_url")
}
})
except Exception as e:
logger.error(f"Error getting upload result: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.get("/file-info/{file_id}")
async def get_file_info(file_id: int):
"""Get file information and detection summary by file_id"""
try:
# Get file information
file_response = supabase_client.client.table('files').select('*').eq('id', file_id).execute()
if not file_response.data:
raise HTTPException(status_code=404, detail="File not found")
file_info = file_response.data[0]
# Get detection count
detection_response = supabase_client.client.table('detections').select('id').eq('file_id', file_id).execute()
detections_count = len(detection_response.data)
# Get brands detected
brands_response = supabase_client.client.table('detections') \
.select('brands(name)') \
.eq('file_id', file_id) \
.execute()
brands = list(set([d['brands']['name'] for d in brands_response.data if d['brands']]))
# Get frame captures count
frames_response = supabase_client.client.table('frame_captures').select('id').eq('file_id', file_id).execute()
frames_count = len(frames_response.data)
return JSONResponse(content={
"file_id": file_id,
"filename": file_info.get('filename'),
"file_type": file_info.get('file_type'),
"created_at": file_info.get('created_at'),
"detections_count": detections_count,
"brands_detected": brands,
"frame_captures_count": frames_count,
"duration_seconds": file_info.get('duration_seconds'),
"fps": file_info.get('fps'),
"storage": {
"bucket": file_info.get('bucket'),
"path": file_info.get('path')
}
})
except HTTPException:
raise
except Exception as e:
logger.error(f"Error getting file info: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.delete("/processing-status/{session_id}")
async def clear_processing_status(session_id: str):
"""Clear processing result from cache"""
try:
if session_id in processing_results:
del processing_results[session_id]
return {"message": "Processing result cleared", "session_id": session_id}
else:
return {"message": "Session not found", "session_id": session_id}
except Exception as e:
logger.error(f"Error clearing processing status: {e}")
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
import uvicorn
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Get port from environment or use default
port = int(os.getenv("BACKEND_PORT", 8001))
host = os.getenv("BACKEND_HOST", "0.0.0.0")
print(f"π Starting Logo Detection API with modular backend structure...")
print(f"π Server will be available at: http://{host}:{port}")
uvicorn.run(app, host=host, port=port)