Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,507 +1,3 @@
|
|
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 |
-
# from langchain_together import ChatTogether
|
14 |
-
# # تنظیمات کلیدهای API
|
15 |
-
# HUGGINGFACE_API_KEY = os.getenv("HUGGINGFACE_API_KEY")
|
16 |
-
|
17 |
-
|
18 |
-
# # اطمینان از تنظیم بودن کلیدهای API
|
19 |
-
|
20 |
-
|
21 |
-
# os.environ["TOGETHER_API_KEY"] = "e9e74dc49951281481f5c7ec603f867f55cfe5ef776a1459289974cbe5a4af11"
|
22 |
-
|
23 |
-
# from langchain_together import ChatTogether
|
24 |
-
|
25 |
-
# llm = ChatTogether(
|
26 |
-
# model="meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo",
|
27 |
-
# temperature=1,
|
28 |
-
# max_tokens=None,
|
29 |
-
# timeout=None,
|
30 |
-
# max_retries=2,
|
31 |
-
# # other params...
|
32 |
-
# )
|
33 |
-
|
34 |
-
# prompt_template ="""
|
35 |
-
# شما یک دکتر و کارشناس تغذیه به نام دکتر مهرشاد بنت یعقوب هستید شما با گرفتن اطلاعاتی از بیمار به انها رژیم مد نظر و مناسب انهار را تجویز می کنید
|
36 |
-
# تمام این موارد با توجه به سر فصل از بیمار میپرسی تک به تک و دونه دونه
|
37 |
-
# تمام این موارد رو به صورت سوال می کنی و تک به تک هر سوال شامل یکی از موارد باید باشد
|
38 |
-
# **مشخصات فردی**:
|
39 |
-
# 1.نام و نام خانوادگی
|
40 |
-
# 2.جنسیت
|
41 |
-
# 3.سن
|
42 |
-
# 4.شغل
|
43 |
-
|
44 |
-
# **مشخصات تن سنجی**:
|
45 |
-
# 1.وزن
|
46 |
-
# 2.قد
|
47 |
-
# 3.دور کمر
|
48 |
-
# 4.دور باسن
|
49 |
-
|
50 |
-
# **سوالات مربوط به فعالبت بدنی** :
|
51 |
-
# 1.میزان فعالیت کدام هست : کم متوسط زیاد
|
52 |
-
|
53 |
-
# 2.آیا فعالیت ورزشی دارید؟ بلی / خیر
|
54 |
-
|
55 |
-
# 3.نوع فعالیت ورزشی و مدت و زمان فعالیت که دارید در موردش توضیح دهید؟
|
56 |
-
|
57 |
-
# 4.آیا تا به حال رژیم غذایی گرفته اید؟ زیر نظر چه کسی؟ به چه مدت؟ در انجام رژیم موفق بوده اید؟
|
58 |
-
|
59 |
-
# 5.آیا تا به حال از دستگاه کمک لاغری استفاده کرده اید؟
|
60 |
-
|
61 |
-
# **بیماری های زمینه ای**:
|
62 |
-
|
63 |
-
# 1.آیا مشکلات گوارشی نظیر نفخ-ریفلاکس -یبوست-بی اشتهایی / پر اشتهایی دارید
|
64 |
-
|
65 |
-
# 2.داروها / مکمل های مصرفی که مصرف میکنید لطفا نام ببرید
|
66 |
-
|
67 |
-
# 3.اگر آلرژی ، تمایلات و عدم تمایلات غذایی دارید در موردش توضیح دهید
|
68 |
-
|
69 |
-
# 4.آیا به ماده غذایی خاصی آلرژی یا حساسیت دارید؟ بله / خیر
|
70 |
-
|
71 |
-
# 5.تنفرات و عدم تمایلات غذایی رو توضیح دهید
|
72 |
-
# 6.به کدام ماده یا مواد غذایی تمایل زیادی دارید و بیش از اندازه مصرف میکنید؟
|
73 |
-
|
74 |
-
# **بررسی الگوی غذای روزانه**:
|
75 |
-
# 1.مصرف صبحانه چطوری هست ؟ همیشه اغلب گاهی به ندرت اصلا
|
76 |
-
# 2.معمولا صبحانه چه میخورید؟ چه مقدار ؟
|
77 |
-
# 3.میان وعده چه میخورید ؟ چه مقدار؟
|
78 |
-
# 4.مصرف میزان نان یا برنج در ناهار چه مقدار است؟
|
79 |
-
# 5.مصرف میان وعده عصر؟
|
80 |
-
# 6.آیا شام میل میکنید ؟
|
81 |
-
# 7.آیا وعده ی قبل از خواب میل میکنید
|
82 |
-
# 8.چه زمان از روز بیشتر احساس گرسنگی میکنید؟
|
83 |
-
|
84 |
-
|
85 |
-
# **عادات غذایی**:
|
86 |
-
# 1.آیا فست فودها و غذاهای سرخ کردنی مصرف می کنید
|
87 |
-
# 2.میزان مصرف سبزیجات- لبنیات-میوه در طول روز چقدر هست
|
88 |
-
# 3.آیا به شرینیجات / شکلات / کیک / بیسکوییت تمایل دارید
|
89 |
-
# 4.به چه میزان ریزه خواری دارید و به غذا ناخنک میزنید؟
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
# **رژیم دادن **:
|
95 |
-
|
96 |
-
# در بخش اخر تو به کاربر رژیم مناسب میدی
|
97 |
-
|
98 |
-
# You are a professional nutritionist, and your task is to design a personalized and effective diet plan for the user based on the following information. The diet should be tailored to the user's personal, physical, and health characteristics. You will calculate the user's **BMR (Basal Metabolic Rate)** and **TDEE (Total Daily Energy Expenditure)** using the Harris-Benedict equation and then adjust the macronutrient distribution based on their goal (weight loss, weight maintenance, or muscle gain).
|
99 |
-
|
100 |
-
# ### Step 1: **Calculate BMR**
|
101 |
-
# For **men**:
|
102 |
-
# BMR = 88.362 + (13.397 × Weight in kg) + (4.799 × Height in cm) - (5.677 × Age)
|
103 |
-
|
104 |
-
# For **women**:
|
105 |
-
# BMR = 447.593 + (9.247 × Weight in kg) + (3.098 × Height in cm) - (4.330 × Age)
|
106 |
-
|
107 |
-
# ### Step 2: **Calculate TDEE (Total Daily Energy Expenditure)**
|
108 |
-
# To calculate TDEE, multiply the BMR by the activity level factor:
|
109 |
-
# - **Sedentary (little or no exercise)**: TDEE = BMR × 1.2
|
110 |
-
# - **Moderate Activity (moderate exercise/sports 3-5 days/week)**: TDEE = BMR × 1.55
|
111 |
-
# - **High Activity (intense exercise/sports 6-7 days/week)**: TDEE = BMR × 1.9
|
112 |
-
|
113 |
-
# ### Step 3: **Adjust Macronutrient Distribution based on the Goal**
|
114 |
-
|
115 |
-
# 1. **For Weight Loss (Caloric Deficit)**:
|
116 |
-
# - **Protein**: 2-2.5 grams per kg of body weight
|
117 |
-
# - **Carbohydrates**: 40-45% of total daily calories
|
118 |
-
# - **Fats**: 30-35% of total daily calories
|
119 |
-
|
120 |
-
# 2. **For Weight Maintenance**:
|
121 |
-
# - **Protein**: 1.5-2 grams per kg of body weight
|
122 |
-
# - **Carbohydrates**: 45-55% of total daily calories
|
123 |
-
# - **Fats**: 25-30% of total daily calories
|
124 |
-
|
125 |
-
# 3. **For Muscle Gain (Caloric Surplus)**:
|
126 |
-
# - **Protein**: 2-2.5 grams per kg of body weight
|
127 |
-
# - **Carbohydrates**: 50-60% of total daily calories
|
128 |
-
# - **Fats**: 20-25% of total daily calories
|
129 |
-
|
130 |
-
# ### Step 4: **Generate the Detailed Meal Plan**
|
131 |
-
# Based on the calculated TDEE and macronutrient distribution, provide a **daily meal plan** that includes:
|
132 |
-
|
133 |
-
# - **Total Daily Calories**: Include the daily calorie goal based on the TDEE and weight loss/maintenance/muscle gain target.
|
134 |
-
# - **Macronutrient Breakdown**: List the grams of protein, carbohydrates, and fats for each macronutrient.
|
135 |
-
# - **Meal Suggestions**: Offer breakfast, lunch, dinner, snacks, and post-dinner options with specific food items, portion sizes, and calorie distribution for each meal.
|
136 |
-
|
137 |
-
# ### User’s Information:
|
138 |
-
|
139 |
-
# - **Gender**: [Male/Female]
|
140 |
-
# - **Age**: [User's Age]
|
141 |
-
# - **Weight (kg)**: [User's Weight]
|
142 |
-
# - **Height (cm)**: [User's Height]
|
143 |
-
# - **Activity Level**: [Sedentary/Moderate/High]
|
144 |
-
# - **Goal**: [Weight Loss/Weight Maintenance/Muscle Gain]
|
145 |
-
|
146 |
-
# ### Example Output:
|
147 |
-
|
148 |
-
# **1. Calculate BMR:**
|
149 |
-
|
150 |
-
# For example, for a male user:
|
151 |
-
# BMR = 88.362 + (13.397 × 75) + (4.799 × 175) - (5.677 × 30)
|
152 |
-
|
153 |
-
# **2. Calculate TDEE:**
|
154 |
-
# Multiply BMR by the activity factor:
|
155 |
-
# - Sedentary (1.2), Moderate (1.55), High (1.9)
|
156 |
-
|
157 |
-
# **3. Macronutrient Breakdown:**
|
158 |
-
# For weight loss (Caloric Deficit):
|
159 |
-
# - Protein: 2 grams per kg body weight
|
160 |
-
# - Carbs: 40% of total calories
|
161 |
-
# - Fats: 30% of total calories
|
162 |
-
|
163 |
-
# Provide meal breakdown with specific examples of food items and portions.
|
164 |
-
|
165 |
-
|
166 |
-
# تاریخچه مکالمه:
|
167 |
-
# {chat_history}
|
168 |
-
# """
|
169 |
-
|
170 |
-
# # ایجاد Prompt
|
171 |
-
# prompt = PromptTemplate(template=prompt_template, input_variables=["chat_history"])
|
172 |
-
|
173 |
-
# # حافظه مکالمه
|
174 |
-
# memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
175 |
-
|
176 |
-
# # متغیر برای ذخیره متن شغلی
|
177 |
-
# job_description = ""
|
178 |
-
# job_description_confirmed = False
|
179 |
-
|
180 |
-
# # تابع برای تبدیل تاریخچه مکالمه به رشته
|
181 |
-
# def get_chat_history_string(chat_memory):
|
182 |
-
# history = ""
|
183 |
-
# for msg in chat_memory.messages:
|
184 |
-
# if isinstance(msg, HumanMessage):
|
185 |
-
# history += f"کارفرما: {msg.content}\n"
|
186 |
-
# elif isinstance(msg, AIMessage):
|
187 |
-
# history += f"دستیار: {msg.content}\n"
|
188 |
-
# return history
|
189 |
-
|
190 |
-
# # تابع تبدیل متن به گفتار با استفاده از Azure Speech SDK
|
191 |
-
# # def synthesize_speech(text):
|
192 |
-
# # try:
|
193 |
-
# # speech_config = speechsdk.SpeechConfig(subscription=AZURE_SPEECH_API_KEY, region=AZURE_SPEECH_REGION)
|
194 |
-
# # speech_config.speech_synthesis_voice_name = AZURE_SPEECH_VOICE_NAME
|
195 |
-
|
196 |
-
# # # تنظیم فرمت خروجی صوتی
|
197 |
-
# # speech_config.set_speech_synthesis_output_format(
|
198 |
-
# # speechsdk.SpeechSynthesisOutputFormat.Audio48Khz192KBitRateMonoMp3
|
199 |
-
# # )
|
200 |
-
|
201 |
-
# # # تولید نام فایل موقت برای ذخیره صوت
|
202 |
-
# # voice_generate_path = f'{uuid.uuid4()}.mp3'
|
203 |
-
# # temp_voice_generate_path = os.path.join(os.getcwd(), voice_generate_path)
|
204 |
-
|
205 |
-
# # # تنظیم خروجی به فایل
|
206 |
-
# # audio_config = speechsdk.audio.AudioOutputConfig(filename=temp_voice_generate_path)
|
207 |
-
|
208 |
-
# # speech_synthesizer = speechsdk.SpeechSynthesizer(
|
209 |
-
# # speech_config=speech_config,
|
210 |
-
# # audio_config=audio_config
|
211 |
-
# # )
|
212 |
-
|
213 |
-
# # speech_synthesis_result = speech_synthesizer.speak_text_async(text).get()
|
214 |
-
|
215 |
-
# # if speech_synthesis_result.reason == speechsdk.ResultReason.SynthesizingAudioCompleted:
|
216 |
-
# # # خواندن دادههای صوتی از فایل
|
217 |
-
# # with open(temp_voice_generate_path, "rb") as audio_file:
|
218 |
-
# # audio_data = audio_file.read()
|
219 |
-
# # # حذف فایل موقت
|
220 |
-
# # os.remove(temp_voice_generate_path)
|
221 |
-
# # return audio_data
|
222 |
-
# # else:
|
223 |
-
# # print("خطا در تبدیل متن به گفتار:", speech_synthesis_result.reason)
|
224 |
-
# # return None
|
225 |
-
# # except Exception as e:
|
226 |
-
# # print("خطا در تبدیل متن به گفتار:", e)
|
227 |
-
# # return None
|
228 |
-
# def get_model_response(messages):
|
229 |
-
# response = client.chat.completions.create(
|
230 |
-
# model="meta-llama/Llama-3.3-70B-Instruct-Turbo",
|
231 |
-
# messages=messages,
|
232 |
-
# max_tokens=1024,
|
233 |
-
# temperature=0.7,
|
234 |
-
# top_p=0.7,
|
235 |
-
# top_k=50,
|
236 |
-
# repetition_penalty=1,
|
237 |
-
# stop=["<|eot_id|>", "<|eom_id|>"],
|
238 |
-
# stream=False,
|
239 |
-
# )
|
240 |
-
# return response.choices[0].message["content"]
|
241 |
-
|
242 |
-
|
243 |
-
# تابع اصلی برای مدیریت مکالمه
|
244 |
-
# def agent_respond(message):
|
245 |
-
# global job_description, job_description_confirmed
|
246 |
-
|
247 |
-
# # بهروزرسانی حافظه با پیام کاربر
|
248 |
-
# memory.chat_memory.add_user_message(message)
|
249 |
-
|
250 |
-
# # آمادهسازی پیامها برای LLM
|
251 |
-
# messages = memory.chat_memory.messages.copy()
|
252 |
-
|
253 |
-
# # اضافه کردن Prompt به عنوان پیام سیستم
|
254 |
-
# system_prompt = prompt.format(chat_history=get_chat_history_string(memory.chat_memory))
|
255 |
-
# messages.insert(0, SystemMessage(content=system_prompt))
|
256 |
-
|
257 |
-
# # تولید پاسخ دستیار
|
258 |
-
# response = llm(messages=messages)
|
259 |
-
|
260 |
-
# # افزودن پاسخ دستیار به حافظه
|
261 |
-
# memory.chat_memory.add_ai_message(response.content)
|
262 |
-
|
263 |
-
# # بررسی اینکه آیا باید متن شغلی تولید شود
|
264 |
-
# if not job_description_confirmed and "متن شغلی" in response.content.lower():
|
265 |
-
# # تولید متن شغلی بر اساس مکالمه
|
266 |
-
# jd_prompt = f"""
|
267 |
-
# بر اساس مکالمه تا کنون، یک متن شغلی دقیق و حرفهای برای موقعیت مورد نظر بنویسید. وظایف، مسئولیتها، مهارتها و هر جزئیات مرتبط دیگری که کارفرما ارائه داده است را شامل کنید.
|
268 |
-
# مکالمه:
|
269 |
-
# {get_chat_history_string(memory.chat_memory)}
|
270 |
-
# """
|
271 |
-
|
272 |
-
# # اضافه کردن Prompt به عنوان پیام سیستم
|
273 |
-
# jd_messages = [
|
274 |
-
# SystemMessage(content=jd_prompt)
|
275 |
-
# ]
|
276 |
-
|
277 |
-
# jd_response = llm(messages=jd_messages)
|
278 |
-
# job_description = jd_response.content
|
279 |
-
|
280 |
-
# # ارائه متن شغلی به کارفرما
|
281 |
-
# confirmation_message = f"متن شغلی پیشنهادی به شرح زیر است:\n\n{job_description}\n\nلطفاً آن را بررسی کرده و بگویید آیا نیاز به تغییر دارد."
|
282 |
-
# memory.chat_memory.add_ai_message(confirmation_message)
|
283 |
-
# return confirmation_message
|
284 |
-
|
285 |
-
# # بررسی بازخورد کارفرما درباره متن شغلی
|
286 |
-
# if job_description and not job_description_confirmed:
|
287 |
-
# if any(word in message.lower() for word in ["تغییر", "ویرایش", "بهروزرسانی", "اصلاح"]):
|
288 |
-
# # بهروزرسانی متن شغلی بر اساس بازخورد کارفرما
|
289 |
-
# update_prompt = f"""
|
290 |
-
# کارفرما بازخورد زیر را درباره متن شغلی ارائه داده است:
|
291 |
-
# "{message}"
|
292 |
-
# لطفاً متن شغلی را بر این اساس بهروزرسانی کنید.
|
293 |
-
# متن شغلی اصلی:
|
294 |
-
# {job_description}
|
295 |
-
# """
|
296 |
-
|
297 |
-
# # اضافه کردن Prompt به عنوان پیام سیستم
|
298 |
-
# update_messages = [
|
299 |
-
# SystemMessage(content=update_prompt)
|
300 |
-
# ]
|
301 |
-
|
302 |
-
# update_response = llm(messages=update_messages)
|
303 |
-
# job_description = update_response.content
|
304 |
-
|
305 |
-
# # ارائه متن شغلی بهروزشده
|
306 |
-
# updated_message = f"متن شغلی بهروزرسانیشده به شرح زیر است:\n\n{job_description}\n\nآیا این مورد رضایتبخش است؟"
|
307 |
-
# memory.chat_memory.add_ai_message(updated_message)
|
308 |
-
# return updated_message
|
309 |
-
# elif any(word in message.lower() for word in ["بله", "موافقم", "رضایتبخش است", "خوب است"]):
|
310 |
-
# job_description_confirmed = True
|
311 |
-
# final_message = "عالی! متن شغلی نهایی شد. از زمانی که اختصاص دادید متشکرم."
|
312 |
-
# memory.chat_memory.add_ai_message(final_message)
|
313 |
-
# return final_message
|
314 |
-
|
315 |
-
# return response.content
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
# # def agent_respond(message, chat_history):
|
320 |
-
# # messages = [{"role": "user", "content": message}]
|
321 |
-
# # bot_response = get_model_response(messages)
|
322 |
-
# # chat_history.append((message, bot_response))
|
323 |
-
# # audio_response = synthesize_speech(bot_response)
|
324 |
-
# # return chat_history, "", audio_response
|
325 |
-
|
326 |
-
|
327 |
-
# import os
|
328 |
-
# import uuid
|
329 |
-
# from pydub import AudioSegment
|
330 |
-
# from pydub.exceptions import CouldntDecodeError
|
331 |
-
# import requests
|
332 |
-
|
333 |
-
# # # مطمئن شوید که کلید API را به صورت امن نگهداری میکنید
|
334 |
-
# # # به عنوان مثال، میتوانید آن را به صورت متغیر محیطی ذخیره کنید
|
335 |
-
# # HUGGINGFACE_API_KEY = os.getenv("HUGGINGFACE_API_KEY")
|
336 |
-
|
337 |
-
# # API_URL = "https://api-inference.huggingface.co/models/openai/whisper-large"
|
338 |
-
# # headers = {"Authorization": f"Bearer {HUGGINGFACE_API_KEY}"}
|
339 |
-
|
340 |
-
# # def query(filename):
|
341 |
-
# # with open(filename, "rb") as f:
|
342 |
-
# # data = f.read()
|
343 |
-
# # response = requests.post(API_URL, headers=headers, data=data)
|
344 |
-
# # if response.status_code == 200:
|
345 |
-
# # return response.json()
|
346 |
-
# # else:
|
347 |
-
# # return {"error": response.json()}
|
348 |
-
|
349 |
-
# # def process_audio(audio):
|
350 |
-
# # audio_file = open(audio, "rb")
|
351 |
-
# # try:
|
352 |
-
# # audio = AudioSegment.from_file(audio_file)
|
353 |
-
# # except CouldntDecodeError:
|
354 |
-
# # os.remove(audio)
|
355 |
-
# # return "Unsupported audio format"
|
356 |
-
|
357 |
-
# # # بررسی مدت زمان فایل صوتی
|
358 |
-
# # duration_seconds = len(audio_file) / 1000.0 # مدت زمان به ثانیه
|
359 |
-
# # if duration_seconds > 900:
|
360 |
-
# # os.remove(audio)
|
361 |
-
# # return "Audio file is too long"
|
362 |
-
|
363 |
-
# # project_root = os.path.dirname(os.path.dirname(__file__))
|
364 |
-
# # voice_id = str(uuid.uuid4())
|
365 |
-
# # # تبدیل به فرمت WAV سازگار با Whisper
|
366 |
-
# # whisper_path = f'{voice_id}.wav'
|
367 |
-
# # whisper_voice_path = os.path.join(project_root, whisper_path)
|
368 |
-
|
369 |
-
# # audio.export(whisper_voice_path, format='wav')
|
370 |
-
|
371 |
-
# # # ارسال درخواست به API Hugging Face
|
372 |
-
# # output = query(whisper_voice_path)
|
373 |
-
|
374 |
-
# # # حذف فایل موقت
|
375 |
-
# # os.remove(whisper_voice_path)
|
376 |
-
|
377 |
-
# # if "error" in output:
|
378 |
-
# # print("Error:", output["error"])
|
379 |
-
# # return "Transcription failed"
|
380 |
-
# # else:
|
381 |
-
# # text_question = output.get("text", "")
|
382 |
-
# # print("text_question =", text_question)
|
383 |
-
# # return text_question
|
384 |
-
|
385 |
-
# # def process_audio(audio):
|
386 |
-
# # # باز کردن فایل صوتی ضبطشده
|
387 |
-
# # audio_file = open(audio, "rb")
|
388 |
-
|
389 |
-
# # # Load and convert the audio file
|
390 |
-
# # try:
|
391 |
-
# # audio = AudioSegment.from_file(audio_file)
|
392 |
-
|
393 |
-
# # except CouldntDecodeError:
|
394 |
-
# # os.remove(audio_file)
|
395 |
-
# # return "Unsupported audio format"
|
396 |
-
|
397 |
-
# # # Check duration
|
398 |
-
# # duration_seconds = len(audio) / 1000.0 # Duration in seconds
|
399 |
-
# # if duration_seconds > 900:
|
400 |
-
# # os.remove(whisper_voice_path)
|
401 |
-
# # return "Audio file is too long"
|
402 |
-
|
403 |
-
# # project_root = os.path.dirname(os.path.dirname(__file__))
|
404 |
-
# # voice_id = str(uuid.uuid4())
|
405 |
-
# # # Convert to WAV format compatible with Whisper
|
406 |
-
# # whisper_path = f'{voice_id}.wav'
|
407 |
-
# # whisper_voice_path = os.path.join(project_root, whisper_path)
|
408 |
-
|
409 |
-
# # audio.export(whisper_voice_path, format='wav')
|
410 |
-
|
411 |
-
# # client = OpenAI(api_key=OPENAI_API_KEY)
|
412 |
-
|
413 |
-
# # with open(whisper_voice_path, 'rb') as audio_file:
|
414 |
-
# # text_question = client.audio.transcriptions.create(model="whisper-1",
|
415 |
-
# # file=audio_file,
|
416 |
-
# # response_format="text",
|
417 |
-
# # language="fa")
|
418 |
-
# # # حذف فایل موقت
|
419 |
-
# # os.remove(whisper_voice_path)
|
420 |
-
# # print("text_question=", text_question)
|
421 |
-
# # return text_question
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
# def clear_memory():
|
426 |
-
# global job_description, job_description_confirmed
|
427 |
-
# memory.chat_memory.clear()
|
428 |
-
# job_description = ""
|
429 |
-
# job_description_confirmed = False
|
430 |
-
# return [], "", None ,None
|
431 |
-
# # افزودن None برای خروجی صوتی
|
432 |
-
|
433 |
-
# with gr.Blocks() as demo:
|
434 |
-
# chatbot = gr.Chatbot(height=500)
|
435 |
-
# msg = gr.Textbox(show_label=False, placeholder="Send Message")
|
436 |
-
# # audio_input = gr.Audio(sources="microphone", type="filepath",label="Audio voice to voice")
|
437 |
-
# # audio_output = gr.Audio(label="Assistant voice response") # افزودن کامپوننت صوتی برای خروجی
|
438 |
-
# # inputs=gr.Audio(sources="microphone", type="filepath",label="Audio voice to text")
|
439 |
-
# with gr.Row():
|
440 |
-
# submit_btn = gr.Button("send")
|
441 |
-
# # voice_btn = gr.Button("voice to voice")
|
442 |
-
# clear_btn = gr.Button("clear_chat 🧹")
|
443 |
-
# # voice_btn1 = gr.Button("voice to text")
|
444 |
-
# def fix_bidi_text(text):
|
445 |
-
# RLE = '\u202B' # Right-To-Left Embedding
|
446 |
-
# PDF = '\u202C' # Pop Directional Formatting
|
447 |
-
# return f"{RLE}{text}{PDF}"
|
448 |
-
|
449 |
-
# def respond(message, chat_history):
|
450 |
-
# bot_response = agent_respond(message)
|
451 |
-
# # Fix the text
|
452 |
-
# fixed_message = fix_bidi_text(message)
|
453 |
-
# fixed_bot_response = fix_bidi_text(bot_response)
|
454 |
-
# chat_history.append((fixed_message, fixed_bot_response))
|
455 |
-
|
456 |
-
# # تبدیل پاسخ به صوت
|
457 |
-
# # audio_data = synthesize_speech(bot_response)
|
458 |
-
# return chat_history, "" # افزودن audio_data به خروجی
|
459 |
-
|
460 |
-
# # def response_voice(audio, chat_history):
|
461 |
-
# # if not audio:
|
462 |
-
# # return chat_history, "فایل صوتی ارائه نشده است.", None
|
463 |
-
|
464 |
-
# # # پردازش فایل صوتی و دریافت متن تبدیلشده
|
465 |
-
# # transcribed_text = process_audio(audio)
|
466 |
-
|
467 |
-
# # # دریافت پاسخ مدل با استفاده از متن تبدیلشده
|
468 |
-
# # bot_response = agent_respond(transcribed_text)
|
469 |
-
|
470 |
-
# # # اصلاح متنها برای نمایش راستچین
|
471 |
-
# # fixed_user_message = fix_bidi_text(transcribed_text)
|
472 |
-
|
473 |
-
# # fixed_bot_response = fix_bidi_text(bot_response)
|
474 |
-
|
475 |
-
# # # افزودن پیامها به تاریخچه چت
|
476 |
-
# # chat_history.append((fixed_user_message, fixed_bot_response))
|
477 |
-
|
478 |
-
# # # تبدیل پاسخ به صوت
|
479 |
-
# # audio_data = synthesize_speech(bot_response)
|
480 |
-
# # return chat_history, "", audio_data
|
481 |
-
# # # افزودن audio_data به خروجی
|
482 |
-
# # def response_voice1(audio, chat_history):
|
483 |
-
# # if not audio:
|
484 |
-
# # return chat_history, "No audio file provided."
|
485 |
-
|
486 |
-
# # # پردازش فایل صوتی
|
487 |
-
# # bot_response = process_audio(audio)
|
488 |
-
# # fixed_bot_response = fix_bidi_text(bot_response)
|
489 |
-
# # chat_history.append(("صدا ارسال شد", fixed_bot_response))
|
490 |
-
# # return chat_history, ""
|
491 |
-
# submit_btn.click(respond, [msg, chatbot], [chatbot, msg])
|
492 |
-
# # voice_btn.click(response_voice, [audio_input, chatbot], [chatbot, msg, audio_output])
|
493 |
-
# # voice_btn1.click(response_voice1, [inputs, chatbot], [chatbot, msg])
|
494 |
-
|
495 |
-
# msg.submit(respond, [msg, chatbot], [chatbot, msg])
|
496 |
-
# clear_btn.click(clear_memory, inputs=None, outputs=[chatbot, msg])
|
497 |
-
|
498 |
-
# # اجرای Gradio
|
499 |
-
# if __name__ == "__main__":
|
500 |
-
# demo.launch()
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
import os
|
506 |
import gradio as gr
|
507 |
from together import Together
|
@@ -509,9 +5,6 @@ from langchain.prompts import PromptTemplate
|
|
509 |
from langchain.memory import ConversationBufferMemory
|
510 |
from langchain.schema import SystemMessage, HumanMessage, AIMessage
|
511 |
|
512 |
-
# تنظیمات کلیدهای API
|
513 |
-
# OPENAI_API_KEY = os.getenv("OPENAI_API_KEY1")
|
514 |
-
# os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
|
515 |
os.environ["TOGETHER_API_KEY"] = "e9e74dc49951281481f5c7ec603f867f55cfe5ef776a1459289974cbe5a4af11"
|
516 |
# مدل LLM برای Chatbot
|
517 |
client = Together()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
import gradio as gr
|
3 |
from together import Together
|
|
|
5 |
from langchain.memory import ConversationBufferMemory
|
6 |
from langchain.schema import SystemMessage, HumanMessage, AIMessage
|
7 |
|
|
|
|
|
|
|
8 |
os.environ["TOGETHER_API_KEY"] = "e9e74dc49951281481f5c7ec603f867f55cfe5ef776a1459289974cbe5a4af11"
|
9 |
# مدل LLM برای Chatbot
|
10 |
client = Together()
|