Roo-Kh commited on
Commit
57bfa8d
1 Parent(s): fafbdf7

Upload 8 files

Browse files
Files changed (7) hide show
  1. .gitignore +2 -0
  2. 1.wav +0 -0
  3. README.md +7 -6
  4. app.py +433 -0
  5. requirements.txt +6 -0
  6. sample_input.mp3 +0 -0
  7. test.py +16 -0
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ .env
2
+ lain halloween.png
1.wav ADDED
Binary file (317 kB). View file
 
README.md CHANGED
@@ -1,12 +1,13 @@
1
  ---
2
- title: Try Yestara
3
- emoji: 📊
4
  colorFrom: purple
5
- colorTo: purple
6
  sdk: gradio
7
- sdk_version: 4.1.2
8
  app_file: app.py
9
- pinned: false
 
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: MultiMed
3
+ emoji: ⚕️😷🦠
4
  colorFrom: purple
5
+ colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 4.0.2
8
  app_file: app.py
9
+ pinned: true
10
+ license: mit
11
  ---
12
 
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Welcome to Team Tonic's MultiMed
2
+
3
+ from gradio_client import Client
4
+ import os
5
+ import numpy as np
6
+ import base64
7
+ import gradio as gr
8
+ import requests
9
+ import json
10
+ import dotenv
11
+ from scipy.io.wavfile import write
12
+ import PIL
13
+ from openai import OpenAI
14
+ import time
15
+ dotenv.load_dotenv()
16
+
17
+ seamless_client = Client("facebook/seamless_m4t")
18
+
19
+
20
+
21
+
22
+ def process_speech(audio_input,input_language,target_language):
23
+ """
24
+ processing sound using seamless_m4t
25
+ """
26
+ time.sleep(2) # wait for the audio to be saved
27
+ print(f"audio : {audio_input}")
28
+ print(f"audio type : {type(audio_input)}")
29
+
30
+ try :
31
+ audio_name = f"{np.random.randint(0, 100)}.wav"
32
+ sr, data = audio_input
33
+ write(audio_name, sr, data.astype(np.int16))
34
+ audio_input = audio_name
35
+ except :
36
+ pass
37
+ out = seamless_client.predict(
38
+ "S2TT",
39
+ "file",
40
+ None,
41
+ audio_input, #audio_name
42
+ "",
43
+ input_language,# Use selected input language as the source language
44
+ input_language,# Use selected input language as the target language
45
+ api_name="/run",
46
+ )
47
+ out = out[1] # get the text
48
+ try :
49
+ return f"{out}"
50
+ except Exception as e :
51
+ return f"{e}"
52
+
53
+
54
+
55
+
56
+ def process_image(image) :
57
+ img_name = f"{np.random.randint(0, 100)}.jpg"
58
+ PIL.Image.fromarray(image.astype('uint8'), 'RGB').save(img_name)
59
+ image = open(img_name, "rb").read()
60
+ base64_image = base64_image = base64.b64encode(image).decode('utf-8')
61
+ openai_api_key = os.getenv('OPENAI_API_KEY')
62
+ # oai_org = os.getenv('OAI_ORG')
63
+
64
+ headers = {
65
+ "Content-Type": "application/json",
66
+ "Authorization": f"Bearer {openai_api_key}"
67
+ }
68
+
69
+ payload = {
70
+ "model": "gpt-4-vision-preview",
71
+ "messages": [
72
+ {
73
+ "role": "user",
74
+ "content": [
75
+ {
76
+ "type": "text",
77
+ "text": "You are clinical consultant discussion training cases with students at TonicUniversity. Assess and describe the photo in minute detail. Explain why each area or item in the photograph would be inappropriate to describe if required. Pay attention to anatomy, symptoms and remedies. Propose a course of action based on your assessment. Exclude any other commentary:"
78
+ },
79
+ {
80
+ "type": "image_url",
81
+ "image_url": {
82
+ "url": f"data:image/jpeg;base64,{base64_image}"
83
+ }
84
+ }
85
+ ]
86
+ }
87
+ ],
88
+ "max_tokens": 1200
89
+ }
90
+
91
+ response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)
92
+
93
+ try :
94
+ out = response.json()
95
+ out = out["choices"][0]["message"]["content"]
96
+
97
+ return out
98
+ except Exception as e :
99
+ return f"{e}"
100
+
101
+
102
+ def query_vectara(text):
103
+ user_message = text
104
+
105
+ # Read authentication parameters from the .env file
106
+ CUSTOMER_ID = os.getenv('CUSTOMER_ID')
107
+ CORPUS_ID = os.getenv('CORPUS_ID')
108
+ API_KEY = os.getenv('API_KEY')
109
+
110
+ # Define the headers
111
+ api_key_header = {
112
+ "customer-id": CUSTOMER_ID,
113
+ "x-api-key": API_KEY
114
+ }
115
+
116
+ # Define the request body in the structure provided in the example
117
+ request_body = {
118
+ "query": [
119
+ {
120
+ "query": user_message,
121
+ "queryContext": "",
122
+ "start": 1,
123
+ "numResults": 50,
124
+ "contextConfig": {
125
+ "charsBefore": 0,
126
+ "charsAfter": 0,
127
+ "sentencesBefore": 2,
128
+ "sentencesAfter": 2,
129
+ "startTag": "%START_SNIPPET%",
130
+ "endTag": "%END_SNIPPET%",
131
+ },
132
+ "rerankingConfig": {
133
+ "rerankerId": 272725718,
134
+ "mmrConfig": {
135
+ "diversityBias": 0.35
136
+ }
137
+ },
138
+ "corpusKey": [
139
+ {
140
+ "customerId": CUSTOMER_ID,
141
+ "corpusId": CORPUS_ID,
142
+ "semantics": 0,
143
+ "metadataFilter": "",
144
+ "lexicalInterpolationConfig": {
145
+ "lambda": 0
146
+ },
147
+ "dim": []
148
+ }
149
+ ],
150
+ "summary": [
151
+ {
152
+ "maxSummarizedResults": 5,
153
+ "responseLang": "auto",
154
+ "summarizerPromptName": "vectara-summary-ext-v1.2.0"
155
+ }
156
+ ]
157
+ }
158
+ ]
159
+ }
160
+
161
+ # Make the API request using Gradio
162
+ response = requests.post(
163
+ "https://api.vectara.io/v1/query",
164
+ json=request_body, # Use json to automatically serialize the request body
165
+ verify=True,
166
+ headers=api_key_header
167
+ )
168
+
169
+ if response.status_code == 200:
170
+ query_data = response.json()
171
+ if query_data:
172
+ sources_info = []
173
+
174
+ # Extract the summary.
175
+ summary = query_data['responseSet'][0]['summary'][0]['text']
176
+
177
+ # Iterate over all response sets
178
+ for response_set in query_data.get('responseSet', []):
179
+ # Extract sources
180
+ # Limit to top 5 sources.
181
+ for source in response_set.get('response', [])[:5]:
182
+ source_metadata = source.get('metadata', [])
183
+ source_info = {}
184
+
185
+ for metadata in source_metadata:
186
+ metadata_name = metadata.get('name', '')
187
+ metadata_value = metadata.get('value', '')
188
+
189
+ if metadata_name == 'title':
190
+ source_info['title'] = metadata_value
191
+ elif metadata_name == 'author':
192
+ source_info['author'] = metadata_value
193
+ elif metadata_name == 'pageNumber':
194
+ source_info['page number'] = metadata_value
195
+
196
+ if source_info:
197
+ sources_info.append(source_info)
198
+
199
+ result = {"summary": summary, "sources": sources_info}
200
+ return f"{json.dumps(result, indent=2)}"
201
+ else:
202
+ return "No data found in the response."
203
+ else:
204
+ return f"Error: {response.status_code}"
205
+
206
+
207
+ def convert_to_markdown(vectara_response_json):
208
+ vectara_response = json.loads(vectara_response_json)
209
+ if vectara_response:
210
+ summary = vectara_response.get('summary', 'No summary available')
211
+ sources_info = vectara_response.get('sources', [])
212
+
213
+ # Format the summary as Markdown
214
+ markdown_summary = f'**Summary:** {summary}\n\n'
215
+
216
+ # Format the sources as a numbered list
217
+ markdown_sources = ""
218
+ for i, source_info in enumerate(sources_info):
219
+ author = source_info.get('author', 'Unknown author')
220
+ title = source_info.get('title', 'Unknown title')
221
+ page_number = source_info.get('page number', 'Unknown page number')
222
+ markdown_sources += f"{i+1}. {title} by {author}, Page {page_number}\n"
223
+
224
+ return f"{markdown_summary}**Sources:**\n{markdown_sources}"
225
+ else:
226
+ return "No data found in the response."
227
+ # Main function to handle the Gradio interface logic
228
+
229
+
230
+ def process_and_query(text=None):
231
+ try:
232
+ # augment the prompt before feeding it to vectara
233
+ text = "the user asks the following to his health adviser " + text
234
+ # If an image is provided, process it with OpenAI and use the response as the text query for Vectara
235
+ # if image is not None:
236
+ # text = process_image(image)
237
+ # return "**Summary:** "+text
238
+ # if audio is not None:
239
+ # text = process_speech(audio)
240
+ # # augment the prompt before feeding it to vectara
241
+ # text = "the user asks the following to his health adviser " + text
242
+
243
+
244
+ # Now, use the text (either provided by the user or obtained from OpenAI) to query Vectara
245
+ vectara_response_json = query_vectara(text)
246
+ markdown_output = convert_to_markdown(vectara_response_json)
247
+ client = OpenAI()
248
+ prompt ="Answer in the same language, write it better, more understandable and shorter:"
249
+ markdown_output_final = markdown_output
250
+
251
+ completion = client.chat.completions.create(
252
+ model="gpt-3.5-turbo",
253
+ messages=[
254
+ {"role": "system", "content": prompt},
255
+ {"role": "user", "content": markdown_output_final}
256
+ ]
257
+ )
258
+ final_response= completion.choices[0].message.content
259
+ return final_response
260
+ except Exception as e:
261
+ return str(e)
262
+
263
+
264
+ # Define the Gradio interface
265
+ # iface = gr.Interface(
266
+ # fn=process_and_query,
267
+ # inputs=[
268
+ # gr.Textbox(label="Input Text"),
269
+ # gr.Image(label="Upload Image"),
270
+ # gr.Audio(label="talk in french",
271
+ # sources=["microphone"]),
272
+ # ],
273
+ # outputs=[gr.Markdown(label="Output Text")],
274
+ # title="👋🏻Welcome to ⚕🗣️😷MultiMed - Access Chat ⚕🗣️😷",
275
+ # description='''
276
+ # ### How To Use ⚕🗣️😷MultiMed⚕:
277
+ # #### 🗣️📝Interact with ⚕🗣️😷MultiMed⚕ in any language using audio or text!
278
+ # #### 🗣️📝 This is an educational and accessible conversational tool to improve wellness and sanitation in support of public health.
279
+ # #### 📚🌟💼 The knowledge base is composed of publicly available medical and health sources in multiple languages. We also used [Kelvalya/MedAware](https://huggingface.co/datasets/keivalya/MedQuad-MedicalQnADataset) that we processed and converted to HTML. The quality of the answers depends on the quality of the dataset, so if you want to see some data represented here, do [get in touch](https://discord.gg/GWpVpekp). You can also use 😷MultiMed⚕️ on your own data & in your own way by cloning this space. 🧬🔬🔍 Simply click here: <a style="display:inline-block" href="https://huggingface.co/spaces/TeamTonic/MultiMed?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a></h3>
280
+ # #### Join us : 🌟TeamTonic🌟 is always making cool demos! Join our active builder's🛠️community on 👻Discord: [Discord](https://discord.gg/GWpVpekp) On 🤗Huggingface: [TeamTonic](https://huggingface.co/TeamTonic) & [MultiTransformer](https://huggingface.co/MultiTransformer) On 🌐Github: [Polytonic](https://github.com/tonic-ai) & contribute to 🌟 [PolyGPT](https://github.com/tonic-ai/polygpt-alpha)"
281
+ # ''',
282
+ # theme='ParityError/Anime',
283
+ # examples=[
284
+ # ["What is the proper treatment for buccal herpes?"],
285
+ # ["Male, 40 presenting with swollen glands and a rash"],
286
+ # ["How does cellular metabolism work TCA cycle"],
287
+ # ["What special care must be provided to children with chicken pox?"],
288
+ # ["When and how often should I wash my hands ?"],
289
+ # ["بکل ہرپس کا صحیح علاج کیا ہے؟"],
290
+ # ["구강 헤르페스의 적절한 치료법은 무엇입니까?"],
291
+ # ["Je, ni matibabu gani sahihi kwa herpes ya buccal?"],
292
+ # ],
293
+ # )
294
+
295
+ welcome_message = """
296
+ # 👋🏻Welcome to ⚕🗣️😷MultiMed - Access Chat ⚕🗣️😷
297
+ ### How To Use ⚕🗣️😷MultiMed⚕:
298
+ #### 🗣️📝Interact with ⚕🗣️😷MultiMed⚕ in any language using audio or text!
299
+ #### 🗣️📝 This is an educational and accessible conversational tool to improve wellness and sanitation in support of public health.
300
+ #### 📚🌟💼 The knowledge base is composed of publicly available medical and health sources in multiple languages. We also used [Kelvalya/MedAware](https://huggingface.co/datasets/keivalya/MedQuad-MedicalQnADataset) that we processed and converted to HTML. The quality of the answers depends on the quality of the dataset, so if you want to see some data represented here, do [get in touch](https://discord.gg/GWpVpekp). You can also use 😷MultiMed⚕️ on your own data & in your own way by cloning this space. 🧬🔬🔍 Simply click here: <a style="display:inline-block" href="https://huggingface.co/spaces/TeamTonic/MultiMed?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a></h3>
301
+ #### Join us : 🌟TeamTonic🌟 is always making cool demos! Join our active builder's🛠️community on 👻Discord: [Discord](https://discord.gg/GWpVpekp) On 🤗Huggingface: [TeamTonic](https://huggingface.co/TeamTonic) & [MultiTransformer](https://huggingface.co/MultiTransformer) On 🌐Github: [Polytonic](https://github.com/tonic-ai) & contribute to 🌟 [PolyGPT](https://github.com/tonic-ai/polygpt-alpha)"
302
+ """
303
+
304
+
305
+ languages = [
306
+ "Afrikaans",
307
+ "Amharic",
308
+ "Modern Standard Arabic",
309
+ "Moroccan Arabic",
310
+ "Egyptian Arabic",
311
+ "Assamese",
312
+ "Asturian",
313
+ "North Azerbaijani",
314
+ "Belarusian",
315
+ "Bengali",
316
+ "Bosnian",
317
+ "Bulgarian",
318
+ "Catalan",
319
+ "Cebuano",
320
+ "Czech",
321
+ "Central Kurdish",
322
+ "Mandarin Chinese",
323
+ "Welsh",
324
+ "Danish",
325
+ "German",
326
+ "Greek",
327
+ "English",
328
+ "Estonian",
329
+ "Basque",
330
+ "Finnish",
331
+ "French",
332
+ "West Central Oromo",
333
+ "Irish",
334
+ "Galician",
335
+ "Gujarati",
336
+ "Hebrew",
337
+ "Hindi",
338
+ "Croatian",
339
+ "Hungarian",
340
+ "Armenian",
341
+ "Igbo",
342
+ "Indonesian",
343
+ "Icelandic",
344
+ "Italian",
345
+ "Javanese",
346
+ "Japanese",
347
+ "Kamba",
348
+ "Kannada",
349
+ "Georgian",
350
+ "Kazakh",
351
+ "Kabuverdianu",
352
+ "Halh Mongolian",
353
+ "Khmer",
354
+ "Kyrgyz",
355
+ "Korean",
356
+ "Lao",
357
+ "Lithuanian",
358
+ "Luxembourgish",
359
+ "Ganda",
360
+ "Luo",
361
+ "Standard Latvian",
362
+ "Maithili",
363
+ "Malayalam",
364
+ "Marathi",
365
+ "Macedonian",
366
+ "Maltese",
367
+ "Meitei",
368
+ "Burmese",
369
+ "Dutch",
370
+ "Norwegian Nynorsk",
371
+ "Norwegian Bokmål",
372
+ "Nepali",
373
+ "Nyanja",
374
+ "Occitan",
375
+ "Odia",
376
+ "Punjabi",
377
+ "Southern Pashto",
378
+ "Western Persian",
379
+ "Polish",
380
+ "Portuguese",
381
+ "Romanian",
382
+ "Russian",
383
+ "Slovak",
384
+ "Slovenian",
385
+ "Shona",
386
+ "Sindhi",
387
+ "Somali",
388
+ "Spanish",
389
+ "Serbian",
390
+ "Swedish",
391
+ "Swahili",
392
+ "Tamil",
393
+ "Telugu",
394
+ "Tajik",
395
+ "Tagalog",
396
+ "Thai",
397
+ "Turkish",
398
+ "Ukrainian",
399
+ "Urdu",
400
+ "Northern Uzbek",
401
+ "Vietnamese",
402
+ "Xhosa",
403
+ "Yoruba",
404
+ "Cantonese",
405
+ "Colloquial Malay",
406
+ "Standard Malay",
407
+ "Zulu"
408
+ ]
409
+
410
+
411
+ with gr.Blocks(theme='ParityError/Anime') as iface :
412
+ gr.Markdown(welcome_message)
413
+ with gr.Tab("text summarization"):
414
+ text_input = gr.Textbox(label="input text",lines=5)
415
+ text_output = gr.Markdown(label="output text")
416
+ text_button = gr.Button("process text")
417
+ with gr.Tab("image identification"):
418
+ image_input = gr.Image(label="upload image")
419
+ image_output = gr.Markdown(label="output text")
420
+ image_button = gr.Button("process image")
421
+ with gr.Tab("speech to text translation"):
422
+ with gr.Row():
423
+ input_language = gr.Dropdown(languages, label="input language",value="French",interactive=True)
424
+ target_language = gr.Dropdown(languages, label="target language",value="English",interactive=True)
425
+ audio_input = gr.Audio(label="speak",type="filepath",sources="microphone")
426
+ audio_output = gr.Markdown(label="output text")
427
+ audio_button = gr.Button("process audio")
428
+ text_button.click(process_and_query, inputs=text_input, outputs=text_output)
429
+ image_button.click(process_image, inputs=image_input, outputs=image_output)
430
+ audio_button.click(process_speech, inputs=[audio_input,input_language,target_language], outputs=audio_output)
431
+
432
+
433
+ iface.queue().launch(show_error=True,debug=True)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ python-dotenv
2
+ Pillow==10.0.1
3
+ scipy
4
+ openai==1.1.2
5
+ gradio==4.1.2
6
+ gradio_client==0.7.0
sample_input.mp3 ADDED
Binary file (10.3 kB). View file
 
test.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+
4
+ def process_speech(audio):
5
+ return f"""audio {audio}
6
+ type {type(audio)}"""
7
+
8
+
9
+ with gr.Blocks(theme='ParityError/Anime') as iface :
10
+ audio_input = gr.Audio(label="talk in french")
11
+ audio_output = gr.Markdown(label="output text")
12
+ audio_button = gr.Button("process audio")
13
+ audio_button.click(process_speech, inputs=audio_input, outputs=audio_output)
14
+
15
+
16
+ iface.launch(show_error=True)