Spaces:
Sleeping

calorie-tracker / app.py
lou693's picture
robust dev
22890dd
Raw History Blame Contribute Delete
2.93 kB
import gradio as gr
import torch
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info
import re
import json
# 1. LOAD THE 2B MODEL (CPU Optimized)
MODEL_ID = "Qwen/Qwen2-VL-2B-Instruct"
# Senior Tip: Check for CUDA, otherwise default to CPU
device = "cuda" if torch.cuda.is_available() else "cpu"
model = Qwen2VLForConditionalGeneration.from_pretrained(
MODEL_ID,
torch_dtype="auto",
device_map=device
)
processor = AutoProcessor.from_pretrained(MODEL_ID)
def analyze_macros(image):
if image is None: return None, "### โš ๏ธ Please upload an image."
prompt = (
"Identify food items. Estimate weights. Calculate Calories, Protein, Fat, and Carbs. "
"Output ONLY a valid JSON: "
'{"items": [{"name": "item", "weight": 0, "cal": 0, "p": 0, "f": 0, "c": 0}]}'
)
messages = [
{
"role": "user",
"content": [
{"type": "image", "image": image},
{"type": "text", "text": prompt},
],
}
]
# Pre-processing using qwen_vl_utils (requires torchvision)
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
image_inputs, _ = process_vision_info(messages)
inputs = processor(
text=[text],
images=image_inputs,
padding=True,
return_tensors="pt",
).to(device)
# Generate
with torch.no_grad():
generated_ids = model.generate(**inputs, max_new_tokens=512)
generated_text = processor.batch_decode(
generated_ids, skip_special_tokens=True
)[0]
try:
# Extract JSON
json_str = re.search(r"\{.*\}", generated_text, re.DOTALL).group()
data = json.loads(json_str.replace("'", '"'))
items = data.get("items", [])
# 4-9-4 Logic for absolute scientific accuracy
p = sum(float(i.get("p", 0)) for i in items)
f = sum(float(i.get("f", 0)) for i in items)
c = sum(float(i.get("c", 0)) for i in items)
total_cal = (p * 4) + (f * 9) + (c * 4)
summary = (
f"### โœ… Meal Analysis\n"
f"**Total Energy:** {round(total_cal, 1)} kcal\n\n"
f"**Macros:** P: {p}g | F: {f}g | C: {c}g"
)
return items, summary
except Exception:
return None, f"### โŒ Parsing Error\nAI responded: {generated_text[:200]}"
# UI
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("# ๐Ÿฅ— OpenCal AI (Stable 2B)")
with gr.Row():
input_img = gr.Image(type="pil")
with gr.Column():
output_md = gr.Markdown("Waiting for image...")
output_json = gr.JSON(label="Ingredient Stats")
btn = gr.Button("๐Ÿš€ Analyze Meal", variant="primary")
btn.click(analyze_macros, inputs=input_img, outputs=[output_json, output_md])
demo.launch()