File size: 3,698 Bytes
aecc9b7
 
5327928
 
f793037
435efcf
69c8a2d
93878a6
69c8a2d
aecc9b7
941de86
f793037
83e778c
69c8a2d
 
 
 
f793037
93878a6
69c8a2d
 
dee18ff
69c8a2d
5327928
761c17d
326a734
f793037
aecc9b7
f793037
 
 
 
aecc9b7
 
 
f793037
 
aecc9b7
 
 
 
 
fde8ac8
 
 
aecc9b7
326a734
98be153
fde8ac8
aecc9b7
 
 
 
 
 
 
 
 
 
 
fde8ac8
 
93878a6
326a734
fde8ac8
 
 
 
 
 
326a734
fde8ac8
 
 
 
 
 
 
 
aecc9b7
 
 
fde8ac8
 
f793037
fde8ac8
f793037
aecc9b7
 
 
 
545eb49
69c8a2d
aecc9b7
dee18ff
545eb49
69c8a2d
aecc9b7
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
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))