Spaces:
Sleeping
Sleeping
change
Browse files7 unmodified lines891011121314154 unmodified lines20212223242526272829303132333435364 unmodified lines41424344454647484950515253545556575859606162636465666768697071727374757677787 unmodified lines# 1. Load Model and Processor (CPU Optimized)model_id = "HuggingFaceTB/SmolVLM2-256M-Video-Instruct"processor = AutoProcessor.from_pretrained(model_id)# Fixed: Changed torch_dtype to dtype as per warningmodel = AutoModelForImageTextToText.from_pretrained(model_id,dtype=torch.float32,4 unmodified linesif image is None:return {"error": "No image provided"}# Resize image to 512px for speed and memory safetyimage.thumbnail((512, 512))# Nutritionist Promptprompt_text = ("Identify every food item in this image. Estimate weight in grams for each. ""Calculate calories, protein, carbs, and fat. ""Account for cooking oils. Output ONLY a JSON list.")# 2. Format Chat Templatemessages = [{"role": "user",4 unmodified lines}]# 3. Process inputsprompt = processor.apply_chat_template(messages, add_generation_prompt=True)inputs = processor(text=prompt, images=[image], return_tensors="pt").to("cpu")# 4. Generate responsewith torch.no_grad():generated_ids = model.generate(**inputs,max_new_tokens=300,do_sample=False,temperature=0.1)raw_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]# 5. Clean and parse JSONtry:json_match = re.search(r'\[.*\]', raw_text, re.DOTALL)if json_match:return json.loads(json_match.group())return {"error": "AI could not format data correctly", "raw_response": raw_text}except Exception as e:return {"error": str(e), "raw_ai_text": raw_text}# 6. UI Setup (Cleaned for Gradio 6.0)demo = gr.Interface(fn=estimate_calories,inputs=gr.Image(type="pil", label="Capture/Upload Meal"),outputs=gr.JSON(label="Nutritional Breakdown"),title="🥗 OpenCal AI",description="### Free Calorie AI (CPU Edition)\nUpload a photo to see the breakdown. Ported for Gradio 6.0 compatibility.",)# Pass theme to launch instead of Interface constructor if neededdemo.launch()7 unmodified lines89101112134 unmodified lines18192021222324252627282930313233344 unmodified lines39404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293947 unmodified lines# 1. Load Model and Processor (CPU Optimized)model_id = "HuggingFaceTB/SmolVLM2-256M-Video-Instruct"processor = AutoProcessor.from_pretrained(model_id)model = AutoModelForImageTextToText.from_pretrained(model_id,dtype=torch.float32,4 unmodified linesif image is None:return {"error": "No image provided"}# Optimization: Resize for CPU speedimage.thumbnail((512, 512))# SENIOR PROMPT: Includes a few-shot example to force accuracyprompt_text = ("You are a professional nutritionist. Identify food items and provide nutritional data in JSON format only. ""Example Output: [{'item': 'Fried Egg', 'weight_g': 50, 'calories': 90, 'protein_g': 6, 'carbs_g': 1, 'fat_g': 7}] ""Now, analyze this image and output ONLY the JSON list.")# Format Chat Templatemessages = [{"role": "user",4 unmodified lines}]prompt = processor.apply_chat_template(messages, add_generation_prompt=True)inputs = processor(text=prompt, images=[image], return_tensors="pt").to("cpu")# 4. Generate response - Fixed parameterswith torch.no_grad():generated_ids = model.generate(**inputs,max_new_tokens=400,do_sample=True, # Changed to True to allow temperature usetemperature=0.1,repetition_penalty=1.2 # Prevents the 'price_per_unit' looping error)# 5. Extract ONLY the assistant's responsegenerated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]# Split to get only the part after the promptif "Assistant:" in generated_text:assistant_part = generated_text.split("Assistant:")[-1]else:assistant_part = generated_text# 6. JSON Extraction Logictry:json_match = re.search(r'\[\s*\{.*\}\s*\]', assistant_part, re.DOTALL)if json_match:return json.loads(json_match.group())# Fallback: if model didn't use bracketsreturn {"raw_ai_analysis": assistant_part.strip()}except Exception as e:return {"error": "Parsing failed", "ai_text": assistant_part}# 7. UI Setupwith gr.Blocks(title="OpenCal AI") as demo:gr.Markdown("# 🥗 OpenCal AI")gr.Markdown("Competitor-grade nutrition analysis on a free CPU.")with gr.Row():input_img = gr.Image(type="pil", label="Upload Food")output_json = gr.JSON(label="Nutritional Data")submit_btn = gr.Button("Analyze Meal", variant="primary")# Added examples to help the model/usergr.Examples(examples=["image_760ba6.jpg"], # Make sure this file exists in your space!inputs=input_img)submit_btn.click(fn=estimate_calories, inputs=input_img, outputs=output_json)demo.launch()
app.py+43-27