YoussefA7med commited on
Commit
9512144
·
verified ·
1 Parent(s): ccc23c4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +196 -249
app.py CHANGED
@@ -1,270 +1,217 @@
 
 
1
  import requests
2
  import json
3
  import random
4
- from gradio_client import Client
 
5
  import gradio as gr
6
- from dotenv import load_dotenv
7
- import os
8
- import tempfile
9
  import speech_recognition as sr
10
- import io
11
- import soundfile as sf
12
-
13
- # Load environment variables
14
- load_dotenv()
15
-
16
- # إعدادات API
17
- API_URL = "https://api.deepseek.com/v1/chat/completions"
18
- API_KEY = os.getenv("DEEPSEEK_API_KEY")
19
- HF_TOKEN = os.getenv("HUGGINGFACE_TOKEN")
20
-
21
- # إعداد TTS
22
- TTS_MODEL = os.getenv("TTS_MODEL", "KindSynapse/Youssef-Ahmed-Private-Text-To-Speech-Unlimited")
23
- TTS_CLIENT = Client(TTS_MODEL, hf_token=HF_TOKEN)
24
- TTS_PASSWORD = os.getenv("TTS_PASSWORD")
25
- TTS_VOICE = os.getenv("TTS_VOICE", "coral")
26
- TTS_SEED = int(os.getenv("TTS_SEED", "12345"))
27
-
28
- # إعداد Speech Recognition
29
- recognizer = sr.Recognizer()
30
-
31
- # التحقق من وجود المتغيرات المطلوبة
32
- required_env_vars = {
33
- "DEEPSEEK_API_KEY": API_KEY,
34
- "HUGGINGFACE_TOKEN": HF_TOKEN,
35
- "TTS_PASSWORD": TTS_PASSWORD
36
- }
37
 
38
- for var_name, var_value in required_env_vars.items():
39
- if not var_value:
40
- raise ValueError(f"Missing required environment variable: {var_name}")
41
 
42
- # البرومبت الرئيسي للشات بوت
43
- MAIN_SYSTEM_PROMPT = {
44
- "role": "system",
45
- "content": (
46
- "You are Sam, a friendly and encouraging English conversation tutor. "
47
- "Your responses must be in JSON with these keys: "
48
- "'response': Your main response to the user, "
49
- "'corrections': Grammar or pronunciation corrections if needed, "
50
- "'vocabulary': Suggested alternative words or phrases, "
51
- "'level': Assessment of user's English level (beginner/intermediate/advanced), "
52
- "'encouragement': A motivating comment. "
53
- "\n\nGuidelines:"
54
- "\n1. Adapt your language to their level"
55
- "\n2. Keep conversations natural and engaging"
56
- "\n3. Focus on their interests and context"
57
- "\n4. Be patient and supportive"
58
- "\n5. Provide gentle corrections"
59
- "\n6. Suggest vocabulary improvements naturally"
60
- "\n7. Keep responses clear and structured"
61
- )
62
- }
63
-
64
- # برومبت خاص بالترحيب (مختصر)
65
- WELCOME_SYSTEM_PROMPT = {
66
- "role": "system",
67
- "content": (
68
- "You are Sam, a friendly English tutor. Create a short, warm welcome message (2-3 sentences max) that: "
69
- "1) Introduces yourself briefly "
70
- "2) Asks for the user's name and what they'd like to practice. "
71
- "Make it casual and friendly. Return ONLY the greeting in JSON format with a single key 'greeting'."
72
- "Example: {'greeting': 'Hi! I'm Sam, your English buddy. What's your name and what would you like to practice today? 😊'}"
73
- )
74
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
- class EnglishTutor:
77
- def __init__(self):
78
- self.chat_history = []
79
- self.user_info = {
80
- "name": None,
81
- "level": None,
82
- "interests": None,
83
- "goals": None
84
- }
85
- # Initialize with welcome message
86
- self.chat_history = [MAIN_SYSTEM_PROMPT]
87
-
88
- def get_welcome_message(self):
89
- """توليد رسالة ترحيب فريدة"""
90
  response = requests.post(
91
- API_URL,
92
- headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
93
  json={
94
  "model": "deepseek-chat",
95
- "messages": [WELCOME_SYSTEM_PROMPT],
 
 
 
 
 
 
 
 
 
96
  "temperature": random.uniform(0.9, 1),
97
- "response_format": {"type": "json_object"}
98
  }
99
  )
100
- welcome_json = json.loads(response.json()["choices"][0]["message"]["content"])
101
- return welcome_json["greeting"]
102
 
103
- def get_bot_response(self, user_message):
104
- """معالجة رسالة المستخدم والحصول على رد"""
105
- self.chat_history.append({"role": "user", "content": user_message})
106
-
107
- response = requests.post(
108
- API_URL,
109
- headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
110
- json={
111
- "model": "deepseek-chat",
112
- "messages": self.chat_history,
113
- "temperature": random.uniform(0.9, 1.0),
114
- "response_format": {"type": "json_object"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  }
116
- )
117
-
118
- bot_message = response.json()["choices"][0]["message"]["content"]
119
- bot_json = json.loads(bot_message)
120
-
121
- # تحديث معلومات المستخدم إذا وجدت
122
- if "level" in bot_json:
123
- self.user_info["level"] = bot_json["level"]
124
-
125
- self.chat_history.append({"role": "assistant", "content": bot_message})
126
- return bot_json
127
-
128
- def text_to_speech(self, text):
129
- """تحويل نص إلى صوت مع مراعاة المبتدئين في اللغة الإنجليزية"""
130
- # تنظيف النص من أي علامات إضافية أو نصوص زائدة
131
- text = text.strip()
132
- if text.startswith('"') and text.endswith('"'):
133
- text = text[1:-1]
134
-
135
- tts_prompt = text
136
- tts_emotion = "Warm, encouraging, and clear with a friendly and supportive tone."
137
-
138
- return TTS_CLIENT.predict(
139
- password=TTS_PASSWORD,
140
- prompt=tts_prompt,
141
- voice=TTS_VOICE,
142
- emotion=tts_emotion,
143
- use_random_seed=True,
144
- specific_seed=TTS_SEED,
145
- api_name="/text_to_speech_app"
146
- )
147
-
148
- # Create a single instance of EnglishTutor
149
- tutor = EnglishTutor()
150
 
151
- def format_response(response_dict):
152
- """Format the response dictionary into a nice HTML string"""
153
- html = f"<div style='font-size: 16px;'>"
154
- html += f"<p>{response_dict['response']}</p>"
155
-
156
- if response_dict['corrections']:
157
- html += f"<p><b>✍️ Corrections:</b> {response_dict['corrections']}</p>"
158
-
159
- if response_dict['vocabulary']:
160
- html += f"<p><b>📚 Vocabulary:</b> {response_dict['vocabulary']}</p>"
161
-
162
- if response_dict['encouragement']:
163
- html += f"<p><b>🌟 Encouragement:</b> {response_dict['encouragement']}</p>"
164
-
165
- html += "</div>"
166
- return html
167
-
168
- def speech_to_text(audio_path):
169
- """Convert speech to text using speech_recognition"""
170
- try:
171
- # Load audio file
172
- with sr.AudioFile(audio_path) as source:
173
- # Record the audio file
174
- audio = recognizer.record(source)
175
- # Use Google Speech Recognition
176
- text = recognizer.recognize_google(audio)
177
- return text
178
  except Exception as e:
179
- print(f"Error in speech recognition: {str(e)}")
180
- return None
181
-
182
- def chat(audio, history):
183
- """Handle chat interactions"""
184
- if audio is None:
185
- # Return empty response if no audio
186
- return history, None
187
-
188
- # Convert audio to WAV format for speech recognition
189
- audio_data = audio[1] # Get the numpy array
190
- sample_rate = audio[0] # Get the sample rate
191
-
192
- # Save as temporary WAV file
193
- with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_wav:
194
- sf.write(temp_wav.name, audio_data, sample_rate)
195
- # Convert speech to text
196
- audio_text = speech_to_text(temp_wav.name)
197
-
198
- # Clean up temporary file
199
- os.unlink(temp_wav.name)
200
-
201
- if not audio_text:
202
- return history, None
203
-
204
- # Get bot response
205
- response = tutor.get_bot_response(audio_text)
206
-
207
- # Generate audio for the main response
208
- audio_path = tutor.text_to_speech(response["response"])[0]
209
-
210
- # Format the complete response
211
- formatted_response = format_response(response)
212
-
213
- # Update history in the correct format for gr.Chatbot
214
- history = history or []
215
- history.append((audio_text, formatted_response))
216
-
217
- return history, audio_path
218
-
219
- def show_welcome():
220
- """Show welcome message on startup"""
221
- welcome = tutor.get_welcome_message()
222
- audio_path = tutor.text_to_speech(welcome)[0]
223
- return [(None, welcome)], audio_path
224
 
225
- # Create Gradio interface
226
- with gr.Blocks(css="footer {display: none}") as demo:
227
- gr.Markdown("# 🤖 Sam - Your English Tutor")
228
- gr.Markdown("Welcome to your personalized English learning session! Click the microphone and start speaking!")
229
-
230
- chatbot = gr.Chatbot(
231
- show_label=False,
232
- height=400,
233
- type="messages"
234
- )
235
-
236
- with gr.Row():
237
- audio_input = gr.Audio(
238
- source="microphone",
239
- type="numpy",
240
- label="Speak here",
241
- show_label=True
242
- )
243
- audio_output = gr.Audio(
244
- label="Sam's Voice",
245
- show_label=True,
246
- type="filepath"
247
- )
248
-
249
- # Handle audio input
250
- audio_input.stop_recording(
251
- fn=chat,
252
- inputs=[audio_input, chatbot],
253
- outputs=[chatbot, audio_output],
254
- queue=False
255
- )
256
-
257
- # Show welcome message on page load
258
- demo.load_event(
259
- fn=show_welcome,
260
- inputs=None,
261
- outputs=[chatbot, audio_output]
262
- )
263
 
264
- # Launch the interface
265
  if __name__ == "__main__":
266
- demo.launch(
267
- server_name="0.0.0.0",
268
- server_port=7860,
269
- share=False
270
- )
 
1
+ import os
2
+ import uuid
3
  import requests
4
  import json
5
  import random
6
+ import re
7
+ from pydub import AudioSegment
8
  import gradio as gr
 
 
 
9
  import speech_recognition as sr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
+ def log_step(msg):
12
+ print(f"[EVAL_SPOKEN] {msg}")
 
13
 
14
+ def convert_to_wav(input_path, output_path=None):
15
+ if output_path is None:
16
+ output_path = os.path.join("uploads", f"converted_{uuid.uuid4()}.wav")
17
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
18
+ log_step(f"Converting audio from {input_path} to WAV format")
19
+ try:
20
+ audio = AudioSegment.from_file(input_path)
21
+ audio.export(output_path, format="wav")
22
+ log_step(f"Audio successfully converted to {output_path}")
23
+ return output_path
24
+ except Exception as e:
25
+ error_msg = f"Failed to convert audio: {e}"
26
+ log_step(f"ERROR in audio conversion: {error_msg}")
27
+ raise RuntimeError(error_msg)
28
+
29
+ def img_detector(model, url):
30
+ api_keys = [
31
+ os.getenv("OPENROUTER_API_KEY_1"),
32
+ os.getenv("OPENROUTER_API_KEY_2"),
33
+ os.getenv("OPENROUTER_API_KEY_3"),
34
+ os.getenv("OPENROUTER_API_KEY_4"),
35
+ ]
36
+ api_keys = [k for k in api_keys if k]
37
+ errors = []
38
+ for api_key in api_keys:
39
+ try:
40
+ response = requests.post(
41
+ url="https://openrouter.ai/api/v1/chat/completions",
42
+ headers={
43
+ "Authorization": f"Bearer {api_key}",
44
+ "Content-Type": "application/json",
45
+ },
46
+ data=json.dumps({
47
+ "model": model,
48
+ "messages": [
49
+ {
50
+ "role": "user",
51
+ "content": [
52
+ {"type": "text", "text": "What is appear in this image? Please provide a detailed description."},
53
+ {"type": "image_url", "image_url": {"url": url}}
54
+ ]
55
+ }
56
+ ]
57
+ })
58
+ )
59
+ if response.status_code == 200:
60
+ data = response.json()
61
+ if 'choices' in data and len(data['choices']) > 0:
62
+ return data['choices'][0]['message']['content']
63
+ else:
64
+ errors.append(f"API key {api_key[:8]}...: No choices in response.")
65
+ else:
66
+ errors.append(f"API key {api_key[:8]}...: Status {response.status_code}")
67
+ except Exception as e:
68
+ errors.append(f"API key {api_key[:8]}...: Exception {e}")
69
+ return f"All VLM API requests failed: {' | '.join(errors)}"
70
+
71
+ def transcribe_audio(audio_path):
72
+ recognizer = sr.Recognizer()
73
+ with sr.AudioFile(audio_path) as source:
74
+ audio = recognizer.record(source)
75
+ try:
76
+ text = recognizer.recognize_google(audio, language='en-US')
77
+ return text
78
+ except sr.UnknownValueError:
79
+ return "Could not understand the audio."
80
+ except sr.RequestError as e:
81
+ return f"Could not request results; {e}"
82
+
83
+ def evaluate_spoken_english(vlm_description, transcript_input, lang="english"):
84
+ """
85
+ Evaluate spoken English based on a VLM image description and a transcript.
86
+ Returns a dict with feedback and scores.
87
+ """
88
+ DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
89
+ if not DEEPSEEK_API_KEY:
90
+ raise EnvironmentError("Missing DEEPSEEK_API_KEY in environment.")
91
+
92
+ prompt = f"""
93
+ You are an expert spoken English tutor evaluating learners' spoken English skills based on CEFR (Common European Framework of Reference for Languages) standards. Your evaluation must consider key criteria such as:
94
+
95
+ - Pronunciation and stress
96
+ - Fluency and rhythm
97
+ - Vocabulary range and appropriateness
98
+ - Coherence and structure
99
+ - Grammar (as inferred from the transcript)
100
+
101
+ Important: The transcript below has **no punctuation**, as it is auto-generated from speech. Focus on what can be evaluated reliably based on the content and structure.
102
+
103
+ The learner was shown the following image (described by a vision-language model):
104
+ ---
105
+ {vlm_description}
106
+ ---
107
+
108
+ Then the learner described the image by voice. This is the auto-generated transcript:
109
+ ---
110
+ {transcript_input}
111
+ ---
112
+
113
+ Please evaluate the learner’s spoken English and return a JSON response including:
114
+ 1. "relevance_score": Score out of 100 for how relevant the speech was to the image.
115
+ 2. "fluency_score": Score out of 100 for fluency and smoothness of speech.
116
+ 3. "pronunciation_feedback": Identify any pronunciation issues or common errors.
117
+ 4. "mistakes": A list of grammar or vocabulary issues inferred from the transcript.
118
+ 5. "corrected_transcript": A corrected version of the transcript with appropriate punctuation and grammar.
119
+ 6. "learning_level": Estimated CEFR level (A1–C2).
120
+ 7. "tips": Actionable learning advice tailored to the learner’s weaknesses.
121
+ 8. "highlight": Something strong or impressive in the learner’s speaking (e.g., good phrasing or word choice).
122
+ 9. "motivational_comment": A short, encouraging note to boost the learner’s confidence.
123
+
124
+ Respond in clean JSON format only.
125
+ """
126
 
127
+ try:
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  response = requests.post(
129
+ "https://api.deepseek.com/v1/chat/completions",
130
+ headers={"Authorization": f"Bearer {DEEPSEEK_API_KEY}"},
131
  json={
132
  "model": "deepseek-chat",
133
+ "messages": [
134
+ {
135
+ "role": "system",
136
+ "content": "You are a certified spoken English tutor helping learners improve pronunciation, fluency, and confidence. You follow CEFR guidelines and speak warmly to encourage learners."
137
+ },
138
+ {
139
+ "role": "user",
140
+ "content": prompt.strip()
141
+ }
142
+ ],
143
  "temperature": random.uniform(0.9, 1),
144
+ "max_tokens": 1500
145
  }
146
  )
 
 
147
 
148
+ if response.status_code == 200:
149
+ data = response.json()
150
+ if "choices" in data and len(data["choices"]) > 0:
151
+ content = data["choices"][0]["message"]["content"]
152
+ clean_json_text = re.sub(r"```json|```", "", content).strip()
153
+
154
+ try:
155
+ return json.loads(clean_json_text)
156
+ except json.JSONDecodeError as decode_err:
157
+ return {
158
+ "relevance_score": 0,
159
+ "fluency_score": 0,
160
+ "pronunciation_feedback": "N/A",
161
+ "mistakes": [],
162
+ "corrected_transcript": "N/A",
163
+ "learning_level": "Unknown",
164
+ "highlight": "N/A",
165
+ "motivational_comment": "N/A",
166
+ "tips": [f"Invalid JSON format: {str(decode_err)}", "Raw content:", clean_json_text]
167
+ }
168
+ else:
169
+ return {
170
+ "relevance_score": 0,
171
+ "fluency_score": 0,
172
+ "pronunciation_feedback": "N/A",
173
+ "mistakes": [],
174
+ "corrected_transcript": "N/A",
175
+ "learning_level": "Unknown",
176
+ "highlight": "N/A",
177
+ "motivational_comment": "N/A",
178
+ "tips": [f"API Error: {response.status_code}"]
179
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
  except Exception as e:
182
+ return {
183
+ "relevance_score": 0,
184
+ "fluency_score": 0,
185
+ "pronunciation_feedback": "N/A",
186
+ "mistakes": [],
187
+ "corrected_transcript": "N/A",
188
+ "learning_level": "Unknown",
189
+ "highlight": "N/A",
190
+ "motivational_comment": "N/A",
191
+ "tips": [f"Exception occurred: {str(e)}"]
192
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
 
194
+ def gradio_spoken_eval(image_url, audio_file, model="meta-llama/llama-3.2-11b-vision-instruct:free"):
195
+ log_step(f"Received image_url={image_url}, audio_file={audio_file}")
196
+ wav_path = convert_to_wav(audio_file)
197
+ transcript = transcribe_audio(wav_path)
198
+ log_step(f"Transcript: {transcript}")
199
+ vlm_desc = img_detector(model, image_url)
200
+ log_step(f"VLM Description: {vlm_desc}")
201
+ result = evaluate_spoken_english(vlm_desc, transcript)
202
+ return json.dumps(result, indent=2, ensure_ascii=False)
203
+
204
+ iface = gr.Interface(
205
+ fn=gradio_spoken_eval,
206
+ inputs=[
207
+ gr.Textbox(label="Image URL"),
208
+ gr.Audio(type="filepath", label="Audio File (any format)"),
209
+ gr.Dropdown(choices=["meta-llama/llama-3.2-11b-vision-instruct:free", "google/gemini-2.0-flash-exp:free"], value="meta-llama/llama-3.2-11b-vision-instruct:free", label="Vision Model")
210
+ ],
211
+ outputs=gr.Code(label="Evaluation JSON", language="json"),
212
+ title="Spoken English Evaluation",
213
+ description="Upload an image URL and an audio file describing the image. The system will transcribe your speech, analyze it, and return a detailed evaluation."
214
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
 
 
216
  if __name__ == "__main__":
217
+ iface.launch()