norhan12 commited on
Commit
f793037
·
verified ·
1 Parent(s): 6b154ff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -42
app.py CHANGED
@@ -1,61 +1,110 @@
1
- from flask import Flask, request, jsonify, send_file
2
  import os
3
  import uuid
 
 
 
 
 
4
  import requests
5
- from process_interview import process_interview
6
- from urllib.parse import urlparse
7
 
8
- app = Flask(__name__)
9
 
10
- OUTPUT_DIR = "./processed_audio"
 
 
 
 
 
 
11
  os.makedirs(OUTPUT_DIR, exist_ok=True)
12
 
13
- @app.route("/process-audio", methods=["POST"])
14
- def process_audio():
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  try:
16
- data = request.json
17
- user_id = data.get("user_id")
18
- audio_url = data.get("audio_url")
 
19
 
20
- if not user_id or not audio_url:
21
- return jsonify({"error": "Missing user_id or audio_url"}), 400
22
 
23
- file_ext = os.path.splitext(urlparse(audio_url).path)[1]
24
- filename = f"{user_id}_{uuid.uuid4()}{file_ext}"
25
- local_file_path = os.path.join(OUTPUT_DIR, filename)
 
26
 
27
- response = requests.get(audio_url, stream=True)
28
- if response.status_code != 200:
29
- return jsonify({"error": "Failed to download audio file"}), 400
 
30
 
31
- with open(local_file_path, "wb") as f:
32
- for chunk in response.iter_content(chunk_size=8192):
33
- f.write(chunk)
 
 
34
 
35
- result = process_interview(local_file_path)
 
 
 
 
36
 
37
- if not result or 'pdf_path' not in result or 'json_path' not in result:
38
- return jsonify({"error": "Processing failed"}), 500
 
39
 
40
- server_url = request.host_url.rstrip('/')
41
- pdf_url = f"{server_url}/download?file={os.path.basename(result['pdf_path'])}"
42
- json_url = f"{server_url}/download?file={os.path.basename(result['json_path'])}"
43
 
44
- return jsonify({
45
- "message": "Processing complete",
46
- "pdf_url": pdf_url,
47
- "json_url": json_url
48
- })
49
 
50
- except Exception as e:
51
- return jsonify({"error": str(e)}), 500
52
 
53
- @app.route("/download", methods=["GET"])
54
- def download_file():
55
- filename = request.args.get("file")
56
- file_path = os.path.join(OUTPUT_DIR, filename)
57
- if not os.path.exists(file_path):
58
- return jsonify({"error": "File not found"}), 404
59
- return send_file(file_path, as_attachment=True)
60
 
61
- # لا تحتفظي بـ app.run لأن gunicorn هيشغله
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import uuid
3
+ import shutil
4
+ import json
5
+ from fastapi import FastAPI, HTTPException, Query
6
+ from fastapi.responses import JSONResponse, FileResponse
7
+ from pydantic import BaseModel
8
  import requests
9
+ from process_interview import process_interview # افترض ان ده ملف عندك فيه الدالة
10
+ from fastapi.staticfiles import StaticFiles
11
 
12
+ app = FastAPI()
13
 
14
+ app.mount("/static", StaticFiles(directory="static"), name="static")
15
+
16
+
17
+ TEMP_DIR = "./temp_files"
18
+ OUTPUT_DIR = "./static/outputs"
19
+
20
+ os.makedirs(TEMP_DIR, exist_ok=True)
21
  os.makedirs(OUTPUT_DIR, exist_ok=True)
22
 
23
+ VALID_EXTENSIONS = ('.wav', '.mp3', '.m4a', '.flac')
24
+ MAX_FILE_SIZE_MB = 300
25
+
26
+ class ProcessResponse(BaseModel):
27
+ summary: str
28
+ json_url: str
29
+ pdf_url: str
30
+
31
+ @app.get("/")
32
+ async def root():
33
+ return {"message": "EvalBot API is running"}
34
+
35
+ @app.post("/process-audio", response_model=ProcessResponse)
36
+ async def process_audio(file_url: str = Query(..., description="URL of the audio file"),
37
+ user_id: str = Query(..., description="User ID")):
38
  try:
39
+ # تحميل الملف مؤقتًا
40
+ file_ext = os.path.splitext(file_url)[1].lower()
41
+ if file_ext not in VALID_EXTENSIONS:
42
+ raise HTTPException(status_code=400, detail=f"Invalid file extension: {file_ext}")
43
 
44
+ local_filename = f"{user_id}_{uuid.uuid4().hex}{file_ext}"
45
+ local_path = os.path.join(TEMP_DIR, local_filename)
46
 
47
+ # تحميل الملف
48
+ resp = requests.get(file_url, stream=True, timeout=30)
49
+ if resp.status_code != 200:
50
+ raise HTTPException(status_code=400, detail="Could not download the file from URL")
51
 
52
+ with open(local_path, "wb") as f:
53
+ for chunk in resp.iter_content(chunk_size=8192):
54
+ if chunk:
55
+ f.write(chunk)
56
 
57
+ # تحقق من الحجم
58
+ file_size_mb = os.path.getsize(local_path) / (1024 * 1024)
59
+ if file_size_mb > MAX_FILE_SIZE_MB:
60
+ os.remove(local_path)
61
+ raise HTTPException(status_code=400, detail=f"File too large: {file_size_mb:.2f} MB")
62
 
63
+ # معالجة الملف (process_interview ترجع dict فيها json_path و pdf_path)
64
+ result = process_interview(local_path)
65
+ if not result:
66
+ os.remove(local_path)
67
+ raise HTTPException(status_code=500, detail="Processing failed")
68
 
69
+ # نسخ ملفات JSON و PDF لمجلد ثابت للاحتفاظ بهم
70
+ json_src = result['json_path']
71
+ pdf_src = result['pdf_path']
72
 
73
+ # أسماء جديدة مع UUID
74
+ json_dest_name = f"{user_id}_{uuid.uuid4().hex}.json"
75
+ pdf_dest_name = f"{user_id}_{uuid.uuid4().hex}.pdf"
76
 
77
+ json_dest = os.path.join(OUTPUT_DIR, json_dest_name)
78
+ pdf_dest = os.path.join(OUTPUT_DIR, pdf_dest_name)
 
 
 
79
 
80
+ shutil.copyfile(json_src, json_dest)
81
+ shutil.copyfile(pdf_src, pdf_dest)
82
 
83
+ # قراءة بيانات JSON للملخص
84
+ with open(json_src, "r") as jf:
85
+ analysis_data = json.load(jf)
 
 
 
 
86
 
87
+ voice = analysis_data.get('voice_analysis', {}).get('interpretation', {})
88
+ speakers = analysis_data.get('speakers', [])
89
+ total_duration = analysis_data.get('text_analysis', {}).get('total_duration', 0.0)
90
+
91
+ summary = (
92
+ f"User ID: {user_id}\n"
93
+ f"Speakers: {', '.join(speakers)}\n"
94
+ f"Duration: {total_duration:.2f} sec\n"
95
+ f"Confidence: {voice.get('confidence_level', 'N/A')}\n"
96
+ f"Anxiety: {voice.get('anxiety_level', 'N/A')}"
97
+ )
98
+
99
+ # بناء URLs للملفات
100
+ base_url = f"http://localhost:7860/static/outputs"
101
+ json_url = f"{base_url}/{json_dest_name}"
102
+ pdf_url = f"{base_url}/{pdf_dest_name}"
103
+
104
+ # تنظيف الملف الصوتي المؤقت
105
+ os.remove(local_path)
106
+
107
+ return ProcessResponse(summary=summary, json_url=json_url, pdf_url=pdf_url)
108
+
109
+ except Exception as e:
110
+ raise HTTPException(status_code=500, detail=str(e))