from fastapi import FastAPI, HTTPException, UploadFile, File, Form from pydantic import BaseModel import os import uuid import shutil import requests from process_interview import process_interview from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse from typing import Optional app = FastAPI() TEMP_DIR = "./temp_files" OUTPUT_DIR = "./static/outputs" JSON_DIR = os.path.join(OUTPUT_DIR, "json") PDF_DIR = os.path.join(OUTPUT_DIR, "pdf") os.makedirs(TEMP_DIR, exist_ok=True) os.makedirs(JSON_DIR, exist_ok=True) os.makedirs(PDF_DIR, exist_ok=True) app.mount("/static", StaticFiles(directory="static"), name="static") BASE_URL = os.getenv("BASE_URL", "https://evalbot-audio-evalbot.hf.space") class ProcessResponse(BaseModel): user_id: str summary: str json_url: str pdf_url: str @app.get("/") def read_root(): return {"message": "EvalBot API is running successfully! 🚀"} @app.post("/process-audio", response_model=ProcessResponse) async def process_audio( user_id: str = Form(...), file_url: Optional[str] = Form(None), file: Optional[UploadFile] = File(None) ): # إنشاء أسماء فريدة للملفات النهائية unique_id = uuid.uuid4().hex local_filename = f"{user_id}_{unique_id}" local_path = os.path.join(TEMP_DIR, local_filename) try: # 1. تحميل الملف if file_url: resp = requests.get(file_url, stream=True, timeout=30) if resp.status_code != 200: raise HTTPException(status_code=400, detail="تعذر الوصول للرابط المقدم.") with open(local_path, "wb") as f: shutil.copyfileobj(resp.raw, f) elif file: with open(local_path, "wb") as buffer: shutil.copyfileobj(file.file, buffer) else: raise HTTPException(status_code=400, detail="يجب توفير رابط صوتي أو رفع ملف.") # 2. المعالجة (تأكدي أن process_interview تعيد مسارات الملفات الناتجة) result = process_interview(local_path) # 3. نقل الملفات من مكانها الأصلي (processed_audio) إلى مجلد static العام final_json_name = f"{local_filename}.json" final_pdf_name = f"{local_filename}.pdf" json_dest_path = os.path.join(JSON_DIR, final_json_name) pdf_dest_path = os.path.join(PDF_DIR, final_pdf_name) # النقل: من مسار النتيجة إلى المسار المتاح للمتصفح shutil.move(result['json_path'], json_dest_path) shutil.move(result['pdf_path'], pdf_dest_path) # تنظيف الملف المؤقت if os.path.exists(local_path): os.remove(local_path) return ProcessResponse( user_id=user_id, summary="تم تحليل المقابلة بنجاح.", json_url=f"{BASE_URL}/static/outputs/json/{final_json_name}", pdf_url=f"{BASE_URL}/static/outputs/pdf/{final_pdf_name}" ) except Exception as e: if os.path.exists(local_path): os.remove(local_path) raise HTTPException(status_code=500, detail=f"حدث خطأ أثناء المعالجة: {str(e)}") # مسارات عرض الملفات @app.get("/static/outputs/json/{filename}") async def get_json_file(filename: str): return FileResponse(os.path.join(JSON_DIR, filename)) @app.get("/static/outputs/pdf/{filename}") async def get_pdf_file(filename: str): return FileResponse(os.path.join(PDF_DIR, filename))