# v1.6.4 — Lore-Only Edition # - Keeps the v1.3 UX flow: Welcome (video + lore buttons) → Era Select → Viewer # - Removes *all* chat / LLM / RAG logic and imports # - Pure Markdown browsing experience (Era + Lore) # - Uses gr.Video(value=..., autoplay=True, loop=True) as in the older working example # # Files used: # - Era markdowns from TIMELINE_DIR (e.g., "Disconnected-Frontier/Timeline Documents/Timeline-*.md") # - Optional Lore markdowns from fixed library folders # - Optional welcome video (WELCOME_VIDEO_PATH) # # Environment variables (public): # PORT : default "7860" # LOG_LEVEL : default "INFO" # TIMELINE_DIR : default "Disconnected-Frontier/Timeline Documents" # WELCOME_VIDEO_PATH : default "videos/insert-coin.mp4" # DEFAULT_ERA_FILE : default "Timeline-09-The-Modern-Era-2025-2030.md" # # No secrets required. No model/proxy variables are read in this edition. import os import re import logging from typing import List, Tuple, Dict, Optional import gradio as gr # ---------------- Env & logging ---------------- PORT = int(os.getenv("PORT", "7860")) LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper() logging.basicConfig(level=getattr(logging, LOG_LEVEL, logging.INFO)) log = logging.getLogger("df-lore-only") # ---------------- Content locations ---------------- TIMELINE_DIR = os.getenv("TIMELINE_DIR", "Disconnected-Frontier/Timeline Documents") WELCOME_VIDEO_PATH = os.getenv("WELCOME_VIDEO_PATH", "videos/insert-coin.mp4") DEFAULT_ERA_FILE = os.getenv("DEFAULT_ERA_FILE", "Timeline-09-The-Modern-Era-2025-2030.md") # ---------------- Helpers: FS & parsing ---------------- def _safe_read(path: str) -> str: """ Read a UTF-8 text file safely. Returns trimmed content or a diagnostic string on error. """ try: with open(path, "r", encoding="utf-8") as f: return f.read().strip() except FileNotFoundError: return f"(missing file: {path})" except Exception as e: return f"(error reading {path}: {e})" def _discover_timelines() -> Dict[str, str]: """ Scan TIMELINE_DIR for 'Timeline-*.md' files and return a dict: { "Timeline-XX-Name": "/abs/path/to/file.md", ... } Sorted by the leading XX number, then label. """ results: Dict[str, str] = {} if not os.path.isdir(TIMELINE_DIR): log.warning(f"Timeline directory not found: {TIMELINE_DIR}") return results for name in os.listdir(TIMELINE_DIR): if not (name.startswith("Timeline-") and name.endswith(".md")): continue results[name[:-3]] = os.path.join(TIMELINE_DIR, name) def _sort_key(label: str): m = re.match(r"Timeline-(\d+)", label) return (int(m.group(1)) if m else 9999, label) # Sort into a stable, human-friendly order return dict(sorted(results.items(), key=lambda kv: _sort_key(kv[0]))) def _discover_library_docs() -> Dict[str, List[Tuple[str, str]]]: """ Find additional lore docs in fixed folders and return: { "Core Lore & Overviews": [(label, path), ...], "Factions & Characters": [(label, path), ...], "Narrative Vignettes": [(label, path), ...], } """ lib_dirs = [ ("Core Lore & Overviews", "Disconnected-Frontier/Core Lore & Overviews"), ("Factions & Characters", "Disconnected-Frontier/Factions & Characters"), ("Narrative Vignettes", "Disconnected-Frontier/Narrative Vignettes"), ] out: Dict[str, List[Tuple[str, str]]] = {} for category, folder in lib_dirs: items: List[Tuple[str, str]] = [] if os.path.isdir(folder): for name in sorted(os.listdir(folder)): if name.endswith(".md"): items.append((os.path.splitext(name)[0].replace("-", " "), os.path.join(folder, name))) if items: out[category] = items return out TIMELINE_CHOICES = _discover_timelines() LIBRARY_DOCS = _discover_library_docs() def _initial_era_label() -> Optional[str]: """ Pick a default Era: - Prefer the file matching DEFAULT_ERA_FILE if present - Else, first discovered entry """ if not TIMELINE_CHOICES: return None for label, path in TIMELINE_CHOICES.items(): if os.path.basename(path) == DEFAULT_ERA_FILE: return label return list(TIMELINE_CHOICES.keys())[0] # ---------------- UI bits (badges, previews) ---------------- def _era_badge_html(label: Optional[str]) -> str: if not label: return "" safe = label.replace("<", "<").replace(">", ">") return f'
Current Era: {safe}
' def _lore_badge_html(label: Optional[str]) -> str: if not label: return "" safe = label.replace("<", "<").replace(">", ">") return f'
Active Lore: {safe}
' def _era_preview_md(label: str, text: str, limit: int = 1200) -> str: """ Return a truncated markdown preview for the Era selection screen. """ snippet = text[:limit] + ("…" if len(text) > limit else "") return f"### {label}\n\n{snippet}" # ---------------- CSS ---------------- CSS = """ /* Layout: Welcome row and right panel */ #welcome-row { gap: 1.25rem; } #welcome-right { display:flex; flex-direction:column; gap:1rem; align-items:start; justify-content:center; } /* Welcome video box (using gr.Video in the component) */ #welcome-video-box { width: 100%; aspect-ratio: 16/9; background:#000; border-radius:16px; overflow:hidden; box-shadow:0 6px 24px rgba(0,0,0,0.25); } /* Badges (high contrast) */ #era-badge, #lore-badge { display: flex; justify-content: flex-end; margin: 0.25rem 0 0.75rem 0; filter: drop-shadow(0 1px 1px rgba(0,0,0,0.55)); } .era-chip, .lore-chip { display: inline-flex; align-items: center; gap: 0.55rem; padding: 0.45rem 0.8rem; border-radius: 999px; background: #0f172a; /* dark slate */ border: 1px solid #94a3b8; /* light slate border */ color: #f8fafc; /* near-white text */ font-size: 0.95rem; line-height: 1.15; font-weight: 600; } .era-dot, .lore-dot { width: 8px; height: 8px; border-radius: 999px; background: #22c55e; box-shadow: 0 0 0 2px rgba(34,197,94,0.18); } /* Viewer areas */ #era-viewer, #lore-viewer, #era-preview { margin-top: .75rem; border: 1px solid #33415522; border-radius: 12px; padding: .75rem 1rem; } #lore-buttons-col > .gr-button { width: 100%; } /* Buttons */ #insert-coin button { width:100%; max-width:420px; height:clamp(56px,12vh,96px); font-size:clamp(1.05rem,2.2vw,1.6rem); border-radius:16px; } """ # ---------------- Build UI ---------------- with gr.Blocks(title="Disconnected Frontier — Lore Only (v1.6.4)", css=CSS) as demo: # States (Era + Active Lore) era_text_state = gr.State("") # full markdown of selected Era era_name_state = gr.State("") # label of selected Era era_file_state = gr.State("") # path of selected Era lore_name_state = gr.State("") # active lore label lore_text_state = gr.State("") # active lore content lore_path_state = gr.State("") # active lore path # ---------- View 1: Welcome ---------- with gr.Group(visible=True) as view_welcome: gr.Markdown("# 🕹️ Disconnected Frontier\n### A Neo-Retro Narrative Interface (Lore-Only Edition)") with gr.Row(elem_id="welcome-row"): with gr.Column(scale=3): # Keep the original working approach: gr.Video with autoplay + loop if os.path.exists(WELCOME_VIDEO_PATH): with gr.Group(elem_id="welcome-video-box"): gr.Video( value=WELCOME_VIDEO_PATH, autoplay=True, loop=True, show_label=False, visible=True, ) else: gr.Markdown(f"_Welcome video missing. Set `WELCOME_VIDEO_PATH` or add `{WELCOME_VIDEO_PATH}`._") with gr.Column(scale=1, elem_id="welcome-right"): btn_start = gr.Button("🪙 INSERT COIN →", variant="primary", elem_id="insert-coin") # Lore document buttons (non-timeline), stacked vertically lore_buttons: List[Tuple[gr.Button, str, str]] = [] if LIBRARY_DOCS: for category, docs in LIBRARY_DOCS.items(): gr.Markdown(f"**{category}**") with gr.Column(elem_id="lore-buttons-col"): for label, path in docs: b = gr.Button(label) lore_buttons.append((b, label, path)) else: gr.Markdown("_No additional lore documents found._") # Inline viewer under Welcome for quick lore peeks welcome_lore_viewer = gr.Markdown("", elem_id="lore-viewer") # Wire the lore buttons to open + set active lore for b, label, path in lore_buttons: def _open_and_activate(l=label, p=path): content = _safe_read(p) return content, l, content, p b.click( _open_and_activate, outputs=[welcome_lore_viewer, lore_name_state, lore_text_state, lore_path_state], ) # ---------- View 2: Era Selection ---------- with gr.Group(visible=False) as view_era: gr.Markdown("## Choose an Era") if TIMELINE_CHOICES: default_label = _initial_era_label() era_radio = gr.Radio( choices=list(TIMELINE_CHOICES.keys()), value=default_label, label="Timeline", interactive=True, ) era_preview = gr.Markdown("_Preview will appear here._", elem_id="era-preview") with gr.Row(): btn_back_welcome = gr.Button("← Back") btn_enter_viewer = gr.Button("Enter Viewer →", variant="primary") else: gr.Markdown(f"No timeline files found. Add markdown files to `{TIMELINE_DIR}`.") era_radio = None era_preview = None btn_back_welcome = gr.Button("← Back") btn_enter_viewer = gr.Button("Enter Viewer →", variant="primary", visible=False) # ---------- View 3: Viewer (Era + Lore readers) ---------- with gr.Group(visible=False) as view_viewer: # Badges era_badge = gr.HTML("", elem_id="era-badge") lore_badge = gr.HTML("", elem_id="lore-badge") # Era markdown (full) gr.Markdown("### Era Document") era_viewer = gr.Markdown("", elem_id="era-viewer") # Lore selection in viewer (dropdown + Open) + viewer area all_docs: List[Tuple[str, str]] = [] if LIBRARY_DOCS: for category, docs in LIBRARY_DOCS.items(): for label, path in docs: all_docs.append((f"{category} · {label}", path)) with gr.Row(): viewer_lore_dd = gr.Dropdown( choices=[name for name, _ in all_docs], value=(all_docs[0][0] if all_docs else None), show_label=False, ) btn_viewer_open_lore = gr.Button("Open") gr.Markdown("### Active Lore") viewer_lore_viewer = gr.Markdown("_(Select a lore document above or from the Welcome screen.)_") btn_change_era = gr.Button("Change Era") # --- Viewer handlers --- def _open_viewer_lore(name: str): for n, p in all_docs: if n == name: content = _safe_read(p) plain = n.split(" · ", 1)[1] if " · " in n else n return content, plain, content, p, _lore_badge_html(plain) return "(document not found)", "", "", "", "" if LIBRARY_DOCS: btn_viewer_open_lore.click( _open_viewer_lore, inputs=[viewer_lore_dd], outputs=[viewer_lore_viewer, lore_name_state, lore_text_state, lore_path_state, lore_badge], ) # ---------- Navigation wiring ---------- def _show_era(): return gr.update(visible=False), gr.update(visible=True) def _show_welcome(): return gr.update(visible=False), gr.update(visible=True) def _show_viewer(): return gr.update(visible=False), gr.update(visible=True) # Welcome → Era btn_start.click(_show_era, outputs=[view_welcome, view_era]) # Initialize era preview when entering the Era selector def _init_default_era(): label = _initial_era_label() if not label: return "_No timelines found_", "", "", "" path = TIMELINE_CHOICES.get(label, "") text = _safe_read(path) if path else "" return _era_preview_md(label, text), text, label, path if TIMELINE_CHOICES: btn_start.click( _init_default_era, outputs=[era_preview, era_text_state, era_name_state, era_file_state], ) # Era → Welcome btn_back_welcome.click(_show_welcome, outputs=[view_era, view_welcome]) # Era radio change → refresh preview and states def _load_era(era_label: str): path = TIMELINE_CHOICES.get(era_label, "") text = _safe_read(path) if path else "" return _era_preview_md(era_label, text), text, era_label, path if era_radio is not None: era_radio.change(_load_era, inputs=[era_radio], outputs=[era_preview, era_text_state, era_name_state, era_file_state]) # Apply Era and enter Viewer def _apply_era_and_enter(era_label: Optional[str], era_text: str, fallback_name: str, lore_name: str): # Ensure label and text are set, even if user didn't touch radio if not era_label and TIMELINE_CHOICES: era_label = _initial_era_label() if (not era_text or not era_text.strip()) and era_label: era_text = _safe_read(TIMELINE_CHOICES.get(era_label, "")) era_badge_html = _era_badge_html(era_label or fallback_name or "") lore_badge_html = _lore_badge_html(lore_name or "") # In Viewer, show the FULL Era markdown (no truncation) return ( gr.update(visible=False), # hide Era view gr.update(visible=True), # show Viewer era_text, # era_viewer content era_badge_html, # era_badge HTML (era_label or fallback_name or ""), # era_name_state lore_badge_html, # lore_badge HTML ) btn_enter_viewer.click( _apply_era_and_enter, inputs=[era_name_state if TIMELINE_CHOICES else gr.State(None), era_text_state, era_name_state, lore_name_state], outputs=[view_era, view_viewer, era_viewer, era_badge, era_name_state, lore_badge], ) # Change Era from Viewer → back to selector def _go_to_era(): return gr.update(visible=False), gr.update(visible=True) btn_change_era.click(_go_to_era, outputs=[view_viewer, view_era]) # ---------------- Run ---------------- if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=PORT)