norhan12 commited on
Commit
435efcf
·
verified ·
1 Parent(s): 9a41576

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -80
app.py CHANGED
@@ -1,101 +1,68 @@
 
1
  import os
2
  import uuid
3
- import logging
4
  import json
5
- import shutil
6
- from pathlib import Path
7
- import tempfile
8
- import gradio as gr
9
  from process_interview import process_interview
10
- from typing import Tuple, Optional, List, Dict
11
- from concurrent.futures import ThreadPoolExecutor
12
- import requests
13
- logging.basicConfig(level=logging.INFO)
14
 
15
- # إعداد مجلد مؤقت للتحميل
16
- TEMP_DIR = "./temp_files"
17
- os.makedirs(TEMP_DIR, exist_ok=True)
18
 
19
- VALID_EXTENSIONS = ('.wav', '.mp3', '.m4a', '.flac')
20
- MAX_FILE_SIZE_MB = 300
 
21
 
22
- # Health check
23
- def check_health() -> str:
24
  try:
25
- if not os.path.exists(TEMP_DIR):
26
- os.makedirs(TEMP_DIR)
27
- return "System is healthy"
28
- except Exception as e:
29
- logging.error(f"Health check failed: {e}")
30
- return "System unhealthy"
31
 
32
- # Main Processing Function
33
- def process_audio(file_url: str, user_id: str) -> Tuple[str, str, str]:
34
- try:
35
- # تحميل الملف
36
- filename = f"{user_id}_{os.path.basename(file_url)}"
37
- local_path = os.path.join(TEMP_DIR, filename)
38
 
39
- logging.info(f"Downloading file: {file_url}")
40
- response = requests.get(file_url, stream=True)
41
- with open(local_path, 'wb') as f:
42
- for chunk in response.iter_content(chunk_size=8192):
43
- f.write(chunk)
44
 
45
- # التحقق من الامتداد والحجم
46
- file_ext = Path(local_path).suffix.lower()
47
- if file_ext not in VALID_EXTENSIONS:
48
- return f" Invalid file type: {file_ext}", "", ""
49
 
50
- file_size_mb = os.path.getsize(local_path) / (1024 * 1024)
51
- if file_size_mb > MAX_FILE_SIZE_MB:
52
- return f"❌ File too large: {file_size_mb:.2f}MB", "", ""
53
 
54
- # بدء المعالجة
55
- result = process_interview(local_path)
56
- if not result:
57
- return "❌ Processing failed.", "", ""
58
 
59
- pdf_path = result['pdf_path']
60
- with open(result['json_path'], 'r') as f:
61
- analysis_data = json.load(f)
62
 
63
- # بناء الـ Summary
64
- voice = analysis_data['voice_analysis']['interpretation']
65
- summary = (
66
- f"User ID: {user_id}\n"
67
- f"Speakers: {', '.join(analysis_data['speakers'])}\n"
68
- f"Duration: {analysis_data['text_analysis']['total_duration']:.2f} sec\n"
69
- f"Confidence: {voice['confidence_level']}\n"
70
- f"Anxiety: {voice['anxiety_level']}"
71
- )
72
 
73
- json_data = json.dumps(analysis_data, indent=2)
74
- return summary, json_data, pdf_path
 
 
 
75
 
76
  except Exception as e:
77
- logging.error(f"Error processing audio: {e}", exc_info=True)
78
- return f"❌ Internal Error: {str(e)}", "", ""
79
-
80
- # Gradio Interface
81
- with gr.Blocks(title="EvalBot Audio Analysis") as demo:
82
- gr.Markdown("# 🎙️ EvalBot Audio Analysis (Single URL Mode)")
83
-
84
- file_url = gr.Textbox(label="Audio File URL (single)")
85
- user_id = gr.Textbox(label="User ID")
86
-
87
- analyze_btn = gr.Button("Analyze Audio")
88
-
89
- output_summary = gr.Textbox(label="Summary")
90
- output_json = gr.Textbox(label="JSON Output")
91
- output_pdf = gr.Textbox(label="PDF Path")
92
 
93
- analyze_btn.click(
94
- fn=process_audio,
95
- inputs=[file_url, user_id],
96
- outputs=[output_summary, output_json, output_pdf],
97
- api_name="analyze_single_audio"
98
- )
 
99
 
100
  if __name__ == "__main__":
101
- demo.launch(server_port=7860, server_name="0.0.0.0")
 
1
+ from flask import Flask, request, jsonify, send_file
2
  import os
3
  import uuid
4
+ import requests
5
  import json
 
 
 
 
6
  from process_interview import process_interview
7
+ from urllib.parse import urlparse
 
 
 
8
 
9
+ app = Flask(__name__)
 
 
10
 
11
+ # Create folders to store the files
12
+ OUTPUT_DIR = "./processed_audio"
13
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
14
 
15
+ @app.route("/process-audio", methods=["POST"])
16
+ def process_audio():
17
  try:
18
+ data = request.json
19
+ user_id = data.get("user_id")
20
+ audio_url = data.get("audio_url")
 
 
 
21
 
22
+ if not user_id or not audio_url:
23
+ return jsonify({"error": "Missing user_id or audio_url"}), 400
 
 
 
 
24
 
25
+ # Generate unique filename per user
26
+ file_ext = os.path.splitext(urlparse(audio_url).path)[1]
27
+ filename = f"{user_id}_{uuid.uuid4()}{file_ext}"
28
+ local_file_path = os.path.join(OUTPUT_DIR, filename)
 
29
 
30
+ # Download the audio file
31
+ response = requests.get(audio_url, stream=True)
32
+ if response.status_code != 200:
33
+ return jsonify({"error": "Failed to download audio file"}), 400
34
 
35
+ with open(local_file_path, "wb") as f:
36
+ for chunk in response.iter_content(chunk_size=8192):
37
+ f.write(chunk)
38
 
39
+ # Call your processing pipeline
40
+ result = process_interview(local_file_path)
 
 
41
 
42
+ if not result or 'pdf_path' not in result or 'json_path' not in result:
43
+ return jsonify({"error": "Processing failed"}), 500
 
44
 
45
+ # Return file URLs (assuming you deploy this API somewhere publicly)
46
+ server_url = request.host_url.rstrip('/')
47
+ pdf_url = f"{server_url}/download?file={os.path.basename(result['pdf_path'])}"
48
+ json_url = f"{server_url}/download?file={os.path.basename(result['json_path'])}"
 
 
 
 
 
49
 
50
+ return jsonify({
51
+ "message": "Processing complete",
52
+ "pdf_url": pdf_url,
53
+ "json_url": json_url
54
+ })
55
 
56
  except Exception as e:
57
+ return jsonify({"error": str(e)}), 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
+ @app.route("/download", methods=["GET"])
60
+ def download_file():
61
+ filename = request.args.get("file")
62
+ file_path = os.path.join(OUTPUT_DIR, filename)
63
+ if not os.path.exists(file_path):
64
+ return jsonify({"error": "File not found"}), 404
65
+ return send_file(file_path, as_attachment=True)
66
 
67
  if __name__ == "__main__":
68
+ app.run(host="0.0.0.0", port=5000)