Spaces:
Sleeping
Sleeping
File size: 8,158 Bytes
b70c076 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 |
import streamlit as st
import requests
import random
# -------------------------------
# Utils
# -------------------------------
@st.cache_data(ttl=3600) # Cache Wikipedia API calls for 1 hour
def get_wikipedia_summary(term):
try:
url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{term}"
response = requests.get(url, timeout=10)
if response.status_code == 200:
return response.json().get("extract", "No summary found.")
else:
return f"Error retrieving information: HTTP {response.status_code}"
except requests.RequestException as e:
st.error(f"Request error: {str(e)}")
return "Connection error. Please try again later."
def get_random_health_tip():
tips = [
"Drink at least 2 liters of water every day.",
"Do at least 30 minutes of physical activity daily.",
"Maintain a regular sleep schedule.",
"Include fruits and vegetables in every meal.",
"Take short breaks during long sitting hours.",
"Practice mindfulness meditation for 10 minutes daily.",
"Reduce sodium intake to help control blood pressure.",
"Limit screen time before bedtime for better sleep.",
"Choose whole grains over refined carbohydrates.",
"Incorporate strength training at least twice a week."
]
return random.choice(tips)
def get_did_you_know_fact():
facts = [
"The human body has 206 bones.",
"Your heart beats about 100,000 times a day.",
"The skin is the body's largest organ.",
"The brain uses around 20% of the bodyβs oxygen.",
"Laughter is good for your heart and can reduce stress."
]
return random.choice(facts)
def get_wikibooks_remedies():
# Placeholder text simulating Wikibooks data
return [
("Turmeric Milk", "Used for colds and inflammation."),
("Honey & Ginger", "Relieves sore throat and cough."),
("Amla Juice", "Boosts immunity and rich in Vitamin C.")
]
def get_workout_plan(workout_type="full_body"):
workouts = {
"full_body": [
"10 Jumping Jacks",
"10 Push-ups",
"15 Squats",
"20-second Plank",
"10 Lunges (each leg)",
"Repeat 3 times"
],
"cardio": [
"30 seconds Jumping Jacks",
"30 seconds High Knees",
"30 seconds Butt Kicks",
"30 seconds Mountain Climbers",
"30 seconds rest",
"Repeat 4 times"
],
"strength": [
"12 Push-ups",
"15 Squats with 5 second hold",
"10 Tricep Dips",
"10 Glute Bridges",
"8 Superman Holds",
"Repeat 3 times"
],
"flexibility": [
"30 seconds Hamstring Stretch",
"30 seconds Quad Stretch (each leg)",
"30 seconds Child's Pose",
"30 seconds Cat-Cow Stretch",
"30 seconds Butterfly Stretch",
"Repeat 2 times"
]
}
return workouts.get(workout_type, workouts["full_body"])
def generate_quiz():
questions = [
("How many bones are there in the human body?", ["206", "201", "212", "195"], "206"),
("What vitamin do we get from sunlight?", ["Vitamin A", "Vitamin B12", "Vitamin D", "Vitamin C"], "Vitamin D"),
("Which organ uses the most oxygen?", ["Heart", "Brain", "Lungs", "Liver"], "Brain")
]
return random.choice(questions)
def calculate_bmi(weight, height, unit="m"):
"""Calculate BMI (Body Mass Index).
Args:
weight: Weight in kilograms
height: Height in meters, centimeters, or feet (with decimal for inches)
unit: Unit of height measurement ("m", "cm", or "ft")
Returns:
tuple: (bmi_value, bmi_category)
"""
if weight <= 0 or height <= 0:
return None, None
# Convert height to meters for calculation
if unit == "cm":
height = height / 100.0
elif unit == "ft":
# Convert feet/inches to meters (1 foot = 0.3048 meters)
feet_whole = int(height)
inches = (height - feet_whole) * 10
height = feet_whole * 0.3048 + inches * 0.0254
bmi = weight / (height ** 2)
if bmi < 18.5:
category = "Underweight"
elif 18.5 <= bmi < 25:
category = "Normal weight"
elif 25 <= bmi < 30:
category = "Overweight"
else:
category = "Obese"
return round(bmi, 2), category
# -------------------------------
# UI
# -------------------------------
st.set_page_config(page_title="WikiFit", page_icon="πͺ")
st.title("πͺ WikiFit β Health & Fitness from Wikimedia")
menu = st.sidebar.selectbox("Navigate", ["Daily Tip", "Health Search", "Workout Plans", "Home Remedies", "Did You Know?", "Fitness Quiz", "BMI Calculator"])
if menu == "Daily Tip":
st.subheader("π Daily Fitness/Nutrition Tip")
st.success(get_random_health_tip())
elif menu == "Health Search":
st.subheader("π Search Health Info from Wikipedia")
query = st.text_input("Enter a health topic (e.g., Vitamin D, Yoga)")
if query:
result = get_wikipedia_summary(query.replace(" ", "_"))
st.info(result)
elif menu == "Workout Plans":
st.subheader("ποΈββοΈ Basic Workout Plans from Wikibooks")
workout_type = st.selectbox("Choose workout type", ["full_body", "cardio", "strength", "flexibility"])
plan = get_workout_plan(workout_type)
for step in plan:
st.write(f"- {step}")
elif menu == "Home Remedies":
st.subheader("πΏ Traditional Remedies from Wikibooks")
remedies = get_wikibooks_remedies()
for title, desc in remedies:
st.markdown(f"**{title}** β {desc}")
elif menu == "Did You Know?":
st.subheader("β Fun Health Facts from Wikipedia")
st.info(get_did_you_know_fact())
elif menu == "Fitness Quiz":
st.subheader("π§ Quick Fitness Quiz")
q, options, answer = generate_quiz()
user_answer = st.radio(q, options)
if st.button("Submit"):
if user_answer == answer:
st.success("Correct! β
")
else:
st.error(f"Incorrect. The right answer is {answer}.")
elif menu == "BMI Calculator":
st.subheader("π BMI Calculator")
col1, col2 = st.columns(2)
with col1:
weight = st.number_input("Weight (kg)", min_value=0.0, max_value=300.0, value=70.0, step=0.1)
with col2:
unit = st.selectbox("Height unit", ["m", "cm", "ft"], index=0)
if unit == "m":
height = st.number_input("Height (m)", min_value=0.0, max_value=3.0, value=1.70, step=0.01)
elif unit == "cm":
height = st.number_input("Height (cm)", min_value=0.0, max_value=300.0, value=170.0, step=1.0)
else: # ft
height = st.number_input("Height (ft.in)",
min_value=0.0,
max_value=8.0,
value=5.6,
step=0.1,
help="Enter feet as whole number and inches as decimal (e.g., 5.6 for 5'6\")")
if st.button("Calculate BMI"):
bmi_value, bmi_category = calculate_bmi(weight, height, unit)
if bmi_value and bmi_category:
st.info(f"Your BMI: **{bmi_value}**")
# Color coding for BMI categories
if bmi_category == "Underweight":
st.warning(f"Category: **{bmi_category}**")
elif bmi_category == "Normal weight":
st.success(f"Category: **{bmi_category}**")
elif bmi_category == "Overweight":
st.warning(f"Category: **{bmi_category}**")
else:
st.error(f"Category: **{bmi_category}**")
st.write("BMI Categories:")
st.write("- Underweight: < 18.5")
st.write("- Normal weight: 18.5β24.9")
st.write("- Overweight: 25β29.9")
st.write("- Obese: β₯ 30")
|