uttarasawant commited on
Commit
52468e0
·
verified ·
1 Parent(s): 762f51c

Update app.py with stateful data save

Browse files
Files changed (1) hide show
  1. app.py +198 -80
app.py CHANGED
@@ -1,107 +1,80 @@
1
  import gradio as gr
2
  import pandas as pd
3
- import torch
4
- from transformers import AutoTokenizer, AutoModelForCausalLM
5
- import json
6
- import re
7
 
8
  # =====================================================================
9
- # 🧠 LIVE 1B MODEL INFRASTRUCTURE (CPU Native - Well-Tuned Track)
10
  # =====================================================================
11
- # TinyLlama is ideal for CPU execution, staying well under the 16GB RAM limit.
12
- model_id = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
13
-
14
- print("Initializing tokenizer...")
15
- tokenizer = AutoTokenizer.from_pretrained(model_id)
16
- print("Loading model weights onto CPU baseline...")
17
- model = AutoModelForCausalLM.from_pretrained(
18
- model_id,
19
- torch_dtype=torch.float32, # Standard float32 ensures clean CPU calculations
20
- device_map="cpu"
21
- )
22
- print("Model infrastructure ready.")
23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  def process_kitchen_operations(input_image, budget, days):
25
- # Fallback deterministic items if text parser drops tokens
26
- fallback_items = [
27
  {"ingredient": "Greek Yogurt", "qty": "0.5 Liters", "status": "Fresh", "est_cost_usd": 2.50},
28
  {"ingredient": "Baby Spinach", "qty": "1 Bag", "status": "Wilting (Critical)", "est_cost_usd": 3.00},
29
  {"ingredient": "Chicken Breast", "qty": "400 Grams", "status": "Fresh", "est_cost_usd": 6.50},
30
  {"ingredient": "Yellow Onion", "qty": "1 Whole", "status": "Fresh", "est_cost_usd": 0.80}
31
  ]
32
 
33
- # 1. Structure prompt for the fine-tuned 1B model to run logistics mapping
34
- system_prompt = (
35
- "You are an industrial logistics warehouse agent tracking kitchen storage inventory assets. "
36
- "Generate a short, strict JSON list containing 4 ingredients currently inside a refrigerator. "
37
- "Use exactly these keys: 'ingredient', 'qty', 'status', 'est_cost_usd'."
38
- )
39
-
40
- messages = [
41
- {"role": "system", "content": system_prompt},
42
- {"role": "user", "content": "Output the inventory array block now."}
43
- ]
44
-
45
- # Format prompt natively using TinyLlama's chat template structure
46
- prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
47
- inputs = tokenizer(prompt, return_tensors="pt").to("cpu")
48
-
49
- # 2. Local CPU Token Generation Loop
50
- with torch.no_grad():
51
- outputs = model.generate(
52
- **inputs,
53
- max_new_tokens=256,
54
- temperature=0.2,
55
- do_sample=True
56
- )
57
-
58
- raw_output = tokenizer.decode(outputs[0][len(inputs.input_ids[0]):], skip_special_tokens=True)
59
-
60
- # 3. Parse JSON Array out of the model generation string
61
- try:
62
- json_match = re.search(r"\[\s*\{.*\}\s*\]", raw_output, re.DOTALL)
63
- if json_match:
64
- detected_assets = json.loads(json_match.group(0))
65
- else:
66
- detected_assets = fallback_items
67
- except Exception:
68
- detected_assets = fallback_items
69
-
70
- # 4. Map results dynamically into our Digital Twin Dataframe format
71
  df_rows = [
72
- [item.get('ingredient', 'Asset'), item.get('qty', '1 Unit'), item.get('status', 'Nominal'), f"${float(item.get('est_cost_usd', 1.0)):.2f}"]
73
  for item in detected_assets
74
  ]
75
 
76
- # 5. Constraint-Based Budget Optimization Logic
 
 
 
77
  daily_budget_allowance = budget / days
78
- critical_items = [item.get('ingredient') for item in detected_assets if "Wilting" in str(item.get('status'))]
79
 
80
- # Generate the Dynamic Markdown Strategy Blueprint
81
- blueprint_md = f"### 🛠️ Logistics Routing Strategy Generated via {model_id}\n"
82
  blueprint_md += f"**Operational Horizon:** {days} Days | **Daily Financial Runway Ceiling:** ${daily_budget_allowance:.2f}/day\n\n"
 
83
 
84
- if critical_items:
85
- blueprint_md += "#### 🚨 High-Decay Asset Prioritization (Use Immediately):\n"
86
- for item in critical_items:
87
- blueprint_md += f"- **{item}** showing critical decay telemetry indices. Scheduled for immediate ingestion into Day 1.\n"
88
-
89
- blueprint_md += "\n#### 📋 Local Cook Execution Pathway:\n"
90
- blueprint_md += f"- **Day 1 (Asset Recovery):** Creamy Chicken & Greens Skillet. *Mitigates waste risk with $0.00 added operational cost.*\n"
91
-
92
- if daily_budget_allowance < 10.00:
93
- blueprint_md += "- **Day 2-3 (Scarcity Allocation):** Marinated chicken bites with caramelized onions. *Hyper-low resource allocation mode engaged.*"
94
- else:
95
- blueprint_md += "- **Day 2-3 (Nominal Operations):** Pan-seared protein paired with fresh custom balanced sides. *Optimal balanced strategy.*"
96
-
97
  return df_rows, blueprint_md
98
 
99
  # =====================================================================
100
- # 🎨 GRADIO 6.0 MOCK INTERFACE ARCHITECTURE
101
  # =====================================================================
102
  with gr.Blocks() as demo:
103
  gr.Markdown("# 🛰️ Parallel Plate: Kitchen Operations & Visual Logistics Engine")
104
- gr.Markdown("### *Physical-to-Digital Twin Asset Management Pipeline (Badge Tier: 🎯 Well-Tuned | HW: 💻 CPU Free)*")
105
 
106
  with gr.Row():
107
  with gr.Column(scale=1):
@@ -114,7 +87,6 @@ with gr.Blocks() as demo:
114
 
115
  scan_btn = gr.Button("🚀 Initialize Asset Optimization Scan", variant="primary")
116
 
117
- # Right Operational Node: Real-time State Machine Telemetry
118
  with gr.Column(scale=1):
119
  gr.Markdown("### 📊 2. Active Refrigerator Digital Twin")
120
  inventory_df = gr.Dataframe(
@@ -122,8 +94,9 @@ with gr.Blocks() as demo:
122
  datatype=["str", "str", "str", "str"],
123
  label="Live Operational Asset Manifest",
124
  interactive=True,
125
- wrap=True, # Ensures text wraps cleanly inside rows instead of clipping
126
- column_widths=["30%", "25%", "25%", "20%"] # Allocates perfect horizontal space per column
 
127
  )
128
 
129
  gr.Markdown("### 🔀 3. Resource Routing & Recipe Output")
@@ -138,6 +111,151 @@ with gr.Blocks() as demo:
138
  if __name__ == "__main__":
139
  demo.launch(theme=gr.themes.Monochrome())
140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  #######################################################################################################################################
142
  #trial 2
143
 
 
1
  import gradio as gr
2
  import pandas as pd
3
+ from pathlib import Path
 
 
 
4
 
5
  # =====================================================================
6
+ # 💾 STATE PERSISTENCE ENGINE (Local File System Checkpoints)
7
  # =====================================================================
8
+ STORAGE_PATH = Path("state_manifest.csv")
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ def load_persisted_state():
11
+ """Reads the asset manifest from the local disk partition upon boot."""
12
+ if STORAGE_PATH.exists():
13
+ try:
14
+ print("💾 Persistent storage record detected. Loading digital twin...")
15
+ df = pd.read_csv(STORAGE_PATH)
16
+ # Ensure compliance with standard dashboard schema
17
+ if list(df.columns) == ["Ingredient Asset", "Current Volume / Qty", "Telemetry Status", "Book Value (Est)"]:
18
+ return df.values.tolist()
19
+ except Exception as e:
20
+ print(f"⚠️ State reconstruction exception: {e}")
21
+
22
+ # Default baseline parameters if no checkpoint exists
23
+ return [
24
+ ["Greek Yogurt", "0.5 Liters", "Fresh", "$2.50"],
25
+ ["Baby Spinach", "1 Bag", "Wilting (Critical)", "$3.00"],
26
+ ["Chicken Breast", "400 Grams", "Fresh", "$6.50"],
27
+ ["Yellow Onion", "1 Whole", "Fresh", "$0.80"]
28
+ ]
29
+
30
+ def save_state_to_disk(dataframe_rows):
31
+ """Commits the current state machine rows permanently to the disk."""
32
+ try:
33
+ df = pd.DataFrame(
34
+ dataframe_rows,
35
+ columns=["Ingredient Asset", "Current Volume / Qty", "Telemetry Status", "Book Value (Est)"]
36
+ )
37
+ df.to_csv(STORAGE_PATH, index=False)
38
+ print("💾 Digital twin state successfully synced to disk partition.")
39
+ except Exception as e:
40
+ print(f"⚠️ Critical storage write failure: {e}")
41
+
42
+ # =====================================================================
43
+ # 🔀 COMPUTATIONAL ENGINE (CPU-Optimized Realignment Matrix)
44
+ # =====================================================================
45
  def process_kitchen_operations(input_image, budget, days):
46
+ # Simulated execution mapping using our validated manifest data
47
+ detected_assets = [
48
  {"ingredient": "Greek Yogurt", "qty": "0.5 Liters", "status": "Fresh", "est_cost_usd": 2.50},
49
  {"ingredient": "Baby Spinach", "qty": "1 Bag", "status": "Wilting (Critical)", "est_cost_usd": 3.00},
50
  {"ingredient": "Chicken Breast", "qty": "400 Grams", "status": "Fresh", "est_cost_usd": 6.50},
51
  {"ingredient": "Yellow Onion", "qty": "1 Whole", "status": "Fresh", "est_cost_usd": 0.80}
52
  ]
53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  df_rows = [
55
+ [item['ingredient'], item['qty'], item['status'], f"${item['est_cost_usd']:.2f}"]
56
  for item in detected_assets
57
  ]
58
 
59
+ # Commit changes immediately to persistent layer
60
+ save_state_to_disk(df_rows)
61
+
62
+ # Calculate constraint ceilings
63
  daily_budget_allowance = budget / days
64
+ critical_items = [item['ingredient'] for item in detected_assets if "Wilting" in item['status']]
65
 
66
+ blueprint_md = f"### 🛠️ Logistics Routing Strategy Generated\n"
 
67
  blueprint_md += f"**Operational Horizon:** {days} Days | **Daily Financial Runway Ceiling:** ${daily_budget_allowance:.2f}/day\n\n"
68
+ blueprint_md += f"💾 *Status: Data persistence synchronized to local storage partition.*"
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  return df_rows, blueprint_md
71
 
72
  # =====================================================================
73
+ # 🎨 GRADIO 6.0 STATEFUL DASHBOARD INTERFACE
74
  # =====================================================================
75
  with gr.Blocks() as demo:
76
  gr.Markdown("# 🛰️ Parallel Plate: Kitchen Operations & Visual Logistics Engine")
77
+ gr.Markdown("### *Physical-to-Digital Twin Asset Management Pipeline (Hardware Tier: 💻 CPU Free)*")
78
 
79
  with gr.Row():
80
  with gr.Column(scale=1):
 
87
 
88
  scan_btn = gr.Button("🚀 Initialize Asset Optimization Scan", variant="primary")
89
 
 
90
  with gr.Column(scale=1):
91
  gr.Markdown("### 📊 2. Active Refrigerator Digital Twin")
92
  inventory_df = gr.Dataframe(
 
94
  datatype=["str", "str", "str", "str"],
95
  label="Live Operational Asset Manifest",
96
  interactive=True,
97
+ wrap=True,
98
+ column_widths=["30%", "25%", "25%", "20%"],
99
+ value=load_persisted_state() # Auto-injects last known state at container boot
100
  )
101
 
102
  gr.Markdown("### 🔀 3. Resource Routing & Recipe Output")
 
111
  if __name__ == "__main__":
112
  demo.launch(theme=gr.themes.Monochrome())
113
 
114
+
115
+ #######################################################################################################################################
116
+ #trial 3
117
+
118
+
119
+ # import gradio as gr
120
+ # import pandas as pd
121
+ # import torch
122
+ # from transformers import AutoTokenizer, AutoModelForCausalLM
123
+ # import json
124
+ # import re
125
+
126
+ # # =====================================================================
127
+ # # 🧠 LIVE 1B MODEL INFRASTRUCTURE (CPU Native - Well-Tuned Track)
128
+ # # =====================================================================
129
+ # # TinyLlama is ideal for CPU execution, staying well under the 16GB RAM limit.
130
+ # model_id = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
131
+
132
+ # print("Initializing tokenizer...")
133
+ # tokenizer = AutoTokenizer.from_pretrained(model_id)
134
+ # print("Loading model weights onto CPU baseline...")
135
+ # model = AutoModelForCausalLM.from_pretrained(
136
+ # model_id,
137
+ # torch_dtype=torch.float32, # Standard float32 ensures clean CPU calculations
138
+ # device_map="cpu"
139
+ # )
140
+ # print("Model infrastructure ready.")
141
+
142
+ # def process_kitchen_operations(input_image, budget, days):
143
+ # # Fallback deterministic items if text parser drops tokens
144
+ # fallback_items = [
145
+ # {"ingredient": "Greek Yogurt", "qty": "0.5 Liters", "status": "Fresh", "est_cost_usd": 2.50},
146
+ # {"ingredient": "Baby Spinach", "qty": "1 Bag", "status": "Wilting (Critical)", "est_cost_usd": 3.00},
147
+ # {"ingredient": "Chicken Breast", "qty": "400 Grams", "status": "Fresh", "est_cost_usd": 6.50},
148
+ # {"ingredient": "Yellow Onion", "qty": "1 Whole", "status": "Fresh", "est_cost_usd": 0.80}
149
+ # ]
150
+
151
+ # # 1. Structure prompt for the fine-tuned 1B model to run logistics mapping
152
+ # system_prompt = (
153
+ # "You are an industrial logistics warehouse agent tracking kitchen storage inventory assets. "
154
+ # "Generate a short, strict JSON list containing 4 ingredients currently inside a refrigerator. "
155
+ # "Use exactly these keys: 'ingredient', 'qty', 'status', 'est_cost_usd'."
156
+ # )
157
+
158
+ # messages = [
159
+ # {"role": "system", "content": system_prompt},
160
+ # {"role": "user", "content": "Output the inventory array block now."}
161
+ # ]
162
+
163
+ # # Format prompt natively using TinyLlama's chat template structure
164
+ # prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
165
+ # inputs = tokenizer(prompt, return_tensors="pt").to("cpu")
166
+
167
+ # # 2. Local CPU Token Generation Loop
168
+ # with torch.no_grad():
169
+ # outputs = model.generate(
170
+ # **inputs,
171
+ # max_new_tokens=256,
172
+ # temperature=0.2,
173
+ # do_sample=True
174
+ # )
175
+
176
+ # raw_output = tokenizer.decode(outputs[0][len(inputs.input_ids[0]):], skip_special_tokens=True)
177
+
178
+ # # 3. Parse JSON Array out of the model generation string
179
+ # try:
180
+ # json_match = re.search(r"\[\s*\{.*\}\s*\]", raw_output, re.DOTALL)
181
+ # if json_match:
182
+ # detected_assets = json.loads(json_match.group(0))
183
+ # else:
184
+ # detected_assets = fallback_items
185
+ # except Exception:
186
+ # detected_assets = fallback_items
187
+
188
+ # # 4. Map results dynamically into our Digital Twin Dataframe format
189
+ # df_rows = [
190
+ # [item.get('ingredient', 'Asset'), item.get('qty', '1 Unit'), item.get('status', 'Nominal'), f"${float(item.get('est_cost_usd', 1.0)):.2f}"]
191
+ # for item in detected_assets
192
+ # ]
193
+
194
+ # # 5. Constraint-Based Budget Optimization Logic
195
+ # daily_budget_allowance = budget / days
196
+ # critical_items = [item.get('ingredient') for item in detected_assets if "Wilting" in str(item.get('status'))]
197
+
198
+ # # Generate the Dynamic Markdown Strategy Blueprint
199
+ # blueprint_md = f"### 🛠️ Logistics Routing Strategy Generated via {model_id}\n"
200
+ # blueprint_md += f"**Operational Horizon:** {days} Days | **Daily Financial Runway Ceiling:** ${daily_budget_allowance:.2f}/day\n\n"
201
+
202
+ # if critical_items:
203
+ # blueprint_md += "#### 🚨 High-Decay Asset Prioritization (Use Immediately):\n"
204
+ # for item in critical_items:
205
+ # blueprint_md += f"- **{item}** showing critical decay telemetry indices. Scheduled for immediate ingestion into Day 1.\n"
206
+
207
+ # blueprint_md += "\n#### 📋 Local Cook Execution Pathway:\n"
208
+ # blueprint_md += f"- **Day 1 (Asset Recovery):** Creamy Chicken & Greens Skillet. *Mitigates waste risk with $0.00 added operational cost.*\n"
209
+
210
+ # if daily_budget_allowance < 10.00:
211
+ # blueprint_md += "- **Day 2-3 (Scarcity Allocation):** Marinated chicken bites with caramelized onions. *Hyper-low resource allocation mode engaged.*"
212
+ # else:
213
+ # blueprint_md += "- **Day 2-3 (Nominal Operations):** Pan-seared protein paired with fresh custom balanced sides. *Optimal balanced strategy.*"
214
+
215
+ # return df_rows, blueprint_md
216
+
217
+ # # =====================================================================
218
+ # # 🎨 GRADIO 6.0 MOCK INTERFACE ARCHITECTURE
219
+ # # =====================================================================
220
+ # with gr.Blocks() as demo:
221
+ # gr.Markdown("# 🛰️ Parallel Plate: Kitchen Operations & Visual Logistics Engine")
222
+ # gr.Markdown("### *Physical-to-Digital Twin Asset Management Pipeline (Badge Tier: 🎯 Well-Tuned | HW: 💻 CPU Free)*")
223
+
224
+ # with gr.Row():
225
+ # with gr.Column(scale=1):
226
+ # gr.Markdown("### 📸 1. Physical Edge Ingestion")
227
+ # image_input = gr.Image(label="Upload Fridge Optical Survey Scan", type="pil")
228
+
229
+ # with gr.Row():
230
+ # budget_slider = gr.Slider(minimum=5, maximum=100, value=25, step=5, label="Runway Budget ($ USD)")
231
+ # days_slider = gr.Slider(minimum=1, maximum=7, value=3, step=1, label="Target Horizon (Days)")
232
+
233
+ # scan_btn = gr.Button("🚀 Initialize Asset Optimization Scan", variant="primary")
234
+
235
+ # # Right Operational Node: Real-time State Machine Telemetry
236
+ # with gr.Column(scale=1):
237
+ # gr.Markdown("### 📊 2. Active Refrigerator Digital Twin")
238
+ # inventory_df = gr.Dataframe(
239
+ # headers=["Ingredient Asset", "Current Volume / Qty", "Telemetry Status", "Book Value (Est)"],
240
+ # datatype=["str", "str", "str", "str"],
241
+ # label="Live Operational Asset Manifest",
242
+ # interactive=True,
243
+ # wrap=True, # Ensures text wraps cleanly inside rows instead of clipping
244
+ # column_widths=["30%", "25%", "25%", "20%"] # Allocates perfect horizontal space per column
245
+ # )
246
+
247
+ # gr.Markdown("### 🔀 3. Resource Routing & Recipe Output")
248
+ # output_text = gr.Markdown("*Awaiting asset telemetry mapping to generate optimal cooking execution paths...*")
249
+
250
+ # scan_btn.click(
251
+ # fn=process_kitchen_operations,
252
+ # inputs=[image_input, budget_slider, days_slider],
253
+ # outputs=[inventory_df, output_text]
254
+ # )
255
+
256
+ # if __name__ == "__main__":
257
+ # demo.launch(theme=gr.themes.Monochrome())
258
+
259
  #######################################################################################################################################
260
  #trial 2
261