ginnyxxxxxxx commited on
Commit
75ab97e
Β·
1 Parent(s): 01349e5
Files changed (1) hide show
  1. app.py +503 -263
app.py CHANGED
@@ -144,298 +144,538 @@ def build_weekly_checkin(agent_sp, max_days=None):
144
 
145
  # ── HTML reasoning chain ──────────────────────────────────────────────────────
146
 
 
 
 
 
147
  CHAIN_CSS = """
148
  <style>
149
- @import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@300;400;600&display=swap');
150
-
151
- .hicotraj-chain { font-family: 'IBM Plex Sans', sans-serif; padding: 12px 4px; }
 
 
 
 
 
 
152
 
153
- .stage-card {
154
- border-radius: 10px; padding: 16px 18px; margin-bottom: 0;
155
- transition: opacity 0.4s, filter 0.4s;
 
 
156
  }
157
- .stage-card.dim { opacity: 0.32; filter: grayscale(0.5); }
158
- .stage-card.active { opacity: 1; filter: none; }
159
-
160
- .stage-card.s1 { background: #f8f9fc; border: 1.5px solid #c8d0e0; }
161
- .stage-card.s2 { background: #fdf6f0; border: 1.5px solid #e8c9a8; }
162
- .stage-card.s3 { background: #fff8f8; border: 2px solid #c0392b; }
163
-
164
- .stage-header { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; }
165
- .stage-badge {
166
- font-family: 'IBM Plex Mono', monospace;
167
- font-size: 10px; font-weight: 600; letter-spacing: 0.08em;
168
- padding: 3px 8px; border-radius: 4px; text-transform: uppercase;
169
  }
170
- .s1 .stage-badge { background: #dde3f0; color: #3a4a6b; }
171
- .s2 .stage-badge { background: #f0dcc8; color: #7a4010; }
172
- .s3 .stage-badge { background: #c0392b; color: #fff; }
173
- .stage-title { font-size: 13px; font-weight: 600; color: #1a1a2e; }
174
-
175
- .tag-row { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 4px; }
176
- .tag {
177
- font-family: 'IBM Plex Mono', monospace; font-size: 11px;
178
- background: #e8ecf5; color: #2c3e60;
179
- padding: 3px 8px; border-radius: 4px; white-space: nowrap;
 
 
 
180
  }
181
 
182
- .behavior-row {
183
- display: grid; grid-template-columns: 100px 1fr;
184
- gap: 4px 10px; margin-top: 2px; font-size: 12px; line-height: 1.6;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  }
186
- .bkey {
187
- font-family: 'IBM Plex Mono', monospace; font-size: 11px;
188
- font-weight: 600; color: #9b6a3a; padding-top: 1px;
 
 
 
 
 
 
 
 
 
189
  }
190
- .bval { color: #3a2a1a; }
191
 
192
- .pred-block { margin-top: 4px; }
193
- .pred-label {
194
- font-size: 11px; font-family: 'IBM Plex Mono', monospace; color: #888;
195
- text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 4px;
 
 
196
  }
197
- .pred-value { font-size: 22px; font-weight: 600; color: #c0392b; margin-bottom: 8px; }
198
- .confidence-bar-wrap { display: flex; align-items: center; gap: 10px; margin-bottom: 10px; }
199
- .confidence-bar-bg { flex: 1; height: 6px; background: #f0d0cf; border-radius: 3px; overflow: hidden; }
200
- .confidence-bar-fill { height: 100%; background: linear-gradient(90deg, #e74c3c, #8b0000); border-radius: 3px; }
201
- .confidence-label { font-family: 'IBM Plex Mono', monospace; font-size: 11px; color: #c0392b; font-weight: 600; white-space: nowrap; }
202
- .reasoning-text { font-size: 12px; color: #4a2a2a; line-height: 1.6; border-left: 3px solid #e8c0be; padding-left: 10px; margin-top: 6px; }
203
- .alternatives { margin-top: 10px; font-size: 11px; font-family: 'IBM Plex Mono', monospace; color: #999; }
204
- .alternatives span { color: #c0392b; opacity: 0.7; }
205
-
206
- .chain-arrow { display: flex; flex-direction: column; align-items: center; padding: 4px 0; transition: opacity 0.4s; }
207
- .arrow-line { width: 2px; height: 16px; background: #d0c0b0; }
208
- .arrow-label {
209
- font-family: 'IBM Plex Mono', monospace; font-size: 10px; color: #aaa;
210
- letter-spacing: 0.06em; text-transform: uppercase;
211
- background: white; padding: 2px 8px; border: 1px solid #e0e0e0; border-radius: 10px; margin: 2px 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  }
213
- .arrow-tip { width: 0; height: 0; border-left: 5px solid transparent; border-right: 5px solid transparent; border-top: 7px solid #d0c0b0; }
214
-
215
- .thinking { font-size: 13px; color: #888; padding: 8px 0; }
216
- .empty-hint { font-size: 12px; color: #ccc; padding: 6px 0; }
217
- .temporal-line { font-size: 11px; color: #666; margin-top: 8px; font-family: 'IBM Plex Mono', monospace; }
218
 
219
- .prompt-snippet {
220
- font-size: 11px; color: #888; line-height: 1.5;
221
- background: rgba(0,0,0,0.03); border-left: 2px solid #ddd;
222
- padding: 6px 10px; border-radius: 0 4px 4px 0;
223
- margin-bottom: 8px; font-family: 'IBM Plex Mono', monospace;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  }
225
- .prompt-label {
226
- display: inline-block; font-size: 9px; font-weight: 600;
227
- text-transform: uppercase; letter-spacing: 0.08em;
228
- color: #aaa; margin-right: 6px;
229
- background: #eee; padding: 1px 5px; border-radius: 3px;
230
  }
231
- .resp-label {
232
- font-size: 9px; font-weight: 600; text-transform: uppercase;
233
- letter-spacing: 0.08em; color: #aaa; margin-bottom: 4px;
234
- display: inline-block; background: #eee; padding: 1px 5px; border-radius: 3px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
  }
236
 
237
- .wd {
238
- display: inline-block; width: 6px; height: 6px; border-radius: 50%;
239
- background: currentColor; margin: 0 2px; opacity: 0.3;
240
- animation: wd-pulse 1.2s ease-in-out infinite;
 
241
  }
242
- .wd:nth-child(2) { animation-delay: 0.2s; }
243
- .wd:nth-child(3) { animation-delay: 0.4s; }
244
- @keyframes wd-pulse {
245
- 0%, 100% { opacity: 0.2; transform: scale(0.8); }
246
- 50% { opacity: 1; transform: scale(1.1); }
 
247
  }
 
 
 
248
  </style>
249
  """
250
 
251
 
252
- def _dots():
253
- return '<span class="wd"></span><span class="wd"></span><span class="wd"></span>'
254
-
255
-
256
- def render_chain(s1_text, s2_text, s3_text, status="done"):
257
- s1_active = status in ("running1", "running2", "running3", "done")
258
- s2_active = status in ("running2", "running3", "done")
259
- s3_active = status in ("running3", "done")
260
-
261
- # ── Stage 1: Location pills + temporal line ───────────────────────────────
262
- if status == "running1":
263
- s1_content = f'<div class="thinking">Extracting features {_dots()}</div>'
264
- elif s1_text:
265
- tags = []
266
- lines = s1_text.splitlines()
267
- # Find frequency section: "Frequency of visits" or direct "- Name: N visits"
268
- freq_mode = False
269
- for line in lines:
270
- stripped = line.strip()
271
- if not stripped:
272
- continue
273
- # Enter frequency section
274
- if re.search(r'frequency of visits', stripped, re.IGNORECASE):
275
- freq_mode = True
276
- continue
277
- # Exit on next section heading
278
- if freq_mode and re.match(r'^[A-Z][A-Z\s]+:', stripped) and not stripped.startswith('-'):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
  break
280
- if freq_mode and stripped.startswith('-'):
281
- # "- Name: N visits" or " - Name: N visits"
282
- m = re.match(r'-+\s*(.+?):\s*(\d+)\s*visit', stripped, re.IGNORECASE)
283
- if m:
284
- tags.append(f"{m.group(1).strip()} Β· {m.group(2)}x")
285
- if len(tags) >= 8:
286
- break
287
- continue
288
- # Fallback: direct "- Name: N visits, description" under LOCATION INVENTORY
289
- if not freq_mode:
290
- m = re.match(r'-\s*(.+?):\s*(\d+)\s*visit', stripped, re.IGNORECASE)
291
- if m and 'LOCATION' not in stripped.upper():
292
- tags.append(f"{m.group(1).strip()} Β· {m.group(2)}x")
293
- if len(tags) >= 8:
294
- break
295
-
296
- # Temporal summary line
297
- temporal_line = ""
298
- for line in lines:
299
- stripped = line.strip().lstrip('-').strip()
300
- if re.search(r'\d+%\s*weekday', stripped, re.IGNORECASE):
301
- temporal_line = stripped[:80]
302
  break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
303
 
304
- tag_html = "".join(f'<span class="tag">{t}</span>' for t in tags)
305
- temp_html = f'<div class="temporal-line">⏱ {temporal_line}</div>' if temporal_line else ""
306
- s1_content = f'<div class="tag-row">{tag_html}</div>{temp_html}'
307
- else:
308
- s1_content = '<div class="empty-hint">Press β–Ά to start</div>'
309
-
310
- # ── Stage 2: 4 behavior dimensions ───────────────────────────────────────
311
- KEYS = [
312
- ("SCHEDULE", ["ROUTINE", "SCHEDULE"]),
313
- ("ECONOMIC", ["ECONOMIC", "SPENDING", "FINANCIAL"]),
314
- ("SOCIAL", ["SOCIAL", "COMMUNITY", "LIFESTYLE"]),
315
- ("STABILITY", ["STABILITY", "CONSISTENCY", "REGULARITY"]),
 
 
 
 
 
 
 
316
  ]
317
- if status == "running2":
318
- s2_content = f'<div class="thinking" style="color:#a06030">Analyzing behavior {_dots()}</div>'
319
- elif s2_text:
320
- # Parse both "1. HEADING:" and "STEP 1: HEADING" formats
321
- sections = {}
322
- current_key = None
323
- current_sents = []
324
- for line in s2_text.splitlines():
325
- stripped = line.strip()
326
- # Match "1. TITLE ANALYSIS:" or "STEP 1: TITLE ANALYSIS"
327
- m = re.match(r'^(?:\d+\.|STEP\s*\d+:)\s+(.+?)(?:\s+ANALYSIS|\s+PATTERNS|\s+INDICATORS|\s+BEHAVIOR|\s+CHARACTERISTICS)?:\s*$', stripped, re.IGNORECASE)
328
- if m:
329
- if current_key and current_sents:
330
- sections[current_key] = " ".join(current_sents)
331
- current_key = m.group(1).upper().strip()
332
- current_sents = []
333
- elif current_key:
334
- # Grab sub-bullet text (skip sub-headings like "1.1")
335
- if re.match(r'^\d+\.\d+', stripped):
336
- # sub-heading: extract its inline content
337
- sub = re.sub(r'^\d+\.\d+[^:]*:\s*', '', stripped)
338
- if sub:
339
- current_sents.append(sub)
340
- elif stripped.startswith('-'):
341
- current_sents.append(stripped.lstrip('-').strip())
342
-
343
- if current_key and current_sents:
344
- sections[current_key] = " ".join(current_sents)
345
-
346
- rows_html = ""
347
- for label, search_words in KEYS:
348
- val = "β€”"
349
- for k, text in sections.items():
350
- if any(w in k for w in search_words) and text:
351
- # First 2 sentences
352
- sents = re.split(r'(?<=[.!?])\s+', text.strip())
353
- val = " ".join(sents[:2])
354
- if len(val) > 110:
355
- val = val[:107] + "..."
356
- break
357
- rows_html += f'<div class="bkey">{label}</div><div class="bval">{val}</div>'
358
- s2_content = f'<div class="behavior-row">{rows_html}</div>'
359
- else:
360
- s2_content = '<div class="empty-hint">Waiting...</div>'
361
-
362
- # ── Stage 3: prediction + full reasoning ─────────────────────────────────
363
- if status == "running3":
364
- s3_content = f'<div class="thinking" style="color:#c0392b">Inferring demographics {_dots()}</div>'
365
- elif s3_text:
366
- pred = ""
367
- reasoning_lines = []
368
- in_reasoning = False
369
- for line in s3_text.splitlines():
370
- stripped = line.strip()
371
- if stripped.startswith("INCOME_PREDICTION:"):
372
- pred = stripped.replace("INCOME_PREDICTION:", "").strip()
373
- in_reasoning = False
374
- elif stripped.startswith("INCOME_REASONING:"):
375
- in_reasoning = True
376
- reasoning_lines.append(stripped.replace("INCOME_REASONING:", "").strip())
377
- elif in_reasoning:
378
- # Stop at second prediction block
379
- if re.match(r'^2\.', stripped) or stripped.startswith("INCOME_CONFIDENCE"):
380
- break
381
- if stripped:
382
- reasoning_lines.append(stripped)
383
-
384
- reasoning = " ".join(reasoning_lines).strip()
385
- # Truncate to 3 sentences
386
- sents = re.split(r'(?<=[.!?])\s+', reasoning)
387
- short = " ".join(sents[:3])
388
- if len(short) > 220:
389
- short = short[:217] + "..."
390
-
391
- s3_content = f"""
392
- <div class="pred-block">
393
- <div class="pred-label">Income Prediction</div>
394
- <div class="pred-value">{pred or "β€”"}</div>
395
- <div class="reasoning-text">{short}</div>
396
- </div>"""
397
- else:
398
- s3_content = '<div class="empty-hint">Waiting...</div>'
399
 
400
- PROMPT_SNIPPETS = {
401
- "s1": "You are an expert mobility analyst. Given the trajectory data below, extract: (1) LOCATION INVENTORY β€” list all POI categories visited and visit frequency; (2) TEMPORAL PATTERNS β€” weekly distribution, peak hours; (3) SEQUENCE β€” typical activity chains...",
402
- "s2": "Based on the trajectory features identified: {Response 1}. Now analyze what these mobility patterns reveal about lifestyle: (1) SCHEDULE β€” work/activity routine type; (2) ECONOMIC β€” spending venue tiers; (3) SOCIAL β€” social engagement; (4) STABILITY β€” consistency of routine...",
403
- "s3": "Based on feature analysis {Response 1} and behavioral analysis {Response 2}, predict income level. Output β€” INCOME_PREDICTION: [range]; INCOME_REASONING: [detailed reasoning]...",
404
- }
405
 
406
- def card(cls, badge, title, content_html, active):
407
- dim = "active" if active else "dim"
408
- prompt = PROMPT_SNIPPETS.get(cls, "")
409
- prompt_html = f'<div class="prompt-snippet"><span class="prompt-label">Prompt</span>{prompt}</div>' if prompt else ""
410
- resp_label = '<div class="resp-label">Response</div>' if active and content_html and "empty-hint" not in content_html and "thinking" not in content_html else ""
411
- return f"""
412
- <div class="stage-card {cls} {dim}">
413
- <div class="stage-header">
414
- <span class="stage-badge">{badge}</span>
415
- <span class="stage-title">{title}</span>
416
- </div>
417
- {prompt_html}
418
- {resp_label}
419
- {content_html}
420
- </div>"""
421
-
422
- def arrow(label, active):
423
- op = "1" if active else "0.25"
424
- return f"""
425
- <div class="chain-arrow" style="opacity:{op}">
426
- <div class="arrow-line"></div>
427
- <div class="arrow-label">{label}</div>
428
- <div class="arrow-line"></div>
429
- <div class="arrow-tip"></div>
430
- </div>"""
431
-
432
- html = CHAIN_CSS + '<div class="hicotraj-chain">'
433
- html += card("s1", "Stage 1", "Factual Feature Extraction", s1_content, s1_active)
434
- html += arrow("behavioral abstraction", s2_active)
435
- html += card("s2", "Stage 2", "Behavioral Pattern Analysis", s2_content, s2_active)
436
- html += arrow("demographic inference", s3_active)
437
- html += card("s3", "Stage 3", "Demographic Inference", s3_content, s3_active)
438
- html += "</div>"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
439
  return html
440
 
441
 
 
144
 
145
  # ── HTML reasoning chain ──────────────────────────────────────────────────────
146
 
147
+ # ── Paste this entire block into app.py, replacing the existing CHAIN_CSS, render_chain, and helper functions ──
148
+
149
+ import re
150
+
151
  CHAIN_CSS = """
152
  <style>
153
+ @import url('https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=DM+Sans:wght@300;400;500;600&display=swap');
154
+
155
+ .hct-root {
156
+ font-family: 'DM Sans', sans-serif;
157
+ display: flex;
158
+ flex-direction: column;
159
+ gap: 0;
160
+ padding: 4px 0 8px;
161
+ }
162
 
163
+ /* ── Stage shell ── */
164
+ .hct-stage {
165
+ border-radius: 12px;
166
+ overflow: hidden;
167
+ transition: opacity 0.3s, filter 0.3s;
168
  }
169
+ .hct-stage.dim { opacity: 0.28; filter: grayscale(0.6); pointer-events: none; }
170
+ .hct-stage.active { opacity: 1; }
171
+
172
+ /* ── Stage header strip ── */
173
+ .hct-head {
174
+ display: flex;
175
+ align-items: center;
176
+ gap: 10px;
177
+ padding: 9px 14px;
 
 
 
178
  }
179
+ .hct-num {
180
+ font-family: 'DM Mono', monospace;
181
+ font-size: 10px;
182
+ font-weight: 500;
183
+ letter-spacing: 0.12em;
184
+ padding: 2px 7px;
185
+ border-radius: 4px;
186
+ }
187
+ .hct-title {
188
+ font-size: 11px;
189
+ font-weight: 600;
190
+ letter-spacing: 0.04em;
191
+ text-transform: uppercase;
192
  }
193
 
194
+ /* Stage 1 colors */
195
+ .hct-s1 { background: #f4f6fb; border: 1.5px solid #d4daf0; }
196
+ .hct-s1 .hct-head { background: #eaecf7; border-bottom: 1px solid #d4daf0; }
197
+ .hct-s1 .hct-num { background: #dde2f3; color: #3a4a80; }
198
+ .hct-s1 .hct-title { color: #3a4a80; }
199
+
200
+ /* Stage 2 colors */
201
+ .hct-s2 { background: #fdf8f2; border: 1.5px solid #e8d5b8; }
202
+ .hct-s2 .hct-head { background: #f7ede0; border-bottom: 1px solid #e8d5b8; }
203
+ .hct-s2 .hct-num { background: #f0dcbf; color: #7a4a10; }
204
+ .hct-s2 .hct-title { color: #7a4a10; }
205
+
206
+ /* Stage 3 colors */
207
+ .hct-s3 { background: #fff6f5; border: 2px solid #d4453a; }
208
+ .hct-s3 .hct-head { background: #fce8e7; border-bottom: 1px solid #d4453a; }
209
+ .hct-s3 .hct-num { background: #d4453a; color: #fff; }
210
+ .hct-s3 .hct-title { color: #b0302a; }
211
+
212
+ /* ── Body ── */
213
+ .hct-body { padding: 12px 14px; }
214
+
215
+ /* ── Arrow connector ── */
216
+ .hct-arrow {
217
+ display: flex;
218
+ align-items: center;
219
+ gap: 8px;
220
+ padding: 5px 18px;
221
+ transition: opacity 0.3s;
222
  }
223
+ .hct-arrow-line { flex: 1; height: 1px; background: #d8d4ce; }
224
+ .hct-arrow-label {
225
+ font-family: 'DM Mono', monospace;
226
+ font-size: 9px;
227
+ color: #b0a898;
228
+ letter-spacing: 0.08em;
229
+ text-transform: uppercase;
230
+ white-space: nowrap;
231
+ background: white;
232
+ padding: 2px 8px;
233
+ border: 1px solid #e0dbd4;
234
+ border-radius: 20px;
235
  }
 
236
 
237
+ /* ── Stage 1: Location table ── */
238
+ .hct-loc-table {
239
+ width: 100%;
240
+ border-collapse: collapse;
241
+ font-size: 11.5px;
242
+ margin-bottom: 10px;
243
  }
244
+ .hct-loc-table th {
245
+ font-family: 'DM Mono', monospace;
246
+ font-size: 9px;
247
+ font-weight: 500;
248
+ letter-spacing: 0.1em;
249
+ text-transform: uppercase;
250
+ color: #8090b0;
251
+ border-bottom: 1px solid #d4daf0;
252
+ padding: 3px 6px 5px;
253
+ text-align: left;
254
+ }
255
+ .hct-loc-table th:not(:first-child) { text-align: right; }
256
+ .hct-loc-table td {
257
+ padding: 5px 6px;
258
+ color: #2a3050;
259
+ border-bottom: 1px solid #eaecf5;
260
+ line-height: 1.3;
261
+ }
262
+ .hct-loc-table td:not(:first-child) { text-align: right; font-family: 'DM Mono', monospace; font-size: 11px; color: #5060a0; }
263
+ .hct-loc-table tr:last-child td { border-bottom: none; }
264
+ .hct-loc-name { font-weight: 500; max-width: 160px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; display: block; }
265
+ .hct-visit-bar-wrap { display: flex; align-items: center; gap: 6px; justify-content: flex-end; }
266
+ .hct-visit-bar { height: 4px; border-radius: 2px; background: #6878c8; opacity: 0.55; }
267
+
268
+ /* ── Stage 1: Temporal panel ── */
269
+ .hct-temporal {
270
+ display: grid;
271
+ grid-template-columns: 1fr 1fr;
272
+ gap: 8px;
273
+ }
274
+ .hct-temp-block {
275
+ background: #eef0fa;
276
+ border-radius: 8px;
277
+ padding: 8px 10px;
278
+ }
279
+ .hct-temp-label {
280
+ font-family: 'DM Mono', monospace;
281
+ font-size: 9px;
282
+ font-weight: 500;
283
+ letter-spacing: 0.1em;
284
+ text-transform: uppercase;
285
+ color: #7080b0;
286
+ margin-bottom: 6px;
287
+ }
288
+ .hct-seg-row { display: flex; height: 10px; border-radius: 5px; overflow: hidden; margin-bottom: 5px; }
289
+ .hct-seg { display: flex; align-items: center; justify-content: center; font-size: 0; transition: width 0.5s; }
290
+ .seg-morning { background: #fbbf24; }
291
+ .seg-afternoon{ background: #f97316; }
292
+ .seg-evening { background: #8b5cf6; }
293
+ .seg-night { background: #1e3a5f; }
294
+ .seg-weekday { background: #6878c8; }
295
+ .seg-weekend { background: #e8c080; }
296
+ .hct-legend { display: flex; flex-wrap: wrap; gap: 4px 10px; }
297
+ .hct-leg-item { display: flex; align-items: center; gap: 4px; font-size: 10px; color: #5a6080; }
298
+ .hct-leg-dot { width: 8px; height: 8px; border-radius: 2px; flex-shrink: 0; }
299
+ .hct-dist-line {
300
+ margin-top: 8px;
301
+ font-size: 11px;
302
+ color: #6070a0;
303
+ font-family: 'DM Mono', monospace;
304
+ padding: 5px 8px;
305
+ background: #eef0fa;
306
+ border-radius: 6px;
307
+ display: flex;
308
+ align-items: center;
309
+ gap: 6px;
310
  }
 
 
 
 
 
311
 
312
+ /* ── Stage 2: 2Γ—2 grid ── */
313
+ .hct-dim-grid {
314
+ display: grid;
315
+ grid-template-columns: 1fr 1fr;
316
+ gap: 8px;
317
+ }
318
+ .hct-dim-card {
319
+ background: #fff;
320
+ border: 1px solid #e8d5b8;
321
+ border-radius: 8px;
322
+ padding: 9px 11px;
323
+ }
324
+ .hct-dim-head {
325
+ display: flex;
326
+ align-items: center;
327
+ gap: 6px;
328
+ margin-bottom: 5px;
329
+ }
330
+ .hct-dim-icon { font-size: 13px; line-height: 1; }
331
+ .hct-dim-name {
332
+ font-family: 'DM Mono', monospace;
333
+ font-size: 9px;
334
+ font-weight: 500;
335
+ letter-spacing: 0.1em;
336
+ text-transform: uppercase;
337
+ color: #a07040;
338
  }
339
+ .hct-dim-text {
340
+ font-size: 11px;
341
+ color: #3a2a10;
342
+ line-height: 1.55;
 
343
  }
344
+ .hct-dim-empty { color: #ccc; font-style: italic; }
345
+
346
+ /* ── Stage 3: prediction ── */
347
+ .hct-pred-row {
348
+ display: flex;
349
+ align-items: flex-start;
350
+ gap: 16px;
351
+ margin-bottom: 10px;
352
+ }
353
+ .hct-pred-badge {
354
+ background: #d4453a;
355
+ color: white;
356
+ border-radius: 8px;
357
+ padding: 8px 14px;
358
+ text-align: center;
359
+ flex-shrink: 0;
360
+ }
361
+ .hct-pred-val { font-size: 18px; font-weight: 600; line-height: 1.2; white-space: nowrap; }
362
+ .hct-pred-sub { font-family: 'DM Mono', monospace; font-size: 9px; opacity: 0.8; letter-spacing: 0.08em; text-transform: uppercase; margin-top: 2px; }
363
+ .hct-conf-col { flex: 1; padding-top: 4px; }
364
+ .hct-conf-label { font-family: 'DM Mono', monospace; font-size: 9px; color: #a04040; letter-spacing: 0.08em; text-transform: uppercase; margin-bottom: 4px; }
365
+ .hct-conf-track { height: 6px; background: #f0d0cf; border-radius: 3px; overflow: hidden; margin-bottom: 6px; }
366
+ .hct-conf-fill { height: 100%; background: linear-gradient(90deg, #e74c3c, #8b0000); border-radius: 3px; }
367
+ .hct-reasoning {
368
+ font-size: 11.5px;
369
+ color: #4a2020;
370
+ line-height: 1.6;
371
+ border-left: 3px solid #e8b0ae;
372
+ padding-left: 10px;
373
  }
374
 
375
+ /* ── Idle / loading states ── */
376
+ .hct-idle { font-size: 12px; color: #b0bac8; padding: 6px 0; font-style: italic; }
377
+ .hct-loading {
378
+ font-size: 12px; padding: 6px 0;
379
+ display: flex; align-items: center; gap: 8px;
380
  }
381
+ .hct-dot { width: 6px; height: 6px; border-radius: 50%; display: inline-block; animation: hct-pulse 1.2s ease-in-out infinite; }
382
+ .hct-dot:nth-child(2) { animation-delay: 0.2s; }
383
+ .hct-dot:nth-child(3) { animation-delay: 0.4s; }
384
+ @keyframes hct-pulse {
385
+ 0%,100% { opacity: 0.2; transform: scale(0.8); }
386
+ 50% { opacity: 1; transform: scale(1.1); }
387
  }
388
+ .hct-s1 .hct-dot { background: #6878c8; }
389
+ .hct-s2 .hct-dot { background: #c08040; }
390
+ .hct-s3 .hct-dot { background: #d4453a; }
391
  </style>
392
  """
393
 
394
 
395
+ def _loading(msg):
396
+ return f'<div class="hct-loading"><span class="hct-dot"></span><span class="hct-dot"></span><span class="hct-dot"></span><span style="color:#8090a0;font-size:12px">{msg}</span></div>'
397
+
398
+
399
+ def _parse_s1(text):
400
+ """Returns (locations, tod, wk, dist)"""
401
+ locations = []
402
+ dur_map = {}
403
+ tod = {}
404
+ wk = {}
405
+ dist = None
406
+
407
+ for line in text.splitlines():
408
+ s = line.strip()
409
+ # Location inventory: "- Name: N visits, ..."
410
+ m = re.match(r'-\s+(.+?):\s+(\d+)\s+visit', s, re.IGNORECASE)
411
+ if m:
412
+ locations.append((m.group(1).strip(), int(m.group(2))))
413
+ # Duration: "- LocationName: Average duration of X minutes"
414
+ m2 = re.match(r'-?\s*(.+?):\s+Average duration of ([\d.]+)\s+min', s, re.IGNORECASE)
415
+ if m2:
416
+ dur_map[m2.group(1).strip()] = float(m2.group(2))
417
+ # TOD: "65% morning, 23% afternoon, 6% evening, 5% night"
418
+ if not tod:
419
+ m3 = re.search(r'(\d+)%\s*morning.*?(\d+)%\s*afternoon.*?(\d+)%\s*evening.*?(\d+)%\s*night', s, re.IGNORECASE)
420
+ if m3:
421
+ tod = {'Morning': int(m3.group(1)), 'Afternoon': int(m3.group(2)),
422
+ 'Evening': int(m3.group(3)), 'Night': int(m3.group(4))}
423
+ # Weekday/weekend
424
+ if not wk:
425
+ m4 = re.search(r'(\d+)%\s*weekday.*?(\d+)%\s*weekend', s, re.IGNORECASE)
426
+ if m4:
427
+ wk = {'Weekday': int(m4.group(1)), 'Weekend': int(m4.group(2))}
428
+ # Distance
429
+ if not dist:
430
+ m5 = re.search(r'average distance of approximately ([\d.]+)\s*miles', s, re.IGNORECASE)
431
+ if m5:
432
+ dist = float(m5.group(1))
433
+
434
+ result_locs = [(n, v, dur_map.get(n)) for n, v in locations[:7]]
435
+ return result_locs, tod, wk, dist
436
+
437
+
438
+ def _parse_s2(text):
439
+ """Returns dict: ROUTINE, ECONOMIC, SOCIAL, URBAN, STABILITY β†’ short summary string"""
440
+ DIMS = {
441
+ 'ROUTINE': ['ROUTINE', 'SCHEDULE'],
442
+ 'ECONOMIC': ['ECONOMIC', 'SPENDING'],
443
+ 'SOCIAL': ['SOCIAL', 'LIFESTYLE'],
444
+ 'URBAN': ['URBAN', 'COMMUNITY'],
445
+ 'STABILITY': ['STABILITY', 'REGULARITY', 'CONSISTENCY'],
446
+ }
447
+ sections = {}
448
+ current_key = None
449
+ current_lines = []
450
+
451
+ for line in text.splitlines():
452
+ s = line.strip()
453
+ # Format A: "1. TITLE ANALYSIS:" or "2. ECONOMIC BEHAVIOR PATTERNS:"
454
+ mA = re.match(r'^\d+\.\s+([A-Z][A-Z\s&]+?)(?:\s+ANALYSIS|\s+PATTERNS|\s+INDICATORS|\s+CHARACTERISTICS|\s+STABILITY)?:\s*$', s, re.IGNORECASE)
455
+ # Format B: "STEP 1: ROUTINE & SCHEDULE ANALYSIS"
456
+ mB = re.match(r'^STEP\s+\d+:\s+([A-Z][A-Z\s&]+?)(?:\s+ANALYSIS|\s+PATTERNS|\s+INDICATORS|\s+CHARACTERISTICS|\s+STABILITY)?\s*$', s, re.IGNORECASE)
457
+ mm = mA or mB
458
+ if mm:
459
+ if current_key and current_lines:
460
+ sections[current_key] = ' '.join(current_lines)
461
+ current_key = mm.group(1).upper().strip()
462
+ current_lines = []
463
+ elif current_key and s:
464
+ if re.match(r'^\d+\.\d+', s):
465
+ sub = re.sub(r'^\d+\.\d+[^:]*:\s*', '', s)
466
+ if sub:
467
+ current_lines.append(sub)
468
+ elif s.startswith('-'):
469
+ current_lines.append(s.lstrip('-').strip())
470
+ elif not re.match(r'^\d+\.', s):
471
+ current_lines.append(s)
472
+
473
+ if current_key and current_lines:
474
+ sections[current_key] = ' '.join(current_lines)
475
+
476
+ result = {}
477
+ for dim, keywords in DIMS.items():
478
+ for k, txt in sections.items():
479
+ if any(kw in k for kw in keywords) and txt:
480
+ sents = re.split(r'(?<=[.!?])\s+', txt.strip())
481
+ summary = ' '.join(sents[:2])
482
+ if len(summary) > 160:
483
+ summary = summary[:157] + '…'
484
+ result[dim] = summary
485
  break
486
+ return result
487
+
488
+
489
+ def _parse_s3(text):
490
+ pred, conf, reasoning = '', 0, ''
491
+ in_r = False
492
+ r_lines = []
493
+ for line in text.splitlines():
494
+ s = line.strip()
495
+ if s.startswith('INCOME_PREDICTION:'):
496
+ pred = s.replace('INCOME_PREDICTION:', '').strip()
497
+ elif s.startswith('INCOME_CONFIDENCE:'):
498
+ try:
499
+ conf = int(re.search(r'\d+', s).group())
500
+ except:
501
+ conf = 0
502
+ elif s.startswith('INCOME_REASONING:'):
503
+ in_r = True
504
+ r_lines.append(s.replace('INCOME_REASONING:', '').strip())
505
+ elif in_r:
506
+ if re.match(r'^2\.', s) or s.startswith('INCOME_'):
 
507
  break
508
+ if s:
509
+ r_lines.append(s)
510
+ reasoning = ' '.join(r_lines).strip()
511
+ sents = re.split(r'(?<=[.!?])\s+', reasoning)
512
+ reasoning = ' '.join(sents[:3])
513
+ if len(reasoning) > 280:
514
+ reasoning = reasoning[:277] + '…'
515
+ return pred, conf, reasoning
516
+
517
+
518
+ def _s1_body(text, active):
519
+ if not active:
520
+ return '<div class="hct-idle">Press β–Ά to start</div>'
521
+ if not text:
522
+ return _loading('Extracting features')
523
+ locs, tod, wk, dist = _parse_s1(text)
524
+
525
+ # Location table
526
+ max_v = max((v for _, v, _ in locs), default=1)
527
+ rows = ''
528
+ for name, visits, dur in locs:
529
+ bar_w = int(60 * visits / max_v)
530
+ dur_str = f'{int(dur)}m' if dur else 'β€”'
531
+ rows += (
532
+ f'<tr>'
533
+ f'<td><span class="hct-loc-name" title="{name}">{name}</span></td>'
534
+ f'<td><div class="hct-visit-bar-wrap">'
535
+ f'<div class="hct-visit-bar" style="width:{bar_w}px"></div>'
536
+ f'{visits}</div></td>'
537
+ f'<td>{dur_str}</td>'
538
+ f'</tr>'
539
+ )
540
+ table = (
541
+ f'<table class="hct-loc-table">'
542
+ f'<thead><tr><th>Location</th><th>Visits</th><th>Avg Stay</th></tr></thead>'
543
+ f'<tbody>{rows}</tbody>'
544
+ f'</table>'
545
+ ) if rows else ''
546
+
547
+ # Temporal panels
548
+ def seg_bar(data, seg_classes):
549
+ total = sum(data.values()) or 1
550
+ segs = ''.join(
551
+ f'<div class="hct-seg {cls}" style="width:{int(100*v/total)}%"></div>'
552
+ for (label, v), cls in zip(data.items(), seg_classes)
553
+ )
554
+ legend = ''.join(
555
+ f'<div class="hct-leg-item"><div class="hct-leg-dot {cls}"></div>{label} {v}%</div>'
556
+ for (label, v), cls in zip(data.items(), seg_classes)
557
+ )
558
+ return f'<div class="hct-seg-row">{segs}</div><div class="hct-legend">{legend}</div>'
559
+
560
+ tod_panel = ''
561
+ if tod:
562
+ tod_panel = (
563
+ f'<div class="hct-temp-block">'
564
+ f'<div class="hct-temp-label">Time of Day</div>'
565
+ f'{seg_bar(tod, ["seg-morning","seg-afternoon","seg-evening","seg-night"])}'
566
+ f'</div>'
567
+ )
568
+ wk_panel = ''
569
+ if wk:
570
+ wk_panel = (
571
+ f'<div class="hct-temp-block">'
572
+ f'<div class="hct-temp-label">Weekday / Weekend</div>'
573
+ f'{seg_bar(wk, ["seg-weekday","seg-weekend"])}'
574
+ f'</div>'
575
+ )
576
+ temporal = f'<div class="hct-temporal">{tod_panel}{wk_panel}</div>' if (tod_panel or wk_panel) else ''
577
 
578
+ dist_line = ''
579
+ if dist:
580
+ dist_line = f'<div class="hct-dist-line">πŸ“ Avg trip distance &nbsp;{dist} mi</div>'
581
+
582
+ return table + temporal + dist_line
583
+
584
+
585
+ def _s2_body(text, active):
586
+ if not active:
587
+ return '<div class="hct-idle">Waiting…</div>'
588
+ if not text:
589
+ return _loading('Analyzing behavior')
590
+ dims = _parse_s2(text)
591
+
592
+ DIM_META = [
593
+ ('ROUTINE', 'πŸ•', 'Schedule'),
594
+ ('ECONOMIC', 'πŸ’°', 'Economic'),
595
+ ('SOCIAL', 'πŸ‘₯', 'Social'),
596
+ ('STABILITY', 'πŸ”„', 'Stability'),
597
  ]
598
+ # fallback to URBAN if STABILITY missing
599
+ if 'STABILITY' not in dims and 'URBAN' in dims:
600
+ dims['STABILITY'] = dims['URBAN']
601
+
602
+ cards = ''
603
+ for key, icon, label in DIM_META:
604
+ txt = dims.get(key, '')
605
+ content = f'<div class="hct-dim-text">{txt}</div>' if txt else '<div class="hct-dim-text hct-dim-empty">β€”</div>'
606
+ cards += (
607
+ f'<div class="hct-dim-card">'
608
+ f'<div class="hct-dim-head">'
609
+ f'<span class="hct-dim-icon">{icon}</span>'
610
+ f'<span class="hct-dim-name">{label}</span>'
611
+ f'</div>'
612
+ f'{content}'
613
+ f'</div>'
614
+ )
615
+ return f'<div class="hct-dim-grid">{cards}</div>'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
616
 
 
 
 
 
 
617
 
618
+ def _s3_body(text, active):
619
+ if not active:
620
+ return '<div class="hct-idle">Waiting…</div>'
621
+ if not text:
622
+ return _loading('Inferring demographics')
623
+ pred, conf, reasoning = _parse_s3(text)
624
+ conf_pct = int(conf / 5 * 100)
625
+ return (
626
+ f'<div class="hct-pred-row">'
627
+ f'<div class="hct-pred-badge">'
628
+ f'<div class="hct-pred-val">{pred or "β€”"}</div>'
629
+ f'<div class="hct-pred-sub">Income</div>'
630
+ f'</div>'
631
+ f'<div class="hct-conf-col">'
632
+ f'<div class="hct-conf-label">Confidence &nbsp;{conf}/5</div>'
633
+ f'<div class="hct-conf-track"><div class="hct-conf-fill" style="width:{conf_pct}%"></div></div>'
634
+ f'</div>'
635
+ f'</div>'
636
+ f'<div class="hct-reasoning">{reasoning}</div>'
637
+ )
638
+
639
+
640
+ def render_chain(s1_text, s2_text, s3_text, status="idle"):
641
+ s1_on = status in ("running1", "running2", "running3", "done")
642
+ s2_on = status in ("running2", "running3", "done")
643
+ s3_on = status in ("running3", "done")
644
+
645
+ # For "running" states the text may be empty β†’ show loading dots
646
+ s1_body = _s1_body(s1_text if s1_on else '', s1_on)
647
+ s2_body = _s2_body(s2_text if s2_on else '', s2_on)
648
+ s3_body = _s3_body(s3_text if s3_on else '', s3_on)
649
+
650
+ def stage(cls, num, title, body, on):
651
+ dim_cls = 'active' if on else 'dim'
652
+ return (
653
+ f'<div class="hct-stage hct-{cls} {dim_cls}">'
654
+ f'<div class="hct-head">'
655
+ f'<span class="hct-num">{num}</span>'
656
+ f'<span class="hct-title">{title}</span>'
657
+ f'</div>'
658
+ f'<div class="hct-body">{body}</div>'
659
+ f'</div>'
660
+ )
661
+
662
+ def arrow(label, on):
663
+ op = '1' if on else '0.2'
664
+ return (
665
+ f'<div class="hct-arrow" style="opacity:{op}">'
666
+ f'<div class="hct-arrow-line"></div>'
667
+ f'<div class="hct-arrow-label">{label}</div>'
668
+ f'<div class="hct-arrow-line"></div>'
669
+ f'</div>'
670
+ )
671
+
672
+ html = CHAIN_CSS + '<div class="hct-root">'
673
+ html += stage('s1', 'Stage 01', 'Feature Extraction', s1_body, s1_on)
674
+ html += arrow('behavioral abstraction', s2_on)
675
+ html += stage('s2', 'Stage 02', 'Behavioral Analysis', s2_body, s2_on)
676
+ html += arrow('demographic inference', s3_on)
677
+ html += stage('s3', 'Stage 03', 'Demographic Inference', s3_body, s3_on)
678
+ html += '</div>'
679
  return html
680
 
681