Spaces:
Sleeping

diet / src /streamlit_app.py
faiz3123's picture
Update src/streamlit_app.py
9b10be3 verified
Raw History Blame Contribute Delete
3.82 kB
import streamlit as st
import requests
import base64
import io
from PIL import Image
import pandas as pd
from datetime import datetime
import re
# =========================
# Streamlit setup
# =========================
st.set_page_config(page_title="Calorie Tracker", layout="wide")
st.title("πŸ₯¦ Smart Calorie Tracker (No DB Mode)")
# =========================
# βš™οΈ API key (store securely in practice)
# =========================
OPENROUTER_API_KEY = "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" # ← insert your actual key here temporarily
API_URL = "https://openrouter.ai/api/v1/chat/completions"
# =========================
# Initialize session state storage
# =========================
if "entries" not in st.session_state:
st.session_state.entries = [] # list of dicts: {date, food_name, calories}
def estimate_calories(image):
"""Send image to AI model and return estimated calories and food info"""
buffered = io.BytesIO()
image.save(buffered, format="PNG")
img_b64 = base64.b64encode(buffered.getvalue()).decode()
response = requests.post(
API_URL,
headers={
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
"HTTP-Referer": "http://localhost",
"X-Title": "Calorie Tracker App"
},
json={
"model": "gpt-4o-mini",
"messages": [
{"role": "system",
"content": "You are a nutrition assistant. Identify the food and estimate calories from a photo."},
{"role": "user",
"content": [
{"type": "text", "text": "Estimate the calories in this meal:"},
{"type": "image", "image": f"data:image/png;base64,{img_b64}"}
]}
]
}
)
data = response.json()
try:
result_text = data["choices"][0]["message"]["content"]
except Exception as e:
result_text = f"Error getting model response: {e}\n\n{data}"
return result_text
# =========================
# Upload section
# =========================
uploaded_file = st.file_uploader("Upload a photo of your meal", type=["jpg", "jpeg", "png"])
if uploaded_file is not None:
image = Image.open(uploaded_file)
st.image(image, caption="Uploaded Image", width=300)
if st.button("Analyze"):
with st.spinner("Analyzing image..."):
result = estimate_calories(image)
st.subheader("AI Estimation:")
st.write(result)
# Heuristic: extract number of calories
m = re.search(r"(\d+)\s*cal", result.lower())
cal = float(m.group(1)) if m else 0.0
if cal > 0:
st.session_state.entries.append({
"date": datetime.now().strftime("%Y-%m-%d"),
"food_name": "Detected Meal",
"calories": cal
})
st.success(f"Added {cal:.1f} calories to today's record βœ…")
# =========================
# Daily summary
# =========================
st.header("πŸ“… Daily Summary")
today = datetime.now().strftime("%Y-%m-%d")
today_entries = [e for e in st.session_state.entries if e["date"] == today]
if today_entries:
df_today = pd.DataFrame(today_entries)
total = df_today["calories"].sum()
st.metric("Today's Total Calories", f"{total:.1f} kcal")
st.dataframe(df_today[["food_name", "calories"]])
else:
st.info("No entries for today.")
# =========================
# Historical summary (session only)
# =========================
st.header("πŸ“Š Weekly Overview")
if st.session_state.entries:
df_all = pd.DataFrame(st.session_state.entries)
summary = df_all.groupby("date")["calories"].sum().reset_index()
st.bar_chart(summary.set_index("date"))
else:
st.write("No records yet.")