Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
| from fastapi import APIRouter, UploadFile, File | |
| import os | |
| import shutil | |
| import uuid | |
| router = APIRouter(tags=["files"]) | |
| # Définir le stockage des fichiers par session (importé dans main.py) | |
| session_files = {} | |
| # Dossier racine pour les uploads | |
| UPLOAD_ROOT = "uploaded_files" | |
| os.makedirs(UPLOAD_ROOT, exist_ok=True) | |
| # Initialize session files dictionary with pre-calculated documents | |
| precalculated_docs = ["the-bitter-lesson", "hurricane-faq", "pokemon-guide"] | |
| for doc_id in precalculated_docs: | |
| doc_dir = os.path.join(UPLOAD_ROOT, doc_id) | |
| if os.path.exists(doc_dir): | |
| doc_files_dir = os.path.join(doc_dir, "uploaded_files") | |
| if os.path.exists(doc_files_dir): | |
| for filename in os.listdir(doc_files_dir): | |
| if filename.endswith((".pdf", ".txt", ".html", ".md")): | |
| file_path = os.path.join(doc_files_dir, filename) | |
| session_files[doc_id] = file_path | |
| print(f"Added pre-calculated document to session_files: {doc_id} -> {file_path}") | |
| break | |
| else: | |
| # Search directly in the doc_dir | |
| for filename in os.listdir(doc_dir): | |
| if filename.endswith((".pdf", ".txt", ".html", ".md")): | |
| file_path = os.path.join(doc_dir, filename) | |
| session_files[doc_id] = file_path | |
| print(f"Added pre-calculated document to session_files: {doc_id} -> {file_path}") | |
| break | |
| async def upload_file(file: UploadFile = File(...)): | |
| """ | |
| Upload a file to the server and generate a session ID | |
| Args: | |
| file: The file to upload | |
| Returns: | |
| Dictionary with filename, status and session_id | |
| """ | |
| # Vérifier si le fichier est un PDF, TXT, HTML ou MD | |
| if not file.filename.endswith(('.pdf', '.txt', '.html', '.md')): | |
| return {"error": "Only PDF, TXT, HTML and MD files are accepted"} | |
| # Generate a session ID for this file | |
| session_id = str(uuid.uuid4()) | |
| # Create the session directory structure | |
| session_dir = os.path.join(UPLOAD_ROOT, session_id) | |
| uploaded_files_dir = os.path.join(session_dir, "uploaded_files") | |
| os.makedirs(uploaded_files_dir, exist_ok=True) | |
| # Create the full path to save the file | |
| file_path = os.path.join(uploaded_files_dir, file.filename) | |
| # Sauvegarder le fichier | |
| with open(file_path, "wb") as buffer: | |
| shutil.copyfileobj(file.file, buffer) | |
| # Store file path for later use | |
| session_files[session_id] = file_path | |
| # Débogage pour vérifier l'état des session_files | |
| print(f"DEBUG UPLOAD: File uploaded with session_id: {session_id}") | |
| print(f"DEBUG UPLOAD: Current session_files: {session_files}") | |
| return {"filename": file.filename, "status": "uploaded", "session_id": session_id} |