hamaylza commited on
Commit
e9ef209
Β·
verified Β·
1 Parent(s): 7ce1cd2

refactored real time audio pipeline

Browse files
Files changed (1) hide show
  1. stt_test.py +135 -113
stt_test.py CHANGED
@@ -1,58 +1,93 @@
1
- # -*- coding: utf-8 -*-
2
- """STT_test
 
 
3
 
4
- Automatically generated by Colab.
5
-
6
- Original file is located at
7
- https://colab.research.google.com/drive/1i4LcOMK0nHo5PE0tZKM-yCfxyGmv_sJa
8
- """
9
-
10
- # =========================
11
- # TabeebAI FULL PIPELINE (ONE CELL)
12
- # Speech β†’ Whisper β†’ Symptoms β†’ JSON β†’ Gradio + Batch
13
- # =========================
14
-
15
- !pip -q install groq pydub gradio
16
 
17
  import json
 
 
18
  from groq import Groq
19
- from pydub import AudioSegment
20
- from google.colab import files, userdata
21
  import gradio as gr
22
 
23
- # =========================
24
- # GROQ SETUP
25
- # =========================
26
  client = Groq(api_key=userdata.get("GROQ_API_KEY"))
27
- print("βœ” Groq Ready")
28
-
29
- # =========================
30
- # AUDIO CONVERT (M4A β†’ WAV)
31
- # =========================
32
- def convert_audio(file_path):
33
- audio = AudioSegment.from_file(file_path, format="m4a")
34
- wav_path = file_path.replace(".m4a", ".wav")
35
- audio.export(wav_path, format="wav")
36
- return wav_path
37
-
38
- # =========================
39
- # WHISPER TRANSCRIPTION
40
- # =========================
41
- def transcribe_audio(file_path):
42
- with open(file_path, "rb") as f:
43
- res = client.audio.transcriptions.create(
44
- file=(file_path, f.read()),
45
- model="whisper-large-v3-turbo"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  )
47
- return res.text
48
 
49
- # =========================
50
- # SYMPTOM EXTRACTION (SAFE JSON)
51
- # =========================
 
 
 
 
 
 
52
  def extract_symptoms(text):
53
 
 
 
 
54
  prompt = f"""
55
- Extract medical symptoms and return ONLY valid JSON.
 
 
 
 
 
 
 
 
56
 
57
  TEXT:
58
  {text}
@@ -61,95 +96,82 @@ FORMAT:
61
  {{
62
  "chief_complaint": "",
63
  "symptoms": [
64
- {{"name": "", "severity": "", "duration": ""}}
 
 
 
 
65
  ],
 
66
  "urgency": "low/medium/high",
67
- "language": ""
68
  }}
69
  """
70
 
71
- res = client.chat.completions.create(
72
- model="llama-3.3-70b-versatile",
73
- messages=[{"role": "user", "content": prompt}],
74
- temperature=0.2
75
- )
76
-
77
- output = res.choices[0].message.content
78
- output = output.replace("```json", "").replace("```", "").strip()
79
-
80
  try:
81
- return json.loads(output)
82
- except:
83
- return {"raw_output": output}
84
-
85
- # =========================
86
- # FULL PIPELINE (CORE ENGINE)
87
- # =========================
88
- def run_pipeline(file_name):
89
-
90
- wav = convert_audio(file_name)
91
- text = transcribe_audio(wav)
92
- analysis = extract_symptoms(text)
93
-
94
- return {
95
- "file": file_name,
96
- "transcript": text,
97
- "analysis": analysis
98
- }
99
 
100
- # =========================
101
- # BATCH PROCESS
102
- # =========================
103
- def batch_process(file_list):
104
 
105
- results = []
106
 
107
- for f in file_list:
108
- try:
109
- results.append(run_pipeline(f))
110
- except Exception as e:
111
- results.append({"file": f, "error": str(e)})
 
112
 
113
- return results
114
 
115
- # =========================
116
- # 🌐 GRADIO INTERFACE
117
- # =========================
118
- def gradio_run(file):
119
 
120
- result = run_pipeline(file.name)
 
 
121
 
122
  return (
123
- result["transcript"],
124
- json.dumps(result["analysis"], indent=2, ensure_ascii=False)
 
125
  )
126
 
127
- with gr.Blocks() as demo:
128
-
129
- gr.Markdown("# πŸ₯ TabeebAI - Speech β†’ Symptoms AI")
130
 
131
- file_input = gr.File(label="Upload M4A File")
 
 
 
132
 
133
- btn = gr.Button("Run Analysis πŸš€")
 
 
 
134
 
135
- transcript_box = gr.Textbox(label="Transcript")
136
- json_box = gr.Textbox(
137
- label="Symptoms JSON",
138
- lines=15,
139
- max_lines=30,
140
- show_copy_button=True
141
- )
142
-
143
- btn.click(gradio_run, file_input, [transcript_box, json_box])
144
-
145
- demo.launch(share=True)
146
 
147
- # =========================
148
- # OPTIONAL BATCH TEST (RUN AFTER UPLOAD)
149
- # =========================
150
- uploaded = files.upload()
151
- results = batch_process(uploaded.keys())
152
 
153
- print("\nβœ” FINAL OUTPUT:\n")
154
- print(json.dumps(results, indent=2, ensure_ascii=False))
 
 
 
 
155
 
 
 
 
 
 
1
+ # =========================================
2
+ # TabeebAI β€” FINAL STABLE VERSION without RAG
3
+ # Urdu Speech β†’ English Clinical Report
4
+ # =========================================
5
 
6
+ !pip -q install groq gradio soundfile numpy
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  import json
9
+ import tempfile
10
+ import soundfile as sf
11
  from groq import Groq
12
+ from google.colab import userdata
 
13
  import gradio as gr
14
 
15
+ # =========================================
16
+ # SETUP
17
+ # =========================================
18
  client = Groq(api_key=userdata.get("GROQ_API_KEY"))
19
+
20
+ print(" TabeebAI FINAL Version Ready")
21
+
22
+ # =========================================
23
+ # TRANSCRIPTION (FORCED URDU)
24
+ # =========================================
25
+ def transcribe_audio(audio):
26
+
27
+ if audio is None:
28
+ return "⚠️ No audio detected"
29
+
30
+ sr, data = audio
31
+
32
+ try:
33
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp:
34
+ sf.write(temp.name, data, sr)
35
+
36
+ with open(temp.name, "rb") as f:
37
+ response = client.audio.transcriptions.create(
38
+ file=f,
39
+ model="whisper-large-v3-turbo",
40
+ language="ur" # FORCE URDU
41
+ )
42
+
43
+ return response.text.strip()
44
+
45
+ except Exception as e:
46
+ return f" Transcription Error: {str(e)}"
47
+
48
+
49
+ # =========================================
50
+ # TRANSLATION (URDU β†’ ENGLISH)
51
+ # =========================================
52
+ def translate_to_english(text):
53
+
54
+ if not text or "Error" in text or "No audio" in text:
55
+ return text
56
+
57
+ try:
58
+ response = client.chat.completions.create(
59
+ model="llama-3.3-70b-versatile",
60
+ messages=[{
61
+ "role": "user",
62
+ "content": f"Translate the following Urdu medical text into clear English:\n{text}"
63
+ }],
64
+ temperature=0.1
65
  )
 
66
 
67
+ return response.choices[0].message.content.strip()
68
+
69
+ except Exception as e:
70
+ return f"Translation Error: {str(e)}"
71
+
72
+
73
+ # =========================================
74
+ # SYMPTOM EXTRACTION (ENGLISH ONLY)
75
+ # =========================================
76
  def extract_symptoms(text):
77
 
78
+ if not text or "Error" in text or "No audio" in text:
79
+ return {"error": text}
80
+
81
  prompt = f"""
82
+ You are a clinical AI assistant.
83
+
84
+ STRICT RULES:
85
+ - Input is translated into English
86
+ - Output MUST be ONLY in English
87
+ - Return ONLY valid JSON
88
+ - No explanations, no extra text
89
+
90
+ Extract structured medical symptoms.
91
 
92
  TEXT:
93
  {text}
 
96
  {{
97
  "chief_complaint": "",
98
  "symptoms": [
99
+ {{
100
+ "name": "",
101
+ "severity": "",
102
+ "duration": ""
103
+ }}
104
  ],
105
+ "possible_conditions": [],
106
  "urgency": "low/medium/high",
107
+ "language": "English"
108
  }}
109
  """
110
 
 
 
 
 
 
 
 
 
 
111
  try:
112
+ response = client.chat.completions.create(
113
+ model="llama-3.3-70b-versatile",
114
+ messages=[{"role": "user", "content": prompt}],
115
+ temperature=0.2
116
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
+ output = response.choices[0].message.content
119
+ output = output.replace("```json", "").replace("```", "").strip()
 
 
120
 
121
+ return json.loads(output)
122
 
123
+ except Exception as e:
124
+ return {
125
+ "error": "Parsing failed",
126
+ "details": str(e),
127
+ "raw_output": output if 'output' in locals() else ""
128
+ }
129
 
 
130
 
131
+ # =========================================
132
+ # FULL PIPELINE
133
+ # =========================================
134
+ def pipeline(audio):
135
 
136
+ transcript_urdu = transcribe_audio(audio)
137
+ english_text = translate_to_english(transcript_urdu)
138
+ analysis = extract_symptoms(english_text)
139
 
140
  return (
141
+ transcript_urdu,
142
+ english_text,
143
+ json.dumps(analysis, indent=2, ensure_ascii=False)
144
  )
145
 
 
 
 
146
 
147
+ # =========================================
148
+ # UI (AUTO TRIGGER β€” NO BUTTON BUG)
149
+ # =========================================
150
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
151
 
152
+ gr.Markdown("""
153
+ # πŸ₯ TabeebAI β€” Clinical Voice AI
154
+ 🎀 Speak in Urdu β†’ AI gives English Medical Report
155
+ """)
156
 
157
+ audio_input = gr.Audio(
158
+ sources=["microphone"],
159
+ type="numpy",
160
+ label="🎀 Speak in Urdu"
161
+ )
 
 
 
 
 
 
162
 
163
+ transcript_box = gr.Textbox(label="πŸ“ Urdu Transcript", lines=5)
164
+ english_box = gr.Textbox(label="🌐 English Translation", lines=5)
165
+ json_box = gr.Textbox(label="🩺 Clinical JSON Output", lines=16)
 
 
166
 
167
+ # AUTO PROCESS AFTER RECORDING
168
+ audio_input.stop_recording(
169
+ fn=pipeline,
170
+ inputs=audio_input,
171
+ outputs=[transcript_box, english_box, json_box]
172
+ )
173
 
174
+ # =========================================
175
+ # LAUNCH
176
+ # =========================================
177
+ demo.launch(debug=True, share=True)