therayz1 commited on
Commit
eb65dd7
·
verified ·
1 Parent(s): 5cc72ae

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +424 -0
  2. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import openai
3
+ import pandas as pd
4
+ from datetime import datetime
5
+ from weasyprint import HTML
6
+ from jinja2 import Template
7
+ import os
8
+
9
+ # Egzersiz veritabanı
10
+ exercise_db = {
11
+ "Kardiyovasküler": ["Koşu", "Yürüyüş", "Bisiklet", "Yüzme", "İp atlama"],
12
+ "Güç Antrenmanı": ["Şınav", "Mekik", "Squat", "Deadlift", "Bench Press"],
13
+ "Esneklik": ["Yoga", "Pilates", "Germe Egzersizleri"],
14
+ "HIIT": ["Burpees", "Mountain Climbers", "Jump Squats", "High Knees"]
15
+ }
16
+ html_template = """
17
+ <!DOCTYPE html>
18
+ <html>
19
+ <head>
20
+ <meta charset="UTF-8">
21
+ <style>
22
+ body {
23
+ font-family: Arial, sans-serif;
24
+ line-height: 1.6;
25
+ margin: 40px;
26
+ color: #333;
27
+ }
28
+ .header {
29
+ text-align: center;
30
+ color: #2c3e50;
31
+ margin-bottom: 40px;
32
+ border-bottom: 2px solid #3498db;
33
+ padding-bottom: 20px;
34
+ }
35
+ .section {
36
+ margin: 30px 0;
37
+ padding: 25px;
38
+ background: #f8f9fa;
39
+ border-radius: 10px;
40
+ box-shadow: 0 2px 5px rgba(0,0,0,0.1);
41
+ }
42
+ .section h2 {
43
+ color: #2980b9;
44
+ border-bottom: 1px solid #bdc3c7;
45
+ padding-bottom: 10px;
46
+ }
47
+ .metrics {
48
+ display: grid;
49
+ grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
50
+ gap: 20px;
51
+ margin: 20px 0;
52
+ }
53
+ .metric-box {
54
+ text-align: center;
55
+ padding: 20px;
56
+ background: #fff;
57
+ border-radius: 8px;
58
+ box-shadow: 0 2px 4px rgba(0,0,0,0.05);
59
+ }
60
+ .metric-box h3 {
61
+ color: #3498db;
62
+ margin-bottom: 15px;
63
+ }
64
+ .table {
65
+ width: 100%;
66
+ border-collapse: collapse;
67
+ margin: 20px 0;
68
+ background: #fff;
69
+ }
70
+ .table th, .table td {
71
+ border: 1px solid #e1e1e1;
72
+ padding: 12px;
73
+ text-align: left;
74
+ }
75
+ .table th {
76
+ background-color: #3498db;
77
+ color: white;
78
+ }
79
+ .table tr:nth-child(even) {
80
+ background-color: #f8f9fa;
81
+ }
82
+ .ai-recommendations {
83
+ background: #fff;
84
+ padding: 20px;
85
+ border-radius: 8px;
86
+ box-shadow: 0 2px 4px rgba(0,0,0,0.05);
87
+ margin-top: 20px;
88
+ }
89
+ </style>
90
+ </head>
91
+ <body>
92
+ <div class="header">
93
+ <h1>🏋️‍♂️ Kişisel Fitness Planı</h1>
94
+ <p>Oluşturulma Tarihi: {{ creation_date }}</p>
95
+ </div>
96
+ <div class="section">
97
+ <h2>👤 Kişisel Bilgiler</h2>
98
+ <div class="metrics">
99
+ <div class="metric-box">
100
+ <h3>{{ name }}</h3>
101
+ <p>{{ age }} yaşında</p>
102
+ </div>
103
+ <div class="metric-box">
104
+ <h3>Fiziksel Ölçümler</h3>
105
+ <p>Boy: {{ height }} cm</p>
106
+ <p>Kilo: {{ weight }} kg</p>
107
+ <p>{{ bmi_result }}</p>
108
+ </div>
109
+ <div class="metric-box">
110
+ <h3>Hedef</h3>
111
+ <p>{{ goal }}</p>
112
+ </div>
113
+ </div>
114
+ </div>
115
+ <div class="section">
116
+ <h2>📋 AI Önerileri</h2>
117
+ <div class="ai-recommendations">
118
+ {{ ai_recommendation }}
119
+ </div>
120
+ </div>
121
+ <div class="section">
122
+ <h2>💪 Önerilen Egzersizler</h2>
123
+ <table class="table">
124
+ <tr>
125
+ <th>Kategori</th>
126
+ <th>Egzersizler</th>
127
+ </tr>
128
+ {% for category, exercises in exercise_list.items() %}
129
+ <tr>
130
+ <td>{{ category }}</td>
131
+ <td>{{ ", ".join(exercises) }}</td>
132
+ </tr>
133
+ {% endfor %}
134
+ </table>
135
+ </div>
136
+ </body>
137
+ </html>
138
+ """
139
+
140
+ class FitnessPlan:
141
+ def __init__(self):
142
+ self.current_plan = None
143
+ self.chat_history = []
144
+ self.api_key = None
145
+ self.api_configured = False
146
+
147
+ def configure_api(self, api_key):
148
+ """API yapılandırmasını ayarla"""
149
+ if api_key and api_key.strip():
150
+ self.api_key = api_key
151
+ openai.api_base = "https://integrate.api.nvidia.com/v1"
152
+ openai.api_key = api_key
153
+ self.api_configured = True
154
+ return "✅ API yapılandırması başarıyla tamamlandı!"
155
+ return "❌ Lütfen geçerli bir API anahtarı girin!"
156
+
157
+ def store_plan(self, plan):
158
+ self.current_plan = plan
159
+
160
+ def generate_pdf(self):
161
+ """Fitness planını PDF olarak oluştur"""
162
+ if not self.current_plan:
163
+ return None
164
+
165
+ template = Template(html_template)
166
+ html_content = template.render(
167
+ creation_date=datetime.now().strftime("%d/%m/%Y"),
168
+ name=self.current_plan["user_info"]["name"],
169
+ age=self.current_plan["user_info"]["age"],
170
+ height=self.current_plan["user_info"]["height"],
171
+ weight=self.current_plan["user_info"]["weight"],
172
+ goal=self.current_plan["user_info"]["goal"],
173
+ bmi_result=self.current_plan["bmi_result"],
174
+ ai_recommendation=self.current_plan["ai_recommendation"],
175
+ exercise_list=exercise_db
176
+ )
177
+
178
+ pdf_path = f"fitness_plan_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
179
+
180
+ # HTML içeriği alıp PDF'ye dönüştür
181
+ HTML(string=html_content).write_pdf(pdf_path)
182
+
183
+ return pdf_path
184
+
185
+ fitness_plan = FitnessPlan()
186
+
187
+ def get_ai_recommendation(user_info):
188
+ """AI'dan kişiselleştirilmiş fitness tavsiyesi al"""
189
+ if not fitness_plan.api_configured:
190
+ return "Lütfen önce API anahtarınızı yapılandırın!"
191
+
192
+ prompt = f"""
193
+ Aşağıdaki bilgilere sahip kullanıcı için detaylı bir fitness planı oluştur:
194
+ Yaş: {user_info['age']}
195
+ Kilo: {user_info['weight']} kg
196
+ Boy: {user_info['height']} cm
197
+ Hedef: {user_info['goal']}
198
+ Fitness Seviyesi: {user_info['fitness_level']}
199
+ Sağlık Durumu: {user_info['health_conditions']}
200
+ Lütfen şunları içeren bir plan oluştur:
201
+ 1. Haftalık egzersiz programı
202
+ 2. Beslenme önerileri
203
+ 3. Hedeflerine ulaşması için özel tavsiyeler
204
+ 4. İlerleme takibi için öneriler
205
+
206
+ Lütfen yanıtını HTML formatında, düzenli başlıklar ve listeler kullanarak oluştur.
207
+ """
208
+
209
+ try:
210
+ response = openai.ChatCompletion.create(
211
+ model="nvidia/llama-3.1-nemotron-70b-instruct",
212
+ messages=[{"role": "user", "content": prompt}],
213
+ temperature=0.7,
214
+ max_tokens=1024
215
+ )
216
+ return response.choices[0].message['content']
217
+ except Exception as e:
218
+ return f"AI tavsiyesi alınırken bir hata oluştu: {str(e)}"
219
+
220
+ def calculate_bmi(weight, height):
221
+ """BMI hesaplama"""
222
+ height_m = height / 100
223
+ bmi = weight / (height_m ** 2)
224
+
225
+ if bmi < 18.5:
226
+ category = "Zayıf"
227
+ elif 18.5 <= bmi < 25:
228
+ category = "Normal"
229
+ elif 25 <= bmi < 30:
230
+ category = "Fazla Kilolu"
231
+ else:
232
+ category = "Obez"
233
+
234
+ return f"BMI: {bmi:.1f} - Kategori: {category}"
235
+
236
+ def create_workout_plan(name, age, weight, height, goal, fitness_level, health_conditions):
237
+ """Ana fonksiyon - fitness planı oluştur"""
238
+ if not fitness_plan.api_configured:
239
+ return "⚠️ Lütfen önce API anahtarınızı yapılandırın!"
240
+
241
+ user_info = {
242
+ "name": name,
243
+ "age": age,
244
+ "weight": weight,
245
+ "height": height,
246
+ "goal": goal,
247
+ "fitness_level": fitness_level,
248
+ "health_conditions": health_conditions
249
+ }
250
+
251
+ bmi_result = calculate_bmi(weight, height)
252
+ ai_recommendation = get_ai_recommendation(user_info)
253
+
254
+ # Planı sakla
255
+ fitness_plan.store_plan({
256
+ "user_info": user_info,
257
+ "bmi_result": bmi_result,
258
+ "ai_recommendation": ai_recommendation
259
+ })
260
+
261
+ # Markdown formatında düzenli çıktı
262
+ response = f"""
263
+ ## 👤 Kişisel Bilgiler
264
+ - İsim: {name}
265
+ - Yaş: {age}
266
+ - Kilo: {weight} kg
267
+ - Boy: {height} cm
268
+ - Hedef: {goal}
269
+ - Fitness Seviyesi: {fitness_level}
270
+
271
+ ## 📊 Fiziksel Değerlendirme
272
+ {bmi_result}
273
+
274
+ ## 🤖 AI Önerileri
275
+ {ai_recommendation}
276
+
277
+ ## 💪 Önerilen Egzersiz Kategorileri
278
+ """
279
+
280
+ for category, exercises in exercise_db.items():
281
+ response += f"\n### {category}\n"
282
+ response += "\n".join([f"- {exercise}" for exercise in exercises])
283
+ response += "\n"
284
+
285
+ return response
286
+
287
+ def download_plan():
288
+ """Planı PDF olarak indir"""
289
+ if not fitness_plan.current_plan:
290
+ return None
291
+ return fitness_plan.generate_pdf()
292
+
293
+ def chat_with_ai(api_key, message, history):
294
+ """AI ile sohbet et"""
295
+ if not fitness_plan.api_configured:
296
+ return history + [[message, "⚠️ Lütfen önce API anahtarınızı yapılandırın!"]]
297
+
298
+ if fitness_plan.current_plan is None:
299
+ return history + [[message, "Lütfen önce bir fitness planı oluşturun."]]
300
+
301
+ # Mevcut planı string olarak format
302
+ current_plan_str = f"""
303
+ Kişisel Bilgiler:
304
+ İsim: {fitness_plan.current_plan['user_info']['name']}
305
+ Yaş: {fitness_plan.current_plan['user_info']['age']}
306
+ Boy: {fitness_plan.current_plan['user_info']['height']} cm
307
+ Kilo: {fitness_plan.current_plan['user_info']['weight']} kg
308
+ Hedef: {fitness_plan.current_plan['user_info']['goal']}
309
+ BMI Sonucu: {fitness_plan.current_plan['bmi_result']}
310
+ """
311
+
312
+ prompt = f"""
313
+ Mevcut fitness planı:
314
+ {current_plan_str}
315
+
316
+ AI Önerileri:
317
+ {fitness_plan.current_plan['ai_recommendation']}
318
+
319
+ Kullanıcı sorusu: {message}
320
+ Lütfen kullanıcının sorusunu yukarıdaki fitness planı bağlamında yanıtla.
321
+ """
322
+
323
+ try:
324
+ response = openai.ChatCompletion.create(
325
+ model="nvidia/llama-3.1-nemotron-70b-instruct",
326
+ messages=[{"role": "user", "content": prompt}],
327
+ temperature=0.7,
328
+ max_tokens=1024
329
+ )
330
+ ai_response = response.choices[0].message['content']
331
+ except Exception as e:
332
+ ai_response = f"Yanıt alınırken bir hata oluştu: {str(e)}"
333
+
334
+ return history + [[message, ai_response]]
335
+
336
+
337
+ # Gradio arayüzü
338
+ with gr.Blocks(title="AI Fitness Asistanı", theme=gr.themes.Soft()) as demo:
339
+ gr.Markdown("""
340
+ # 🏋️‍♂️ AI Destekli Fitness Asistanı---Deployed by Eray Coşkun
341
+ Kişiselleştirilmiş fitness planınızı oluşturun ve AI ile planınız hakkında sohbet edin!
342
+ """)
343
+
344
+ with gr.Tab("API Yapılandırması"):
345
+ gr.Markdown("""
346
+ ### 🔑 API Yapılandırması
347
+ Uygulamayı kullanmadan önce NVIDIA API anahtarınızı yapılandırmalısınız.
348
+ """)
349
+ api_key_input = gr.Textbox(
350
+ label="API Anahtarınızı Giriniz (API anahtarınız yoksa [buradan](https://build.nvidia.com/nvidia/llama-3_1-nemotron-70b-instruct) alın)",
351
+ type="password"
352
+ )
353
+ api_status = gr.Markdown()
354
+ api_submit = gr.Button("API'yi Yapılandır", variant="primary")
355
+
356
+ with gr.Tab("Plan Oluştur"):
357
+ with gr.Row():
358
+ with gr.Column():
359
+ name_input = gr.Textbox(label="Adınız")
360
+ age_input = gr.Number(label="Yaşınız", minimum=15, maximum=100)
361
+ weight_input = gr.Number(label="Kilonuz (kg)", minimum=30, maximum=200)
362
+ height_input = gr.Number(label="Boyunuz (cm)", minimum=120, maximum=220)
363
+
364
+ with gr.Column():
365
+ goal_input = gr.Dropdown(
366
+ label="Fitness Hedefiniz",
367
+ choices=["Kilo Vermek", "Kas Kazanmak", "Genel Sağlık", "Güç Artırmak"]
368
+ )
369
+ fitness_level_input = gr.Radio(
370
+ label="Fitness Seviyeniz",
371
+ choices=["Başlangıç", "Orta", "İleri"]
372
+ )
373
+ health_input = gr.Textbox(
374
+ label="Sağlık Durumunuz (varsa)",
375
+ placeholder="Örn: Diyabet, Tansiyon, vs. yoksa 'yok' yazın"
376
+ )
377
+
378
+ with gr.Row():
379
+ submit_btn = gr.Button("Plan Oluştur", variant="primary")
380
+ download_btn = gr.Button("PDF Olarak İndir", variant="secondary")
381
+
382
+ output = gr.Markdown()
383
+ pdf_output = gr.File(label="İndirilebilir PDF")
384
+
385
+ with gr.Tab("AI ile Sohbet"):
386
+ gr.Markdown("""
387
+ ### 💬 Planınız Hakkında Sohbet Edin
388
+ Oluşturulan plan hakkında sorularınızı sorun ve AI'dan kişiselleştirilmiş yanıtlar alın.
389
+ """)
390
+ chatbot = gr.Chatbot(height=400)
391
+ msg = gr.Textbox(label="Planınız hakkında soru sorun",
392
+ placeholder="Örn: Bu plan ile hedefime ne kadar sürede ulaşabilirim?")
393
+ with gr.Row():
394
+ clear = gr.Button("Sohbeti Temizle")
395
+ submit_msg = gr.Button("Gönder", variant="primary")
396
+
397
+ # Event handlers
398
+ api_submit.click(
399
+ fitness_plan.configure_api,
400
+ inputs=[api_key_input],
401
+ outputs=[api_status]
402
+ )
403
+
404
+ submit_btn.click(
405
+ create_workout_plan,
406
+ inputs=[name_input, age_input, weight_input, height_input,
407
+ goal_input, fitness_level_input, health_input],
408
+ outputs=output
409
+ )
410
+
411
+ download_btn.click(
412
+ download_plan,
413
+ inputs=[],
414
+ outputs=pdf_output
415
+ )
416
+
417
+ # Sohbet kutusundaki mesajı gönderme ve temizleme işlevleri
418
+ msg.submit(chat_with_ai, [api_key_input, msg, chatbot], chatbot)
419
+ submit_msg.click(chat_with_ai, [api_key_input, msg, chatbot], chatbot)
420
+ clear.click(lambda: None, None, chatbot, queue=False)
421
+
422
+ # Uygulamayı başlat
423
+ if __name__ == "__main__":
424
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio==3.41.2
2
+ openai==0.27.8
3
+ pandas==1.5.3
4
+ jinja2==3.1.2
5
+ weasyprint==53.3
6
+ pydyf==0.3.0