uttarasawant commited on
Commit
3e3decc
·
verified ·
1 Parent(s): 8ef14c2

Update app.py to use VLM model moondream

Browse files
Files changed (1) hide show
  1. app.py +34 -57
app.py CHANGED
@@ -1,7 +1,8 @@
1
  import gradio as gr
2
  import pandas as pd
3
  from pathlib import Path
4
- from transformers import pipeline
 
5
 
6
  # =====================================================================
7
  # 💾 STATE PERSISTENCE ENGINE (Local File System Checkpoints)
@@ -39,71 +40,47 @@ def save_state_to_disk(dataframe_rows):
39
  except Exception as e:
40
  print(f"⚠️ Critical storage write failure: {e}")
41
 
42
- # =====================================================================
43
- # 🪶 LIGHTWEIGHT COMPUTATIONAL ENGINE (1B Model CPU Fallback)
44
- # =====================================================================
45
- # This initializes a lightweight TinyLlama-1.1B pipeline.
46
- # It runs lightning fast directly on Hugging Face's FREE CPU tier.
47
- print("🤖 Initializing lightweight 1B Edge-native Telemetry Model...")
48
- generator = pipeline("text-generation", model="TinyLlama/TinyLlama-1.1B-Chat-v1.0", device=-1) # device=-1 forces CPU execution
49
 
50
  def process_kitchen_operations(input_image, budget, days):
51
- """
52
- Fixed Version: Combines valid kitchen data mapping with the TinyLlama
53
- narrative engine so the dataframe state does not reset to placeholders.
54
- """
55
- # 1. Capture the image telemetry log safely
56
- if input_image is not None:
57
- width, height = input_image.size
58
- telemetry_log = f"Survey Scan Resolution: {width}x{height} pixels"
59
- else:
60
- telemetry_log = "Using baseline telemetry profile"
61
 
62
- # 2. KEEP YOUR REAL INGREDIENTS ACTIVE (Prevents resetting to milk/butter/sugar)
63
- detected_assets = [
64
- {"ingredient": "Greek Yogurt", "qty": "0.5 Liters", "status": "Fresh", "est_cost_usd": 2.50},
65
- {"ingredient": "Baby Spinach", "qty": "1 Bag", "status": "Wilting (Critical)", "est_cost_usd": 3.00},
66
- {"ingredient": "Chicken Breast", "qty": "400 Grams", "status": "Fresh", "est_cost_usd": 6.50},
67
- {"ingredient": "Yellow Onion", "qty": "1 Whole", "status": "Fresh", "est_cost_usd": 0.80}
68
- ]
69
 
70
- df_rows = [
71
- [item['ingredient'], item['qty'], item['status'], f"${item['est_cost_usd']:.2f}"]
72
- for item in detected_assets
73
- ]
74
 
75
- # Commit your clean ingredients permanently to disk!
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  save_state_to_disk(df_rows)
77
 
78
- # 3. Calculate financial data
79
  daily_budget_allowance = budget / days
 
80
 
81
- # 4. Prompt TinyLlama to generate the custom culinary routing plan
82
- prompt = (
83
- f"<|system|>\nYou are the Parallel Plate routing assistant. Based on the scanned fridge items, "
84
- f"generate a recipe routing plan. Keep it practical, professional, and limited to 2 short sentences.\n"
85
- f"<|user|>\nGenerate a plan for {days} days with a budget of ${daily_budget_allowance:.2f}/day. "
86
- f"Telemetry: {telemetry_log}.\n<|assistant|>\n"
87
- )
88
-
89
- try:
90
- model_output = generator(prompt, max_new_tokens=120, do_sample=True, temperature=0.6, top_k=50)
91
- raw_text = model_output[0]['generated_text']
92
- blueprint_md = raw_text.split("<|assistant|>\n")[-1].strip()
93
- except Exception as e:
94
- # High-quality fallback text just in case the CPU pipeline takes too long during the live demo
95
- blueprint_md = (
96
- f"**Day 1 (Asset Recovery):** Creamy Chicken & Greens Skillet. *Mitigates waste risk with $0.00 added operational cost.*\n"
97
- f"**Day 2-3 (Scarcity Allocation):** Marinated chicken bites with caramelized onions. *Hyper-low resource allocation mode engaged.*"
98
- )
99
-
100
- # Add the final formatting wrapper
101
- final_output_md = f"### 🛠️ Logistics Routing Strategy Generated via TinyLlama-1.1B\n\n"
102
- final_output_md += f"**Operational Horizon:** {days} Days | **Daily Financial Runway Ceiling:** ${daily_budget_allowance:.2f}/day\n\n"
103
- final_output_md += f"📋 **Local Cook Execution Pathway:**\n{blueprint_md}\n\n"
104
- final_output_md += f"💾 *Status: Data persistence synchronized via {telemetry_log}.*"
105
-
106
- return df_rows, final_output_md
107
 
108
  # =====================================================================
109
  # 🎨 GRADIO DASHBOARD INTERFACE
 
1
  import gradio as gr
2
  import pandas as pd
3
  from pathlib import Path
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer
5
+ from PIL import Image
6
 
7
  # =====================================================================
8
  # 💾 STATE PERSISTENCE ENGINE (Local File System Checkpoints)
 
40
  except Exception as e:
41
  print(f"⚠️ Critical storage write failure: {e}")
42
 
43
+ print("🤖 Initializing Edge-native Vision-Telemetry Model...")
44
+ model_id = "vikhyatk/moondream2"
45
+ revision = "2024-05-20" # Use a stable release
46
+ model = AutoModelForCausalLM.from_pretrained(model_id, revision=revision, trust_remote_code=True)
47
+ tokenizer = AutoTokenizer.from_pretrained(model_id, revision=revision)
 
 
48
 
49
  def process_kitchen_operations(input_image, budget, days):
50
+ if input_image is None:
51
+ # Fallback to your baseline if no image is uploaded
52
+ df_rows = load_persisted_state()
53
+ blueprint_md = "No telemetry image provided."
54
+ return df_rows, blueprint_md
 
 
 
 
 
55
 
56
+ # Ensure image is in RGB format
57
+ image = input_image.convert("RGB")
 
 
 
 
 
58
 
59
+ # 1. Ask the Vision Model to identify the items
60
+ prompt = "List the main fresh ingredients visible in this refrigerator with approximate quantities, separated by commas."
61
+ detected_text = model.answer_question(image, prompt, tokenizer)
 
62
 
63
+ # Example raw output: "Salmon fillets (2 pieces), Broccoli (1 head), Mushrooms, Lettuce"
64
+ print(f"Telemetried Inventory: {detected_text}")
65
+
66
+ # 2. Parse the text dynamically into DataFrame Rows
67
+ # (You can split the string and map defaults for status and cost)
68
+ df_rows = []
69
+ items = detected_text.split(",")
70
+ for item in items:
71
+ clean_item = item.strip()
72
+ if clean_item:
73
+ # Dynamically push parsed edge data into the twin matrix
74
+ df_rows.append([clean_item, "1 Unit", "Nominal", "$3.50"])
75
+
76
+ # Save the real detected state to disk
77
  save_state_to_disk(df_rows)
78
 
79
+ # 3. Pass this data to your recipe generation string...
80
  daily_budget_allowance = budget / days
81
+ blueprint_md = f"Plan optimized for identified assets: {detected_text}."
82
 
83
+ return df_rows, blueprint_md
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
  # =====================================================================
86
  # 🎨 GRADIO DASHBOARD INTERFACE