sd4m commited on
Commit
855d453
·
verified ·
1 Parent(s): 3682114

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +430 -0
app.py ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import math
3
+ import numpy as np
4
+ import pandas as pd
5
+ import plotly.graph_objects as go
6
+ import gradio as gr
7
+
8
+ # --------------------------
9
+ # CONFIG (change if you want)
10
+ # --------------------------
11
+ # High-res Mars texture (albedo). You can replace with a local file in /assets
12
+ MARS_TEXTURE_URL = "https://upload.wikimedia.org/wikipedia/commons/7/70/Solarsystemscope_texture_8k_mars.jpg"
13
+
14
+ # Jezero background image (fallback-friendly). Replace with a local /assets/jezero_bg.jpg if you prefer.
15
+ JEZERO_BG_URL = "https://upload.wikimedia.org/wikipedia/commons/1/10/Jezero_crater_delta.png"
16
+
17
+ # Visual style
18
+ TRASH_COLOR = "deepskyblue"
19
+ BOT_COLOR = "orange"
20
+
21
+
22
+ # ------------------------------------------------
23
+ # 1) LANDING & 4) CLEAN: Three.js embed (HTML)
24
+ # ------------------------------------------------
25
+ def three_js_mars_html(texture_url: str, title_text: str = "", subtitle_text: str = "") -> str:
26
+ """
27
+ Returns a self-contained HTML snippet (for gr.HTML) that renders a rotating Mars using Three.js.
28
+ Uses CDN for three.js for speed. Works in HF Spaces.
29
+ """
30
+ return f"""
31
+ <div id="mars-root" style="position:relative;width:100%;height:80vh;background:#000;overflow:hidden;border-radius:16px;">
32
+ <div style="position:absolute;top:24px;left:24px;color:#fff;font-family:system-ui,Segoe UI,Roboto,Helvetica,Arial;
33
+ text-shadow:0 2px 24px rgba(0,0,0,0.6);z-index:2">
34
+ <div style="font-size:28px;font-weight:700;letter-spacing:.3px">{title_text}</div>
35
+ <div style="opacity:.9;margin-top:6px">{subtitle_text}</div>
36
+ </div>
37
+ </div>
38
+ <script type="module">
39
+ import * as THREE from 'https://unpkg.com/three@0.160.0/build/three.module.js';
40
+ import {{ OrbitControls }} from 'https://unpkg.com/three@0.160.0/examples/jsm/controls/OrbitControls.js';
41
+
42
+ const root = document.getElementById('mars-root');
43
+ const scene = new THREE.Scene();
44
+ const camera = new THREE.PerspectiveCamera(55, root.clientWidth/root.clientHeight, 0.1, 1000);
45
+ camera.position.set(0, 0, 3.2);
46
+
47
+ const renderer = new THREE.WebGLRenderer({{ antialias: true, alpha: true }});
48
+ renderer.setSize(root.clientWidth, root.clientHeight);
49
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
50
+ root.appendChild(renderer.domElement);
51
+
52
+ // Stars background
53
+ const starsGeo = new THREE.BufferGeometry();
54
+ const starCount = 2000;
55
+ const positions = new Float32Array(starCount * 3);
56
+ for (let i=0; i<starCount; i++) {{
57
+ positions[i*3+0] = (Math.random()-0.5)*200;
58
+ positions[i*3+1] = (Math.random()-0.5)*200;
59
+ positions[i*3+2] = (Math.random()-0.5)*200;
60
+ }}
61
+ starsGeo.setAttribute('position', new THREE.BufferAttribute(positions, 3));
62
+ const stars = new THREE.Points(starsGeo, new THREE.PointsMaterial({{ size: 0.4, sizeAttenuation: true, color: 0xffffff }}));
63
+ scene.add(stars);
64
+
65
+ // Mars
66
+ const texLoader = new THREE.TextureLoader();
67
+ const marsTex = texLoader.load('{texture_url}');
68
+ const marsGeo = new THREE.SphereGeometry(1.2, 64, 64);
69
+ const marsMat = new THREE.MeshStandardMaterial({{ map: marsTex }});
70
+ const mars = new THREE.Mesh(marsGeo, marsMat);
71
+ scene.add(mars);
72
+
73
+ // Lights
74
+ const keyLight = new THREE.DirectionalLight(0xffffff, 1.3);
75
+ keyLight.position.set(5, 2, 3);
76
+ scene.add(keyLight);
77
+ scene.add(new THREE.AmbientLight(0x404040, 0.9));
78
+
79
+ const controls = new OrbitControls(camera, renderer.domElement);
80
+ controls.enablePan = false;
81
+ controls.enableZoom = false;
82
+ controls.autoRotate = true;
83
+ controls.autoRotateSpeed = 0.8;
84
+
85
+ function onResize() {{
86
+ camera.aspect = root.clientWidth / root.clientHeight;
87
+ camera.updateProjectionMatrix();
88
+ renderer.setSize(root.clientWidth, root.clientHeight);
89
+ }}
90
+ window.addEventListener('resize', onResize);
91
+
92
+ (function animate() {{
93
+ requestAnimationFrame(animate);
94
+ mars.rotation.y += 0.0009;
95
+ renderer.render(scene, camera);
96
+ }})();
97
+ </script>
98
+ """
99
+
100
+
101
+ # ------------------------------------------------
102
+ # 2) SIMULATION: Trash field + bot collecting
103
+ # ------------------------------------------------
104
+ def build_collection_animation(n_points=200, seed=42, speed=1.0):
105
+ """
106
+ Build a Plotly animated figure:
107
+ - Blue dots = trash (static positions)
108
+ - Orange triangle = bot
109
+ - Bot moves point-to-point (nearest neighbor)
110
+ - As it visits each trash point, that dot disappears
111
+ """
112
+ rng = np.random.RandomState(seed)
113
+
114
+ # Random field (rough aspect similar to Jezero crop)
115
+ x = rng.uniform(-20, 20, size=n_points)
116
+ y = rng.uniform(-12, 12, size=n_points)
117
+ pts = np.column_stack([x, y])
118
+
119
+ # Simple nearest-neighbor path starting at bottom-left
120
+ start = np.array([-19.0, -11.0])
121
+ remaining = pts.tolist()
122
+ path = [start.tolist()]
123
+ order = []
124
+
125
+ curr = start
126
+ while remaining:
127
+ dists = [np.linalg.norm(curr - np.array(p)) for p in remaining]
128
+ idx = int(np.argmin(dists))
129
+ nxt = np.array(remaining.pop(idx))
130
+ path.append(nxt.tolist())
131
+ order.append(nxt.tolist())
132
+ curr = nxt
133
+
134
+ bot_x = [p[0] for p in path]
135
+ bot_y = [p[1] for p in path]
136
+
137
+ # Base figure
138
+ fig = go.Figure()
139
+
140
+ # Background image (Jezero)
141
+ fig.update_layout(
142
+ xaxis=dict(range=[-21, 21], visible=False),
143
+ yaxis=dict(range=[-13, 13], visible=False),
144
+ margin=dict(l=0, r=0, t=0, b=0),
145
+ plot_bgcolor="black",
146
+ paper_bgcolor="black",
147
+ images=[dict(
148
+ source=JEZERO_BG_URL,
149
+ xref="x", yref="y",
150
+ x=-21, y=13,
151
+ sizex=42, sizey=26,
152
+ sizing="stretch",
153
+ layer="below"
154
+ )]
155
+ )
156
+
157
+ # Initial trash scatter (all visible)
158
+ trash_scatter = go.Scatter(
159
+ x=x, y=y,
160
+ mode="markers",
161
+ marker=dict(size=8, color=TRASH_COLOR, opacity=0.95),
162
+ name="Trash"
163
+ )
164
+ bot_scatter = go.Scatter(
165
+ x=[bot_x[0]], y=[bot_y[0]],
166
+ mode="markers",
167
+ marker=dict(size=18, color=BOT_COLOR, symbol="triangle-up"),
168
+ name="Collector bot"
169
+ )
170
+ path_trace = go.Scatter(
171
+ x=[bot_x[0]], y=[bot_y[0]],
172
+ mode="lines",
173
+ line=dict(width=2),
174
+ name="Path"
175
+ )
176
+
177
+ fig.add_trace(trash_scatter)
178
+ fig.add_trace(path_trace)
179
+ fig.add_trace(bot_scatter)
180
+
181
+ # Build frames: each frame visits one point
182
+ frames = []
183
+ trash_x = list(x)
184
+ trash_y = list(y)
185
+
186
+ for i in range(1, len(path)):
187
+ # Bot position
188
+ bx = bot_x[i]
189
+ by = bot_y[i]
190
+
191
+ # Remove the visited trash point (closest in order list)
192
+ vx, vy = order[i-1]
193
+ # Find index of that point in the trash arrays and pop it
194
+ try:
195
+ idx = trash_x.index(vx)
196
+ if abs(trash_y[idx] - vy) < 1e-9:
197
+ trash_x.pop(idx)
198
+ trash_y.pop(idx)
199
+ except ValueError:
200
+ pass
201
+
202
+ frames.append(go.Frame(
203
+ data=[
204
+ go.Scatter(x=trash_x, y=trash_y), # trash
205
+ go.Scatter(x=bot_x[:i+1], y=bot_y[:i+1]), # path so far
206
+ go.Scatter(x=[bx], y=[by]) # bot marker
207
+ ],
208
+ name=f"step{i}"
209
+ ))
210
+
211
+ fig.frames = frames
212
+
213
+ # Animation buttons
214
+ fig.update_layout(
215
+ updatemenus=[dict(
216
+ type="buttons",
217
+ x=0.02, y=0.02, xanchor="left", yanchor="bottom",
218
+ bgcolor="rgba(0,0,0,0.4)",
219
+ bordercolor="rgba(255,255,255,0.25)",
220
+ font=dict(color="white"),
221
+ buttons=[
222
+ dict(label="▶ Collect",
223
+ method="animate",
224
+ args=[None, dict(frame=dict(duration=max(30, int(70/speed)), redraw=True),
225
+ transition=dict(duration=0),
226
+ fromcurrent=True,
227
+ mode="immediate")]),
228
+ dict(label="⟳ Reset",
229
+ method="animate",
230
+ args=[[None], dict(frame=dict(duration=0, redraw=True),
231
+ transition=dict(duration=0),
232
+ mode="immediate")])
233
+ ]
234
+ )]
235
+ )
236
+
237
+ return fig
238
+
239
+
240
+ # ------------------------------------------------
241
+ # 3) CALCULATIONS: KPIs & simple model
242
+ # ------------------------------------------------
243
+ def compute_kpis(trash_kg: float, regolith_pct: int, water_L_per_kg: float,
244
+ mass_recovery_pct: int, water_recovery_pct: int, human_time_min: int):
245
+
246
+ regolith_frac = regolith_pct / 100.0
247
+ mass_recovery = mass_recovery_pct / 100.0
248
+ water_recovery = water_recovery_pct / 100.0
249
+
250
+ # Inputs
251
+ regolith_kg = trash_kg * regolith_frac
252
+ total_input_kg = trash_kg + regolith_kg
253
+
254
+ # Usable product mass
255
+ product_kg = total_input_kg * mass_recovery
256
+
257
+ # Water loop
258
+ gross_water_used_L = trash_kg * water_L_per_kg
259
+ water_recovered_L = gross_water_used_L * water_recovery
260
+ net_water_loss_L = gross_water_used_L - water_recovered_L
261
+ water_loss_per_kg = net_water_loss_L / max(trash_kg, 1e-9)
262
+
263
+ # Simple product mix (illustrative)
264
+ panels = int(max(0, product_kg // 6)) # 6 kg per interior panel (example)
265
+ boxes = int(max(0, (product_kg - panels*6) // 2))# 2 kg per storage box
266
+ utensils = int(max(0, (product_kg - panels*6 - boxes*2) // 0.1)) # 100 g each
267
+
268
+ table = pd.DataFrame({
269
+ "Indicator": [
270
+ "Trash input (kg)", "Regolith added (kg)", "Total input (kg)",
271
+ "Usable product (kg)", "Mass recovery (%)",
272
+ "Gross water used (L)", "Water recovered (L)", "Net water loss (L)", "Water loss (L/kg)",
273
+ "Crew time (min/day)"
274
+ ],
275
+ "Value": [
276
+ round(trash_kg, 2), round(regolith_kg, 2), round(total_input_kg, 2),
277
+ round(product_kg, 2), f"{mass_recovery_pct}%",
278
+ round(gross_water_used_L, 2), round(water_recovered_L, 2),
279
+ round(net_water_loss_L, 2), round(water_loss_per_kg, 3),
280
+ human_time_min
281
+ ]
282
+ })
283
+
284
+ products = pd.DataFrame({
285
+ "Product": ["Interior panels", "Storage boxes", "Utensils"],
286
+ "Estimated qty": [panels, boxes, utensils]
287
+ })
288
+
289
+ return table, products
290
+
291
+
292
+ def build_calc_figs(trash_kg, regolith_pct, water_L_per_kg, mass_recovery_pct, water_recovery_pct, human_time_min):
293
+ kpi_table, products = compute_kpis(trash_kg, regolith_pct, water_L_per_kg,
294
+ mass_recovery_pct, water_recovery_pct, human_time_min)
295
+
296
+ # Simple bars for products
297
+ bar_fig = go.Figure(data=[go.Bar(x=products["Product"], y=products["Estimated qty"])])
298
+ bar_fig.update_layout(template="plotly_dark", height=360, margin=dict(l=10, r=10, t=30, b=10))
299
+
300
+ # Sankey (optional lightweight): Inputs -> Product/Loss
301
+ total_input = trash_kg + trash_kg * (regolith_pct/100)
302
+ product_mass = total_input * (mass_recovery_pct/100)
303
+ loss_mass = total_input - product_mass
304
+
305
+ sankey = go.Figure(data=[go.Sankey(
306
+ arrangement="snap",
307
+ node=dict(
308
+ pad=12, thickness=14,
309
+ label=["Trash", "Regolith", "Total Input", "Product", "Unusable/Loss"],
310
+ color=["#3a86ff", "#a0a0a0", "#777", "#00c853", "#b00020"]
311
+ ),
312
+ link=dict(
313
+ source=[0, 1, 2, 2],
314
+ target=[2, 2, 3, 4],
315
+ value=[trash_kg, trash_kg*(regolith_pct/100), product_mass, max(0.0001, loss_mass)]
316
+ )
317
+ )])
318
+ sankey.update_layout(template="plotly_dark", height=360, margin=dict(l=10, r=10, t=30, b=10))
319
+
320
+ return kpi_table, products, bar_fig, sankey
321
+
322
+
323
+ # ------------------------------------------------
324
+ # GRADIO UI
325
+ # ------------------------------------------------
326
+ def app():
327
+ with gr.Blocks(title="MARS-LOOP — SpaceTrash Hack", theme=gr.themes.Soft(primary_hue="orange", secondary_hue="slate")) as demo:
328
+ gr.Markdown(
329
+ "<h1 style='text-align:center;margin-top:6px'>MARS-LOOP — Modular Additive Regolith-Composite Upcycling Platform</h1>"
330
+ )
331
+
332
+ # App state = which slice is visible
333
+ page = gr.State("landing")
334
+
335
+ # ------------------ LANDING ------------------
336
+ with gr.Group(visible=True) as landing:
337
+ html_landing = gr.HTML(three_js_mars_html(
338
+ MARS_TEXTURE_URL,
339
+ title_text="Welcome to Jezero Base",
340
+ subtitle_text="Trash → Regolith-reinforced products. Click to see how we clean the crater."
341
+ ))
342
+ with gr.Row():
343
+ btn_go_sim = gr.Button("Let’s see Mars trash →", size="lg")
344
+
345
+ # ------------------ SIMULATION ------------------
346
+ with gr.Group(visible=False) as sim_group:
347
+ with gr.Row():
348
+ n_points = gr.Slider(50, 600, value=250, step=10, label="Trash items (blue)")
349
+ speed = gr.Slider(0.2, 3.0, value=1.0, step=0.1, label="Animation speed")
350
+ seed = gr.Slider(0, 9999, value=42, step=1, label="Seed")
351
+ sim_plot = gr.Plot(label="Jezero Collection Simulation", height=520)
352
+ with gr.Row():
353
+ btn_simulate = gr.Button("Generate & Animate", variant="primary")
354
+ btn_to_calc = gr.Button("Next: Calculations →")
355
+
356
+ # ------------------ CALCULATIONS ------------------
357
+ with gr.Group(visible=False) as calc_group:
358
+ with gr.Row():
359
+ trash_kg = gr.Slider(10, 1000, value=100, step=10, label="Trash input (kg)")
360
+ regolith_pct = gr.Slider(0, 60, value=30, step=5, label="Regolith fraction (%)")
361
+ mass_recovery_pct = gr.Slider(50, 98, value=85, step=1, label="Mass recovery (%)")
362
+ with gr.Row():
363
+ water_L_per_kg = gr.Slider(0, 5.0, value=1.0, step=0.1, label="Wash water used (L/kg trash)")
364
+ water_recovery_pct = gr.Slider(70, 99, value=93, step=1, label="Water recovery (%)")
365
+ human_time_min = gr.Slider(0, 60, value=15, step=1, label="Crew time (min/day)")
366
+
367
+ with gr.Row():
368
+ kpi_table = gr.Dataframe(interactive=False, label="Key Performance Indicators")
369
+ with gr.Row():
370
+ bar_fig = gr.Plot(label="Estimated product quantities")
371
+ sankey_fig = gr.Plot(label="Mass balance (Sankey)")
372
+
373
+ with gr.Row():
374
+ btn_to_clean = gr.Button("Final: Clean Mars →")
375
+
376
+ # ------------------ CLEAN MARS ------------------
377
+ with gr.Group(visible=False) as clean_group:
378
+ html_clean = gr.HTML(three_js_mars_html(
379
+ MARS_TEXTURE_URL,
380
+ title_text="Jezero: Clean & Circular",
381
+ subtitle_text="Upcycling complete — panels, boxes, and tools produced from trash + regolith."
382
+ ))
383
+ gr.Markdown(
384
+ "<div style='text-align:center;opacity:.8'>Thanks to MARS-LOOP: microplastics captured, water recovered, and usable mass maximized.</div>"
385
+ )
386
+
387
+ # ------------------ CALLBACKS ------------------
388
+ def go_sim(_):
389
+ return {"landing": gr.update(visible=False),
390
+ "sim_group": gr.update(visible=True)}
391
+
392
+ btn_go_sim.click(go_sim, inputs=[page], outputs=[landing, sim_group])
393
+
394
+ def do_sim(n, s, seed_):
395
+ fig = build_collection_animation(n_points=int(n), seed=int(seed_), speed=float(s))
396
+ return fig
397
+
398
+ btn_simulate.click(do_sim, inputs=[n_points, speed, seed], outputs=[sim_plot])
399
+
400
+ def go_calc():
401
+ return {"sim_group": gr.update(visible=False),
402
+ "calc_group": gr.update(visible=True)}
403
+
404
+ btn_to_calc.click(go_calc, outputs=[sim_group, calc_group])
405
+
406
+ def run_calcs(tkg, rpct, wkg, mrpct, wrpct, cmin):
407
+ kpi, products, bar, sank = build_calc_figs(tkg, rpct, wkg, mrpct, wrpct, cmin)
408
+ return kpi, bar, sank
409
+
410
+ # Any change recomputes KPIs
411
+ for comp in [trash_kg, regolith_pct, water_L_per_kg, mass_recovery_pct, water_recovery_pct, human_time_min]:
412
+ comp.change(run_calcs,
413
+ inputs=[trash_kg, regolith_pct, water_L_per_kg, mass_recovery_pct, water_recovery_pct, human_time_min],
414
+ outputs=[kpi_table, bar_fig, sankey_fig])
415
+
416
+ # Also compute once when arriving
417
+ btn_to_calc.click(run_calcs,
418
+ inputs=[trash_kg, regolith_pct, water_L_per_kg, mass_recovery_pct, water_recovery_pct, human_time_min],
419
+ outputs=[kpi_table, bar_fig, sankey_fig])
420
+
421
+ def go_clean():
422
+ return {"calc_group": gr.update(visible=False),
423
+ "clean_group": gr.update(visible=True)}
424
+ btn_to_clean.click(go_clean, outputs=[calc_group, clean_group])
425
+
426
+ return demo
427
+
428
+
429
+ if __name__ == "__main__":
430
+ app().launch()