srbhavya01 commited on
Commit
03c4b57
·
verified ·
1 Parent(s): 83a2aa2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -122
app.py CHANGED
@@ -1,132 +1,118 @@
1
  import streamlit as st
2
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
3
- import torch
4
-
5
- # --- Page Config ---
6
- st.set_page_config(page_title="FitPlan AI", page_icon="🏋", layout="wide")
7
-
8
- # --- Custom Styling ---
9
- st.markdown("""
10
- <style>
11
- .stApp { background-color: #0E1117; color: white; }
12
- [data-testid="stSidebar"] { background-color: #161B22 !important; }
13
- .stButton > button { width: 100%; border-radius: 8px; font-weight: bold; background-color: #00F260; color: black; }
14
- </style>
15
- """, unsafe_allow_html=True)
16
-
17
- # --- Initialize Session State ---
18
- if 'user_data' not in st.session_state:
19
- st.session_state.user_data = {
20
- 'name': '', 'age': 25, 'height': 0.0, 'weight': 0.0,
21
- 'goal': 'Build Muscle', 'level': 'Beginner', 'equip': [], 'gender': 'Male'
22
- }
23
- if 'profile_complete' not in st.session_state:
24
- st.session_state.profile_complete = False
25
-
26
- # --- Helper Functions ---
27
- def calculate_bmi(w, h_cm):
28
- if h_cm > 0:
29
- return round(w / ((h_cm / 100) ** 2), 2)
30
- return 0
 
 
 
31
 
32
  def bmi_category(bmi):
33
- if bmi < 18.5: return "Underweight"
34
- if bmi < 25: return "Normal"
35
- if bmi < 30: return "Overweight"
36
- return "Obese"
37
-
38
-
39
- @st.cache_resource
40
- def load_model():
41
- tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-base")
42
- model = AutoModelForSeq2SeqLM.from_pretrained("google/flan-t5-base")
43
- return tokenizer, model
44
-
45
- tokenizer, model = load_model()
46
-
47
- # --- Sidebar Navigation ---
48
- with st.sidebar:
49
- st.markdown("<h1 style='color: #00F260;'>🏋 FitPlan AI</h1>", unsafe_allow_html=True)
50
- menu = st.radio("MENU", ["👤 Profile", "📊 Dashboard"])
51
-
52
- # --- NAVIGATION LOGIC ---
53
-
54
- if menu == "👤 Profile":
55
- st.title("👤 User Profile")
56
-
57
- name = st.text_input("Name", value=st.session_state.user_data['name'])
58
- gender = st.selectbox("Gender", ["Male", "Female", "Other"])
59
- col1, col2 = st.columns(2)
60
- height = col1.number_input("Height (cm)", min_value=0.0, value=st.session_state.user_data['height'])
61
- weight = col2.number_input("Weight (kg)", min_value=0.0, value=st.session_state.user_data['weight'])
62
-
63
- goal = st.selectbox("Fitness Goal", ["Build Muscle", "Weight Loss", "Strength Gain", "Abs Building", "Flexible"])
64
- equipment = st.multiselect("Equipment", ["Dumbbells", "Barbell", "Kettlebell", "Resistance Band", "Yoga Mat", "Full Gym", "No Equipment"])
65
- fitness_level = st.select_slider("Fitness Level", options=["Beginner", "Intermediate", "Advanced"])
66
-
67
- bmi = calculate_bmi(weight, height)
68
-
69
-
70
- if st.button(" Submit Profile"):
71
-
72
- if not name:
73
- st.error("Please enter your name.")
74
-
75
- elif height <= 0 or weight <= 0:
76
- st.error("Please enter valid height and weight.")
77
-
78
- elif not equipment:
79
- st.error("Please select at least one equipment option.")
80
-
81
  else:
82
- st.success(" Profile Submitted Successfully!")
83
-
84
- # Syncing data for dashboard
85
- st.session_state.user_data.update({
86
- 'name': name, 'height': height, 'weight': weight,
87
- 'goal': goal, 'equip': equipment, 'level': fitness_level, 'gender': gender
88
- })
89
- st.session_state.profile_complete = True
90
-
91
- bmi_status = bmi_category(bmi)
92
- equipment_list = ", ".join(equipment)
93
-
94
- prompt = f"""
95
  You are a certified professional fitness trainer.
96
- Create a detailed 5-day workout plan.
97
- User Information:
 
 
98
  - Gender: {gender}
 
 
99
  - BMI: {bmi:.2f} ({bmi_status})
100
  - Goal: {goal}
101
  - Fitness Level: {fitness_level}
102
- - Equipment Available: {equipment_list}
103
- Start directly with:
104
- Day 1:
 
 
 
 
 
 
 
105
  """
106
-
107
- with st.spinner("Generating your AI workout plan..."):
108
-
109
- inputs = tokenizer(prompt, return_tensors="pt", truncation=True)
110
-
111
- outputs = model.generate(
112
- **inputs,
113
- max_new_tokens=600,
114
- temperature=0.7,
115
- do_sample=True
116
- )
117
-
118
- result = tokenizer.decode(outputs[0], skip_special_tokens=True).strip()
119
-
120
- st.subheader(" Your Personalized Workout Plan")
121
- st.write(result)
122
-
123
- elif menu == "📊 Dashboard":
124
- if not st.session_state.profile_complete:
125
- st.warning("Please complete your profile first.")
126
- else:
127
- ud = st.session_state.user_data
128
- bmi = calculate_bmi(ud['weight'], ud['height'])
129
- st.title(f"Welcome, {ud['name']}!")
130
- st.metric("Current BMI", f"{bmi}")
131
- st.write(f"**Current Goal:** {ud['goal']}")
132
- st.write(f"**Equipment Available:** {', '.join(ud['equip'])}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ from huggingface_hub import InferenceClient
3
+ import os
4
+
5
+ # ---------- MODEL QUERY FUNCTION ----------
6
+ def query_model(prompt):
7
+ try:
8
+ HF_TOKEN = os.getenv("HF_TOKEN")
9
+
10
+ client = InferenceClient(
11
+ model="mistralai/Mistral-7B-Instruct-v0.2",
12
+ token=HF_TOKEN
13
+ )
14
+
15
+ response = client.chat_completion(
16
+ messages=[
17
+ {"role": "system", "content": "You are a certified professional fitness trainer."},
18
+ {"role": "user", "content": prompt}
19
+ ],
20
+ max_tokens=2000,
21
+ temperature=0.7
22
+ )
23
+
24
+ return response.choices[0].message.content
25
+
26
+ except Exception as e:
27
+ return f"Error: {str(e)}"
28
+
29
+
30
+ # ---------- BMI FUNCTIONS ----------
31
+ def calculate_bmi(weight, height):
32
+ height_m = height / 100
33
+ return weight / (height_m ** 2)
34
 
35
  def bmi_category(bmi):
36
+ if bmi < 18.5:
37
+ return "Underweight"
38
+ elif bmi < 25:
39
+ return "Normal Weight"
40
+ elif bmi < 30:
41
+ return "Overweight"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  else:
43
+ return "Obese"
44
+
45
+
46
+ # ---------- PROMPT BUILDER ----------
47
+ def build_prompt(name, gender, height, weight, goal, fitness_level, equipment):
48
+
49
+ bmi = calculate_bmi(weight, height)
50
+ bmi_status = bmi_category(bmi)
51
+
52
+ equipment_list = ", ".join(equipment) if equipment else "No Equipment"
53
+
54
+ prompt = f"""
 
55
  You are a certified professional fitness trainer.
56
+ Create a structured 5-day personalized workout plan.
57
+
58
+ User Profile:
59
+ - Name: {name}
60
  - Gender: {gender}
61
+ - Height: {height} cm
62
+ - Weight: {weight} kg
63
  - BMI: {bmi:.2f} ({bmi_status})
64
  - Goal: {goal}
65
  - Fitness Level: {fitness_level}
66
+ - Available Equipment: {equipment_list}
67
+
68
+ Instructions:
69
+ 1. Divide clearly into Day 1 to Day 5.
70
+ 2. Include exercise name.
71
+ 3. Include sets and reps.
72
+ 4. Include rest period.
73
+ 5. Adjust intensity based on BMI category.
74
+ 6. Avoid unsafe exercises for beginners.
75
+ 7. Keep the plan professional and easy to follow.
76
  """
77
+ return prompt, bmi, bmi_status
78
+
79
+
80
+ # ---------- STREAMLIT UI ----------
81
+ st.title("🏋️ AI Personalized 5-Day Workout Planner")
82
+
83
+ name = st.text_input("Name")
84
+ gender = st.selectbox("Gender", ["Male", "Female", "Other"])
85
+ height = st.number_input("Height (cm)", min_value=100, max_value=250)
86
+ weight = st.number_input("Weight (kg)", min_value=30, max_value=200)
87
+
88
+ goal = st.selectbox("Fitness Goal", [
89
+ "Weight Loss",
90
+ "Muscle Gain",
91
+ "General Fitness",
92
+ "Strength"
93
+ ])
94
+
95
+ fitness_level = st.selectbox("Fitness Level", [
96
+ "Beginner",
97
+ "Intermediate",
98
+ "Advanced"
99
+ ])
100
+
101
+ equipment = st.multiselect(
102
+ "Available Equipment",
103
+ ["Dumbbells", "Barbell", "Resistance Bands", "Kettlebell", "No Equipment"]
104
+ )
105
+
106
+ if st.button("Generate 5-Day Plan 💪"):
107
+
108
+ prompt, bmi, bmi_status = build_prompt(
109
+ name, gender, height, weight, goal, fitness_level, equipment
110
+ )
111
+
112
+ st.subheader(f"Your BMI: {bmi:.2f} ({bmi_status})")
113
+
114
+ with st.spinner("Creating your personalized workout plan..."):
115
+ result = query_model(prompt)
116
+
117
+ st.markdown("## 🗓️ Your 5-Day Workout Plan")
118
+ st.write(result)