cdcvd commited on
Commit
7f6aa65
·
verified ·
1 Parent(s): 2e4101d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +388 -48
app.py CHANGED
@@ -1,64 +1,404 @@
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
27
 
28
- response = ""
 
 
 
 
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
 
 
 
 
 
38
 
39
- response += token
40
- yield response
 
41
 
 
 
 
 
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
 
63
  if __name__ == "__main__":
64
  demo.launch()
 
1
+ import os
2
+ import uuid
3
+ from langchain.chat_models import ChatOpenAI
4
+ from langchain.prompts import PromptTemplate
5
+ from langchain.memory import ConversationBufferMemory
6
+ from langchain.schema import SystemMessage, HumanMessage, AIMessage
7
+ from openai import OpenAI
8
+ from pydub import AudioSegment
9
+ from pydub.exceptions import CouldntDecodeError
10
  import gradio as gr
11
+ import azure.cognitiveservices.speech as speechsdk # اضافه شده
12
+ import tempfile
13
+ # تنظیمات کلیدهای API
14
+ HUGGINGFACE_API_KEY = os.getenv("HUGGINGFACE_API_KEY")
15
 
16
+ AZURE_SPEECH_API_KEY="e1b8c7909ed5488fad1c92b2bb499fcb"
17
+ AZURE_SPEECH_REGION="eastus"
18
+ AZURE_SPEECH_VOICE_NAME="fa-IR-FaridNeural" # مثلاً "fa-IR-FaridNeural"
 
19
 
20
+ # اطمینان از تنظیم بودن کلیدهای API
21
 
 
 
 
 
 
 
 
 
 
22
 
23
+ os.environ["TOGETHER_API_KEY"] = "569f8449a21864e866504d563ac3e34835e48ce36665a9acd890d049fe14c024"
 
 
 
 
24
 
25
+ from langchain_together import ChatTogether
26
 
27
+ llm = ChatTogether(
28
+ model="meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo",
29
+ temperature=1,
30
+ max_tokens=None,
31
+ timeout=None,
32
+ max_retries=2,
33
+ # other params...
34
+ )
35
 
36
+ prompt_template ="""
37
+ شما یک دکتر و کارشناس تغذیه به نام دکتر مهرشاد بنت یعقوب هستید شما با گرفتن اطلاعاتی از بیمار به انها رژیم مد نظر و مناسب انهار را تجویز می کنید
38
+ تمام این موارد با توجه به سر فصل از بیمار میپرسی تک به تک و دونه دونه
39
+ مشخصات فردی **
40
+ نام و نام خانوادگی:
41
+ جنسیت :
42
+ سن :
43
+ شغل :
44
+ مشخصات تن سنجی **
45
+ وزن :
46
+ قد :
47
+ دور کمر :
48
+ دور باسن :
49
 
50
+ سوالات مربوط به فعالبت بدنی :**
51
+ میزان فعالیت کدام هست : کم متوسط زیاد
52
+ آیا فعالیت ورزشی دارید؟ بلی / خیر
53
 
54
+ نوع فعالیت ورزشی :
55
+ مدت و زمان فعالیت :
56
+ آیا تا به حال رژیم غذایی گرفته اید؟ زیر نظر چه کسی؟ به چه مدت؟ در انجام رژیم موفق بوده اید؟
57
+ آیا تا به حال از دستگاه کمک لاغری استفاده کرده اید؟
58
 
59
+ بیماری های زمینه ای :**
60
+ آزمایش خون ؟
61
+ مشکلات گوارشی : نفخ
62
+ یبوست ریفلاکس بی اشتهایی / پر اشتهایی
63
+
64
+ داروها / مکمل های مصرفی :
65
+
66
+ آلرژی ، تمایلات و عدم تمایلات غذایی :
67
+
68
+ آیا به ماده غذایی خاصی آلرژی یا حساسیت دارید؟ بله / خیر
69
+
70
+ تنفرات و عدم تمایلات غذایی ؟
71
+ به کدام ماده یا مواد غذایی تمایل زیادی دارید و بیش از اندازه مصرف میکنید؟
72
+ بررسی الگوی غذای روزانه :***
73
+ مصرف صبحانه ؟ همیشه اغلب گاهی به ندرت اصلا
74
+
75
+ معمولا صبحانه چه میخورید؟ چه مقدار ؟
76
+
77
+ میان وعده چه میخورید ؟ چه مقدار؟
78
+
79
+ مصرف میزان نان یا برنج در ناهار چه مقدار است؟
80
+
81
+ مصرف میان وعده عصر؟
82
+ شام؟
83
+
84
+ وعده ی قبل از خواب؟
85
+
86
+ چه زمان از روز بیشتر احساس گرسنگی میکنید؟
87
+
88
+ عادات غذایی :***
89
+ مصرف فست فودها و غذاهای سرخ کردنی؟
90
+ میزان مصرف سبزیجات ؟ لبنیات ؟ میوه ؟ در طول روز
91
+ تمایل به شرینیجات / شکلات / کیک / بیسکوییت و ..... ؟
92
+ به چه میزان ریزه خواری دارید و به غذا ناخنک میزنید؟
93
+
94
+ تاریخچه مکالمه:
95
+ {chat_history}
96
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
+ # ایجاد Prompt
99
+ prompt = PromptTemplate(template=prompt_template, input_variables=["chat_history"])
100
+
101
+ # حافظه مکالمه
102
+ memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
103
+
104
+ # متغیر برای ذخیره متن شغلی
105
+ job_description = ""
106
+ job_description_confirmed = False
107
+
108
+ # تابع برای تبدیل تاریخچه مکالمه به رشته
109
+ def get_chat_history_string(chat_memory):
110
+ history = ""
111
+ for msg in chat_memory.messages:
112
+ if isinstance(msg, HumanMessage):
113
+ history += f"کارفرما: {msg.content}\n"
114
+ elif isinstance(msg, AIMessage):
115
+ history += f"دستیار: {msg.content}\n"
116
+ return history
117
+
118
+ # تابع تبدیل متن به گفتار با استفاده از Azure Speech SDK
119
+ def synthesize_speech(text):
120
+ try:
121
+ speech_config = speechsdk.SpeechConfig(subscription=AZURE_SPEECH_API_KEY, region=AZURE_SPEECH_REGION)
122
+ speech_config.speech_synthesis_voice_name = AZURE_SPEECH_VOICE_NAME
123
+
124
+ # تنظیم فرمت خروجی صوتی
125
+ speech_config.set_speech_synthesis_output_format(
126
+ speechsdk.SpeechSynthesisOutputFormat.Audio48Khz192KBitRateMonoMp3
127
+ )
128
+
129
+ # تولید نام فایل موقت برای ذخیره صوت
130
+ voice_generate_path = f'{uuid.uuid4()}.mp3'
131
+ temp_voice_generate_path = os.path.join(os.getcwd(), voice_generate_path)
132
+
133
+ # تنظیم خروجی به فایل
134
+ audio_config = speechsdk.audio.AudioOutputConfig(filename=temp_voice_generate_path)
135
+
136
+ speech_synthesizer = speechsdk.SpeechSynthesizer(
137
+ speech_config=speech_config,
138
+ audio_config=audio_config
139
+ )
140
+
141
+ speech_synthesis_result = speech_synthesizer.speak_text_async(text).get()
142
+
143
+ if speech_synthesis_result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:
144
+ # خواندن داده‌های صوتی از فایل
145
+ with open(temp_voice_generate_path, "rb") as audio_file:
146
+ audio_data = audio_file.read()
147
+ # حذف فایل موقت
148
+ os.remove(temp_voice_generate_path)
149
+ return audio_data
150
+ else:
151
+ print("خطا در تبدیل متن به گفتار:", speech_synthesis_result.reason)
152
+ return None
153
+ except Exception as e:
154
+ print("خطا در تبدیل متن به گفتار:", e)
155
+ return None
156
+
157
+ # تابع اصلی برای مدیریت مکالمه
158
+ def agent_respond(message):
159
+ global job_description, job_description_confirmed
160
+
161
+ # به‌روزرسانی حافظه با پیام کاربر
162
+ memory.chat_memory.add_user_message(message)
163
+
164
+ # آماده‌سازی پیام‌ها برای LLM
165
+ messages = memory.chat_memory.messages.copy()
166
+
167
+ # اضافه کردن Prompt به عنوان پیام سیستم
168
+ system_prompt = prompt.format(chat_history=get_chat_history_string(memory.chat_memory))
169
+ messages.insert(0, SystemMessage(content=system_prompt))
170
+
171
+ # تولید پاسخ دستیار
172
+ response = llm(messages=messages)
173
+
174
+ # افزودن پاسخ دستیار به حافظه
175
+ memory.chat_memory.add_ai_message(response.content)
176
+
177
+ # بررسی اینکه آیا باید متن شغلی تولید شود
178
+ if not job_description_confirmed and "متن شغلی" in response.content.lower():
179
+ # تولید متن شغلی بر اساس مکالمه
180
+ jd_prompt = f"""
181
+ بر اساس مکالمه تا کنون، یک متن شغلی دقیق و حرفه‌ای برای موقعیت مورد نظر بنویسید. وظایف، مسئولیت‌ها، مهارت‌ها و هر جزئیات مرتبط دیگری که کارفرما ارائه داده است را شامل کنید.
182
+ مکالمه:
183
+ {get_chat_history_string(memory.chat_memory)}
184
+ """
185
+
186
+ # اضافه کردن Prompt به عنوان پیام سیستم
187
+ jd_messages = [
188
+ SystemMessage(content=jd_prompt)
189
+ ]
190
+
191
+ jd_response = llm(messages=jd_messages)
192
+ job_description = jd_response.content
193
+
194
+ # ارائه متن شغلی به کارفرما
195
+ confirmation_message = f"متن شغلی پیشنهادی به شرح زیر است:\n\n{job_description}\n\nلطفاً آن را بررسی کرده و بگویید آیا نیاز به تغیی�� دارد."
196
+ memory.chat_memory.add_ai_message(confirmation_message)
197
+ return confirmation_message
198
+
199
+ # بررسی بازخورد کارفرما درباره متن شغلی
200
+ if job_description and not job_description_confirmed:
201
+ if any(word in message.lower() for word in ["تغییر", "ویرایش", "به‌روزرسانی", "اصلاح"]):
202
+ # به‌روزرسانی متن شغلی بر اساس بازخورد کارفرما
203
+ update_prompt = f"""
204
+ کارفرما بازخورد زیر را درباره متن شغلی ارائه داده است:
205
+ "{message}"
206
+ لطفاً متن شغلی را بر این اساس به‌روزرسانی کنید.
207
+ متن شغلی اصلی:
208
+ {job_description}
209
+ """
210
+
211
+ # اضافه کردن Prompt به عنوان پیام سیستم
212
+ update_messages = [
213
+ SystemMessage(content=update_prompt)
214
+ ]
215
+
216
+ update_response = llm(messages=update_messages)
217
+ job_description = update_response.content
218
+
219
+ # ارائه متن شغلی به‌روزشده
220
+ updated_message = f"متن شغلی به‌روزرسانی‌شده به شرح زیر است:\n\n{job_description}\n\nآیا این مورد رضایت‌بخش است؟"
221
+ memory.chat_memory.add_ai_message(updated_message)
222
+ return updated_message
223
+ elif any(word in message.lower() for word in ["بله", "موافقم", "رضایت‌بخش است", "خوب است"]):
224
+ job_description_confirmed = True
225
+ final_message = "عالی! متن شغلی نهایی شد. از زمانی که اختصاص دادید متشکرم."
226
+ memory.chat_memory.add_ai_message(final_message)
227
+ return final_message
228
+
229
+ return response.content
230
+
231
+ import os
232
+ import uuid
233
+ from pydub import AudioSegment
234
+ from pydub.exceptions import CouldntDecodeError
235
+ import requests
236
+
237
+ # # مطمئن شوید که کلید API را به صورت امن نگهداری می‌کنید
238
+ # # به عنوان مثال، می‌توانید آن را به صورت متغیر محیطی ذخیره کنید
239
+ # HUGGINGFACE_API_KEY = os.getenv("HUGGINGFACE_API_KEY")
240
+
241
+ # API_URL = "https://api-inference.huggingface.co/models/openai/whisper-large"
242
+ # headers = {"Authorization": f"Bearer {HUGGINGFACE_API_KEY}"}
243
+
244
+ # def query(filename):
245
+ # with open(filename, "rb") as f:
246
+ # data = f.read()
247
+ # response = requests.post(API_URL, headers=headers, data=data)
248
+ # if response.status_code == 200:
249
+ # return response.json()
250
+ # else:
251
+ # return {"error": response.json()}
252
+
253
+ # def process_audio(audio):
254
+ # audio_file = open(audio, "rb")
255
+ # try:
256
+ # audio = AudioSegment.from_file(audio_file)
257
+ # except CouldntDecodeError:
258
+ # os.remove(audio)
259
+ # return "Unsupported audio format"
260
+
261
+ # # بررسی مدت زمان فایل صوتی
262
+ # duration_seconds = len(audio_file) / 1000.0 # مدت زمان به ثانیه
263
+ # if duration_seconds > 900:
264
+ # os.remove(audio)
265
+ # return "Audio file is too long"
266
+
267
+ # project_root = os.path.dirname(os.path.dirname(__file__))
268
+ # voice_id = str(uuid.uuid4())
269
+ # # تبدیل به فرمت WAV سازگار با Whisper
270
+ # whisper_path = f'{voice_id}.wav'
271
+ # whisper_voice_path = os.path.join(project_root, whisper_path)
272
+
273
+ # audio.export(whisper_voice_path, format='wav')
274
+
275
+ # # ارسال درخواست به API Hugging Face
276
+ # output = query(whisper_voice_path)
277
+
278
+ # # حذف فایل موقت
279
+ # os.remove(whisper_voice_path)
280
+
281
+ # if "error" in output:
282
+ # print("Error:", output["error"])
283
+ # return "Transcription failed"
284
+ # else:
285
+ # text_question = output.get("text", "")
286
+ # print("text_question =", text_question)
287
+ # return text_question
288
+
289
+ def process_audio(audio):
290
+ # باز کردن فایل صوتی ضبط‌شده
291
+ audio_file = open(audio, "rb")
292
+
293
+ # Load and convert the audio file
294
+ try:
295
+ audio = AudioSegment.from_file(audio_file)
296
+
297
+ except CouldntDecodeError:
298
+ os.remove(audio_file)
299
+ return "Unsupported audio format"
300
+
301
+ # Check duration
302
+ duration_seconds = len(audio) / 1000.0 # Duration in seconds
303
+ if duration_seconds > 900:
304
+ os.remove(whisper_voice_path)
305
+ return "Audio file is too long"
306
+
307
+ project_root = os.path.dirname(os.path.dirname(__file__))
308
+ voice_id = str(uuid.uuid4())
309
+ # Convert to WAV format compatible with Whisper
310
+ whisper_path = f'{voice_id}.wav'
311
+ whisper_voice_path = os.path.join(project_root, whisper_path)
312
+
313
+ audio.export(whisper_voice_path, format='wav')
314
+
315
+ client = OpenAI(api_key=OPENAI_API_KEY)
316
+
317
+ with open(whisper_voice_path, 'rb') as audio_file:
318
+ text_question = client.audio.transcriptions.create(model="whisper-1",
319
+ file=audio_file,
320
+ response_format="text",
321
+ language="fa")
322
+ # حذف فایل موقت
323
+ os.remove(whisper_voice_path)
324
+ print("text_question=", text_question)
325
+ return text_question
326
+
327
+
328
+
329
+ def clear_memory():
330
+ global job_description, job_description_confirmed
331
+ memory.chat_memory.clear()
332
+ job_description = ""
333
+ job_description_confirmed = False
334
+ return [], "", None ,None
335
+ # افزودن None برای خروجی صوتی
336
+
337
+ with gr.Blocks() as demo:
338
+ chatbot = gr.Chatbot(height=500)
339
+ msg = gr.Textbox(show_label=False, placeholder="Send Message")
340
+ audio_input = gr.Audio(sources="microphone", type="filepath",label="Audio voice to voice")
341
+ audio_output = gr.Audio(label="Assistant voice response") # افزودن کامپوننت صوتی برای خروجی
342
+ inputs=gr.Audio(sources="microphone", type="filepath",label="Audio voice to text")
343
+ with gr.Row():
344
+ submit_btn = gr.Button("send")
345
+ voice_btn = gr.Button("voice to voice")
346
+ clear_btn = gr.Button("clear_chat 🧹")
347
+ voice_btn1 = gr.Button("voice to text")
348
+ def fix_bidi_text(text):
349
+ RLE = '\u202B' # Right-To-Left Embedding
350
+ PDF = '\u202C' # Pop Directional Formatting
351
+ return f"{RLE}{text}{PDF}"
352
+
353
+ def respond(message, chat_history):
354
+ bot_response = agent_respond(message)
355
+ # Fix the text
356
+ fixed_message = fix_bidi_text(message)
357
+ fixed_bot_response = fix_bidi_text(bot_response)
358
+ chat_history.append((fixed_message, fixed_bot_response))
359
+
360
+ # تبدیل پاسخ به صوت
361
+ audio_data = synthesize_speech(bot_response)
362
+ return chat_history, "", audio_data # افزودن audio_data به خروجی
363
+
364
+ def response_voice(audio, chat_history):
365
+ if not audio:
366
+ return chat_history, "فایل صوتی ارائه نشده است.", None
367
+
368
+ # پردازش فایل صوتی و دریافت متن تبدیل‌شده
369
+ transcribed_text = process_audio(audio)
370
+
371
+ # دریافت پاسخ مدل با استفاده از متن تبدیل‌شده
372
+ bot_response = agent_respond(transcribed_text)
373
+
374
+ # اصلاح متن‌ها برای نمایش راست‌چین
375
+ fixed_user_message = fix_bidi_text(transcribed_text)
376
+
377
+ fixed_bot_response = fix_bidi_text(bot_response)
378
+
379
+ # افزودن پیام‌ها به تاریخچه چت
380
+ chat_history.append((fixed_user_message, fixed_bot_response))
381
+
382
+ # تبدیل پاسخ به صوت
383
+ audio_data = synthesize_speech(bot_response)
384
+ return chat_history, "", audio_data
385
+ # افزودن audio_data به خروجی
386
+ def response_voice1(audio, chat_history):
387
+ if not audio:
388
+ return chat_history, "No audio file provided."
389
+
390
+ # پردازش فایل صوتی
391
+ bot_response = process_audio(audio)
392
+ fixed_bot_response = fix_bidi_text(bot_response)
393
+ chat_history.append(("صدا ارسال شد", fixed_bot_response))
394
+ return chat_history, ""
395
+ submit_btn.click(respond, [msg, chatbot], [chatbot, msg, audio_output])
396
+ voice_btn.click(response_voice, [audio_input, chatbot], [chatbot, msg, audio_output])
397
+ voice_btn1.click(response_voice1, [inputs, chatbot], [chatbot, msg])
398
+
399
+ msg.submit(respond, [msg, chatbot], [chatbot, msg, audio_output])
400
+ clear_btn.click(clear_memory, inputs=None, outputs=[chatbot, msg, audio_output,audio_input])
401
 
402
+ # اجرای Gradio
403
  if __name__ == "__main__":
404
  demo.launch()