Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,169 +1,600 @@
|
|
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 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
-
4.آیا به ماده غذایی خاصی آلرژی یا حساسیت دارید؟ بله / خیر
|
70 |
|
71 |
-
|
72 |
-
|
|
|
|
|
|
|
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 |
-
|
|
|
|
|
|
|
|
|
99 |
|
100 |
-
### Step
|
101 |
-
For **men**:
|
102 |
-
BMR = 88.362 + (13.397 × Weight in kg) + (4.799 × Height in cm) - (5.677 × Age)
|
103 |
|
104 |
-
For
|
105 |
-
|
|
|
|
|
106 |
|
107 |
-
|
108 |
-
|
109 |
-
- **
|
110 |
-
- **
|
111 |
-
- **High Activity (intense exercise/sports 6-7 days/week)**: TDEE = BMR × 1.9
|
112 |
|
113 |
-
|
|
|
|
|
|
|
114 |
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
119 |
|
120 |
-
|
121 |
-
|
122 |
-
- **Carbohydrates**: 45-55% of total daily calories
|
123 |
-
- **Fats**: 25-30% of total daily calories
|
124 |
|
125 |
-
|
126 |
-
|
127 |
-
- **Carbohydrates**: 50-60% of total daily calories
|
128 |
-
- **Fats**: 20-25% of total daily calories
|
129 |
|
130 |
-
|
131 |
-
|
132 |
|
133 |
-
|
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 |
-
|
|
|
138 |
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
|
|
145 |
|
146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
147 |
|
148 |
-
|
|
|
149 |
|
150 |
-
|
151 |
-
|
|
|
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 |
|
@@ -173,10 +604,6 @@ prompt = PromptTemplate(template=prompt_template, input_variables=["chat_history
|
|
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 = ""
|
@@ -187,63 +614,8 @@ def get_chat_history_string(chat_memory):
|
|
187 |
history += f"دستیار: {msg.content}\n"
|
188 |
return history
|
189 |
|
190 |
-
# تابع
|
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 |
|
@@ -254,247 +626,70 @@ def agent_respond(message):
|
|
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 =
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
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 |
-
#
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
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 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
|
|
|
|
|
|
|
|
432 |
|
433 |
with gr.Blocks() as demo:
|
434 |
-
chatbot = gr.Chatbot(
|
435 |
-
msg = gr.Textbox(show_label=False, placeholder="
|
436 |
-
|
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("
|
441 |
-
|
442 |
-
|
443 |
-
|
|
|
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 |
-
|
|
|
|
|
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()
|
|
|
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
|
508 |
+
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 |
+
|
516 |
+
# مدل LLM برای Chatbot
|
517 |
+
client = Together()
|
518 |
+
|
519 |
+
# تعریف قالب Prompt
|
520 |
+
prompt_template = """
|
521 |
+
شما یک دکتر و کارشناس تغذیه به نام دکتر مهرشاد بنت یعقوب هستید و میخواهید برای بیماران خود رژیم غذایی مناسب و شخصیسازیشدهای را طراحی کنید. شما با گرفتن اطلاعات از بیمار، رژیم دقیق و متناسب با وضعیت او را تجویز میکنید. ابتدا تک تک سوالات زیر را از بیمار بپرسید و سپس بر اساس پاسخها، محاسبات رژیم غذایی را انجام دهید.
|
522 |
+
|
523 |
+
### **مشخصات فردی**:
|
524 |
+
1. لطفا نام و نام خانوادگی خود را وارد کنید.
|
525 |
+
2. جنسیت شما چیست؟ (مرد/زن)
|
526 |
+
3. سن شما چقدر است؟
|
527 |
+
4. شغل شما چیست؟
|
528 |
+
|
529 |
+
### **مشخصات تن سنجی**:
|
530 |
+
1. وزن شما چقدر است؟ (به کیلوگرم)
|
531 |
+
2. قد شما چقدر است؟ (به سانتیمتر)
|
532 |
+
3. دور کمر شما چقدر است؟
|
533 |
+
4. دور باسن شما چقدر است؟
|
534 |
+
|
535 |
+
### **سوالات مربوط به فعالیت بدنی**:
|
536 |
+
1. میزان فعالیت بدنی شما چگونه است؟ (کم / متوسط / زیاد)
|
537 |
+
2. آیا فعالیت ورزشی دارید؟ (بله / خیر)
|
538 |
+
3. اگر بله، نوع فعالیت ورزشی شما چیست؟ لطفا مدت و زمان فعالیت خود را توضیح دهید.
|
539 |
+
4. آیا تا به حال رژیم غذایی گرفتهاید؟ تحت نظر چه کسی و به مدت چقدر؟ آیا در انجام رژیم موفق بودهاید؟
|
540 |
+
5. آیا تا به حال از دستگاه کمک لاغری استفاده کردهاید؟
|
541 |
+
|
542 |
+
### **بیماریهای زمینهای**:
|
543 |
+
1. آیا مشکلات گوارشی نظیر نفخ، ریفلاکس، یبوست، بیاشتهایی یا پر اشتهایی دارید؟ (بله / خیر) توضیح دهید.
|
544 |
+
2. داروها یا مکملهایی که مصرف میکنید را نام ببرید.
|
545 |
+
3. اگر آلرژی یا تمایلات غذایی خاصی دارید، لطفا توضیح دهید.
|
546 |
+
4. آیا به ماده غذایی خاصی آلرژی یا حساسیت دارید؟ (بله / خیر)
|
547 |
+
5. تنفرات یا عدم تمایلات غذایی خود را توضیح دهید.
|
548 |
+
6. به کدام ماده یا مواد غذایی تمایل زیادی دارید و بیش از اندازه مصرف میکنید؟
|
549 |
+
|
550 |
+
### **بررسی الگوی غذای روزانه**:
|
551 |
+
1. مصرف صبحانه شما چگونه است؟ (همیشه / اغلب / گاهی / به ندرت / اصلا)
|
552 |
+
2. معمولا صبحانه چه میخورید؟ چه مقدار؟
|
553 |
+
3. میان وعدهها چه میخورید؟ چه مقدار؟
|
554 |
+
4. مصرف نان یا برنج در ناهار شما چقدر است؟
|
555 |
+
5. مصرف میان وعده عصر شما چگونه است؟
|
556 |
+
6. آیا شام میل میکنید؟ (بله / خیر)
|
557 |
+
7. آیا وعدهی قبل از خواب میل میکنید؟ (بله / خیر)
|
558 |
+
8. چه زمان از روز بیشتر احساس گرسنگی میکنید؟
|
559 |
+
|
560 |
+
### **عادات غذایی**:
|
561 |
+
1. آیا فست فودها و غذاهای سرخکردنی مصرف میکنید؟ (بله / خیر)
|
562 |
+
2. میزان مصرف سبزیجات، لبنیات و میوهها در طول روز شما چقدر است؟
|
563 |
+
3. آیا به شیرینیجات، شکلات، کیک و بیسکوییت تمایل دارید؟ (بله / خیر)
|
564 |
+
4. میزان ریزهخواری شما چقدر است؟ آیا به غذا ناخنک میزنید؟
|
565 |
+
|
566 |
+
---
|
567 |
+
### **محاسبات رژیم غذایی**:
|
568 |
+
حالا که تمامی اطلاعات از بیمار دریافت شد، لطفا محاسبات زیر را انجام بدهید:
|
569 |
+
|
570 |
+
1. **محاسبه BMR (Basal Metabolic Rate)**:
|
571 |
+
برای **مردان**:
|
572 |
+
BMR = 88.362 + (13.397 × وزن به کیلوگرم) + (4.799 × قد به سانتیمتر) - (5.677 × سن)
|
573 |
+
برای **زنان**:
|
574 |
+
BMR = 447.593 + (9.247 × وزن به کیلوگرم) + (3.098 × قد به سانتیمتر) - (4.330 × سن)
|
575 |
+
|
576 |
+
2. **محاسبه TDEE (Total Daily Energy Expenditure)**:
|
577 |
+
برای محاسبه TDEE، BMR را بر اساس سطح فعالیت فرد ضرب کنید:
|
578 |
+
- **کم تحرک**: TDEE = BMR × 1.2
|
579 |
+
- **فعالیت متوسط**: TDEE = BMR × 1.55
|
580 |
+
- **فعالیت زیاد**: TDEE = BMR × 1.9
|
581 |
+
|
582 |
+
3. **توزیع ماکروها** (کربوهیدراتها، پروتئینها، چربیها):
|
583 |
+
براساس هدف رژیم (کاهش وزن، حفظ وزن، یا افزایش عضله):
|
584 |
+
- **کاهش وزن**: پروتئین: ۲-۲.۵ گرم به ازای هر کیلوگرم وزن بدن، کربوهیدراتها: ۴۰-۴۵% از کالری روزانه، چربیها: ۳۰-۳۵% از کالری روزانه.
|
585 |
+
- **حفظ وزن**: پروتئین: ۱.۵-۲ گرم به ازای هر کیلوگرم وزن بدن، کربوهیدراتها: ۴۵-۵۵% از کالری روزانه، چربیها: ۲۵-۳۰% از کالری روزانه.
|
586 |
+
- **افزایش وزن**: پروتئین: ۲-۲.۵ گرم به ازای هر کیلوگرم وزن بد��، کربوهیدراتها: ۵۰-۶۰% از کالری روزانه، چربیها: ۲۰-۲۵% از کالری روزانه.
|
587 |
+
|
588 |
+
4. **ایجاد رژیم غذایی روزانه**:
|
589 |
+
براساس محاسبات انجام شده، یک رژیم غذایی دقیق و مناسب به فرد پیشنهاد دهید که شامل وعدههای غذایی، مقدار کالری و تقسیم بندی ماکروها باشد.
|
590 |
+
|
591 |
+
---
|
592 |
+
**توضیحات:**
|
593 |
+
در این پرامپت، تمامی سوالات مهم جهت جمعآوری اطلاعات بیمار بهطور دقیق و کامل پرسیده میشود. سپس پس از دریافت پاسخها، محاسبات مورد نیاز برای طراحی رژیم غذایی شخصی انجام میشود.
|
594 |
+
|
595 |
+
با این روش، میتوانید رژیم غذایی مناسب هر فرد را متناسب با ویژگیها، سطح فعالیت بدنی، و هدفهای شخصی او (کاهش وزن، حفظ وزن، یا افزایش عضله) تنظیم کنید.
|
596 |
+
|
597 |
+
chat history:
|
598 |
{chat_history}
|
599 |
"""
|
600 |
|
|
|
604 |
# حافظه مکالمه
|
605 |
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
|
606 |
|
|
|
|
|
|
|
|
|
607 |
# تابع برای تبدیل تاریخچه مکالمه به رشته
|
608 |
def get_chat_history_string(chat_memory):
|
609 |
history = ""
|
|
|
614 |
history += f"دستیار: {msg.content}\n"
|
615 |
return history
|
616 |
|
617 |
+
# تابع اصلی برای مدیریت مکالمه
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
618 |
def agent_respond(message):
|
|
|
|
|
619 |
# بهروزرسانی حافظه با پیام کاربر
|
620 |
memory.chat_memory.add_user_message(message)
|
621 |
|
|
|
626 |
system_prompt = prompt.format(chat_history=get_chat_history_string(memory.chat_memory))
|
627 |
messages.insert(0, SystemMessage(content=system_prompt))
|
628 |
|
629 |
+
# ارسال پیام به مدل `Together` و دریافت پاسخ
|
630 |
+
response = client.chat.completions.create(
|
631 |
+
model="meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
|
632 |
+
messages=[{"role": "system", "content": system_prompt}] + [{"role": "user", "content": message}],
|
633 |
+
max_tokens=500,
|
634 |
+
temperature=1,
|
635 |
+
top_p=0.7,
|
636 |
+
top_k=50,
|
637 |
+
repetition_penalty=1,
|
638 |
+
stop=["<|eot_id|>", "<|eom_id|>"],
|
639 |
+
stream=True
|
640 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
641 |
|
642 |
+
# دریافت و نمایش پاسخ مدل
|
643 |
+
response_content = ""
|
644 |
+
for token in response:
|
645 |
+
if hasattr(token, 'choices'):
|
646 |
+
response_content += token.choices[0].delta.content
|
647 |
+
memory.chat_memory.add_ai_message(response_content)
|
648 |
+
return response_content
|
|
|
|
|
|
|
|
|
649 |
|
650 |
def clear_memory():
|
|
|
651 |
memory.chat_memory.clear()
|
652 |
+
return [], ""
|
653 |
+
|
654 |
+
def save_chat_history():
|
655 |
+
chat_history = get_chat_history_string(memory.chat_memory)
|
656 |
+
file_path = "/tmp/chat_history.txt" # مسیر موقت برای Hugging Face Spaces
|
657 |
+
with open(file_path, "w", encoding="utf-8") as file:
|
658 |
+
file.write(chat_history)
|
659 |
+
return file_path
|
660 |
|
661 |
with gr.Blocks() as demo:
|
662 |
+
chatbot = gr.Chatbot()
|
663 |
+
msg = gr.Textbox(show_label=False, placeholder="پیامتان را وارد کنید...")
|
664 |
+
|
|
|
|
|
665 |
with gr.Row():
|
666 |
+
submit_btn = gr.Button("ارسال")
|
667 |
+
clear_btn = gr.Button("🧹 پاک کردن حافظه")
|
668 |
+
download_btn = gr.Button("📥 دانلود تاریخچه چت")
|
669 |
+
download_link = gr.File(label="دانلود فایل تاریخچه چت") # برای نمایش لینک دانلود
|
670 |
+
|
671 |
def fix_bidi_text(text):
|
672 |
RLE = '\u202B' # Right-To-Left Embedding
|
673 |
PDF = '\u202C' # Pop Directional Formatting
|
674 |
return f"{RLE}{text}{PDF}"
|
675 |
+
|
676 |
def respond(message, chat_history):
|
677 |
bot_response = agent_respond(message)
|
|
|
678 |
fixed_message = fix_bidi_text(message)
|
679 |
fixed_bot_response = fix_bidi_text(bot_response)
|
680 |
chat_history.append((fixed_message, fixed_bot_response))
|
681 |
+
return chat_history, ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
682 |
|
683 |
+
def download_chat_history():
|
684 |
+
file_path = save_chat_history()
|
685 |
+
return file_path # بازگرداندن مسیر فایل
|
686 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
687 |
submit_btn.click(respond, [msg, chatbot], [chatbot, msg])
|
|
|
|
|
|
|
688 |
msg.submit(respond, [msg, chatbot], [chatbot, msg])
|
689 |
clear_btn.click(clear_memory, inputs=None, outputs=[chatbot, msg])
|
690 |
+
download_btn.click(download_chat_history, inputs=None, outputs=download_link) #
|
691 |
+
|
692 |
|
693 |
+
# اجرای برنامه Gradio
|
694 |
if __name__ == "__main__":
|
695 |
+
demo.launch(share=True)
|