ZOTHEOS commited on
Commit
2762feb
Β·
verified Β·
1 Parent(s): 5431ef4

Update main_web.py

Browse files
Files changed (1) hide show
  1. main_web.py +317 -35
main_web.py CHANGED
@@ -1,36 +1,318 @@
1
- # main_web.py β€” ZOTHEOS Hugging Face Entry Point
2
-
3
  import logging
4
- from zotheos_interface_public import (
5
- build_interface,
6
- logo_path_verified,
7
- favicon_path_verified,
8
- APP_TITLE
9
- )
10
-
11
- # Set up logging
12
- logging.basicConfig(
13
- level=logging.INFO,
14
- format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
15
- )
16
- logger = logging.getLogger("ZOTHEOS_WebApp_HF")
17
-
18
- # --- CRUCIAL FINAL CHECK ---
19
- # Ensure your model loading code (likely in another file like 'modules/main_fusion_public.py')
20
- # has been updated to use hf_hub_download.
21
- # The server will download the models, so your code must not look for a local 'models/' folder.
22
- logger.info("Verifying model loading strategy for web deployment...")
23
- # (This is just a log message, the actual code change is in your backend file)
24
-
25
- # --- Build and Launch the App ---
26
- logger.info(f"Building Gradio UI for '{APP_TITLE}'...")
27
- # Build the interface by calling the function from your other script
28
- zotheos_app = build_interface(logo_path_verified, favicon_path_verified)
29
-
30
- logger.info("UI built. Preparing to launch on Hugging Face Spaces...")
31
- # The .queue() is important for handling multiple users.
32
- # The .launch() command without arguments is what Hugging Face expects.
33
- # It will handle the server and networking for you.
34
- zotheos_app.queue().launch()
35
-
36
- logger.info("ZOTHEOS app has been launched by the Hugging Face environment.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import asyncio
3
  import logging
4
+ import os
5
+ import sys
6
+ import time
7
+ import random
8
+ from typing import Optional, Dict, Any, List, Union, Tuple
9
+ import html
10
+ import json
11
+ import tempfile
12
+
13
+ # --- Constants ---
14
+ APP_TITLE = "ZOTHEOS - Ethical Fusion AI"
15
+ FAVICON_FILENAME = "favicon_blackBW.ico"
16
+ LOGO_FILENAME = "zotheos_logo.png"
17
+
18
+ # --- Logger (Your existing code is perfect) ---
19
+ def init_logger():
20
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
21
+ logger_instance = logging.getLogger("ZOTHEOS_Interface")
22
+ if not logger_instance.handlers:
23
+ handler = logging.StreamHandler(sys.stdout); handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S")); logger_instance.addHandler(handler)
24
+ return logger_instance
25
+ logger = init_logger()
26
+
27
+ # --- Asset Path Helper (Your existing code is perfect) ---
28
+ def get_asset_path(filename: str) -> Optional[str]:
29
+ base_dir = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
30
+ for path in [os.path.join(base_dir, 'assets', filename), os.path.join(base_dir, filename)]:
31
+ if os.path.exists(path):
32
+ logger.info(f"Asset found: '{filename}' -> '{path}'")
33
+ return path
34
+ logger.warning(f"Asset NOT FOUND: '{filename}'.")
35
+ return None
36
+
37
+ logo_path_verified = get_asset_path(LOGO_FILENAME)
38
+ favicon_path_verified = get_asset_path(FAVICON_FILENAME)
39
+
40
+ # --- Core Logic Imports (Your existing code is perfect) ---
41
+ MainFusionPublic = None; initialization_error: Optional[Exception] = None; DEFAULT_INFERENCE_PRESET_INTERFACE = "balanced"; get_user_tier = lambda token: "error (auth module failed)"
42
+ try:
43
+ script_dir = os.path.dirname(os.path.abspath(__file__)); project_root = script_dir
44
+ if project_root not in sys.path: sys.path.insert(0, project_root)
45
+ from modules.main_fusion_public import MainFusionPublic
46
+ try: from modules.config_settings_public import DEFAULT_INFERENCE_PRESET as CONFIG_DEFAULT_PRESET; DEFAULT_INFERENCE_PRESET_INTERFACE = CONFIG_DEFAULT_PRESET
47
+ except ImportError: pass
48
+ from modules.user_auth import get_user_tier as imported_get_user_tier; get_user_tier = imported_get_user_tier
49
+ except Exception as e: initialization_error = e
50
+
51
+ # --- Initialize AI System (Your existing code is perfect) ---
52
+ ai_system: Optional[MainFusionPublic] = None
53
+ if 'MainFusionPublic' in globals() and MainFusionPublic is not None and initialization_error is None:
54
+ try: ai_system = MainFusionPublic()
55
+ except Exception as e_init: initialization_error = e_init
56
+ elif initialization_error is None: initialization_error = ModuleNotFoundError("MainFusionPublic module could not be imported.")
57
+
58
+ # --- TIER_FEATURES Dictionary (Your existing code is perfect) ---
59
+ TIER_FEATURES = {"free": {"display_name": "Free Tier", "memory_enabled": False, "export_enabled": False}, "starter": {"display_name": "Starter Tier", "memory_enabled": True, "export_enabled": False}, "pro": {"display_name": "Pro Tier", "memory_enabled": True, "export_enabled": True}, "error (auth module failed)": {"display_name": "Error", "memory_enabled": False, "export_enabled": False}}
60
+
61
+ #
62
+ # --- JESSICA WALSH INSPIRED REDESIGN ---
63
+ #
64
+ zotheos_base_css = """
65
+ @import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Inter:wght@400;600;700&display=swap');
66
+
67
+ :root {
68
+ --bg-main: #050505;
69
+ --bg-surface: #121212;
70
+ --bg-surface-raised: #1A1A1A;
71
+ --text-primary: #EAEAEA;
72
+ --text-secondary: #888888;
73
+ --border-subtle: #2A2A2A;
74
+ --accent-glow: #00BFFF; /* Electric "Truth" Blue */
75
+ --accent-glow-darker: #009ACD;
76
+
77
+ --font-display: 'Bebas Neue', 'Staatliches', cursive;
78
+ --font-body: 'Inter', sans-serif;
79
+
80
+ --radius-md: 12px;
81
+ --radius-sm: 8px;
82
+ --shadow-glow: 0 0 15px rgba(0, 191, 255, 0.2);
83
+ }
84
+
85
+ /* --- Base & Reset --- */
86
+ footer, canvas { display: none !important; }
87
+ html, body {
88
+ background-color: var(--bg-main) !important;
89
+ font-family: var(--font-body);
90
+ color: var(--text-primary);
91
+ line-height: 1.6;
92
+ scroll-behavior: smooth;
93
+ }
94
+ .gradio-container {
95
+ max-width: 800px !important;
96
+ margin: 0 auto !important;
97
+ padding: 2rem 1.5rem !important;
98
+ background-color: transparent !important;
99
+ }
100
+
101
+ /* --- Typographic Hierarchy --- */
102
+ h1, h2, h3, #header_subtitle, #welcome_message {
103
+ font-family: var(--font-display) !important;
104
+ text-transform: uppercase;
105
+ letter-spacing: 1.5px;
106
+ color: var(--text-primary);
107
+ text-align: center;
108
+ }
109
+
110
+ /* --- Header & Branding --- */
111
+ #header_column { margin-bottom: 2rem; }
112
+ #header_logo img {
113
+ max-height: 70px;
114
+ filter: brightness(0) invert(1); /* Force pure white logo */
115
+ }
116
+ #header_subtitle { font-size: 1.2rem !important; color: var(--text-secondary); }
117
+ #welcome_message {
118
+ font-size: 1.5rem !important;
119
+ color: var(--text-primary);
120
+ margin-bottom: 2.5rem;
121
+ }
122
+
123
+ /* --- Interactive Elements & Input Areas --- */
124
+ .gradio-group {
125
+ background: transparent !important;
126
+ border: none !important;
127
+ padding: 0 !important;
128
+ }
129
+ .gradio-textbox textarea, .gradio-textbox input {
130
+ background-color: var(--bg-surface) !important;
131
+ color: var(--text-primary) !important;
132
+ border: 1px solid var(--border-subtle) !important;
133
+ border-radius: var(--radius-md) !important;
134
+ padding: 1rem !important;
135
+ transition: border-color 0.3s, box-shadow 0.3s;
136
+ }
137
+ .gradio-textbox textarea:focus, .gradio-textbox input:focus {
138
+ border-color: var(--accent-glow) !important;
139
+ box-shadow: var(--shadow-glow) !important;
140
+ }
141
+ #query_input textarea { min-height: 180px !important; }
142
+
143
+ /* --- Buttons: The Core Interaction --- */
144
+ .gradio-button {
145
+ border-radius: var(--radius-md) !important;
146
+ transition: all 0.2s ease-in-out;
147
+ border: none !important;
148
+ }
149
+ #submit_button {
150
+ background: var(--accent-glow) !important;
151
+ color: var(--bg-main) !important;
152
+ font-weight: 700 !important;
153
+ text-transform: uppercase;
154
+ }
155
+ #submit_button:hover {
156
+ background: var(--text-primary) !important;
157
+ transform: translateY(-2px);
158
+ box-shadow: 0 4px 20px rgba(0,0,0,0.2);
159
+ }
160
+ #clear_button {
161
+ background: var(--bg-surface-raised) !important;
162
+ color: var(--text-secondary) !important;
163
+ }
164
+ #clear_button:hover {
165
+ background: var(--border-subtle) !important;
166
+ color: var(--text-primary) !important;
167
+ }
168
+ #export_memory_button {
169
+ background: transparent !important;
170
+ color: var(--text-secondary) !important;
171
+ border: 1px solid var(--border-subtle) !important;
172
+ }
173
+ #export_memory_button:hover {
174
+ color: var(--text-primary) !important;
175
+ border-color: var(--accent-glow) !important;
176
+ }
177
+
178
+ /* --- Output & Information Display --- */
179
+ #synthesized_summary_output, #fusion_output {
180
+ background-color: var(--bg-surface) !important;
181
+ border: 1px solid var(--border-subtle) !important;
182
+ border-radius: var(--radius-md) !important;
183
+ padding: 1.5rem !important;
184
+ margin-top: 1rem;
185
+ }
186
+ #synthesized_summary_output h2, #fusion_output h2 { font-size: 1.2rem; color: var(--accent-glow); }
187
+
188
+ /* --- Accordions & Tier Status --- */
189
+ .gradio-accordion { border: none !important; }
190
+ .gradio-accordion > .label-wrap {
191
+ background: var(--bg-surface-raised) !important;
192
+ border-radius: var(--radius-sm) !important;
193
+ padding: 0.75rem 1rem !important;
194
+ color: var(--text-secondary) !important;
195
+ }
196
+ #tier_status_display { text-align: right !important; }
197
+ #tier_status_display small { color: var(--text-secondary) !important; }
198
+
199
+ /* --- Loading Indicator --- */
200
+ .cosmic-loading { padding: 3rem; }
201
+ .orbital-spinner {
202
+ border-color: var(--border-subtle);
203
+ border-top-color: var(--accent-glow);
204
+ }
205
+ .thinking-text { font-family: var(--font-body); color: var(--text-secondary); }
206
+
207
+ /* --- Footer --- */
208
+ #footer_attribution {
209
+ font-size: 0.8rem;
210
+ color: #555;
211
+ text-align: center;
212
+ margin-top: 4rem;
213
+ padding-bottom: 1rem;
214
+ line-height: 1.5;
215
+ }
216
+ #footer_attribution strong { color: #777; font-weight: 600; }
217
+ """
218
+
219
+ # --- Helper Functions (Your existing code is perfect) ---
220
+ def render_memory_entries_as_html(memory_entries: List[dict]) -> str:
221
+ # This function is fine as-is. The new CSS will style the output.
222
+ if not memory_entries: return "<div class='memory-entry'>No stored memory entries or memory disabled.</div>"
223
+ html_blocks = [];
224
+ for entry in reversed(memory_entries[-5:]):
225
+ query = html.escape(entry.get("query", "N/A")); ts_iso = entry.get("metadata", {}).get("timestamp_iso", "Unknown");
226
+ try: dt_obj = time.strptime(ts_iso, '%Y-%m-%dT%H:%M:%SZ'); formatted_ts = time.strftime('%Y-%m-%d %H:%M UTC', dt_obj)
227
+ except: formatted_ts = html.escape(ts_iso)
228
+ models_list = entry.get("metadata", {}).get("active_models_queried", []); models_str = html.escape(", ".join(models_list)) if models_list else "N/A"
229
+ summary_raw = entry.get("metadata", {}).get("synthesized_summary_text", "No summary."); summary = html.escape(summary_raw[:300]) + ("..." if len(summary_raw) > 300 else "")
230
+ html_blocks.append(f"<div class='memory-entry'><p><strong>πŸ•’ TS:</strong> {formatted_ts}</p><p><strong>🧠 Models:</strong> {models_str}</p><div><strong>❓ Q:</strong><div class='query-text'>{query}</div></div><div><strong>πŸ“Œ Sum:</strong><div class='summary-text'>{summary}</div></div></div>")
231
+ return "\n".join(html_blocks)
232
+
233
+ def format_tier_status_for_ui(tier_name: str) -> str:
234
+ features = TIER_FEATURES.get(tier_name, TIER_FEATURES["error (auth module failed)"])
235
+ return f"<small>Tier: **{features['display_name']}** | Memory: {'βœ…' if features['memory_enabled'] else '❌'} | Export: {'βœ…' if features['export_enabled'] else '❌'}</small>"
236
+
237
+ def update_tier_display_and_features_ui(user_token_str: Optional[str]) -> Tuple:
238
+ tier_name = get_user_tier(user_token_str or "")
239
+ tier_features = TIER_FEATURES.get(tier_name, TIER_FEATURES["free"])
240
+ return (gr.update(value=format_tier_status_for_ui(tier_name)), gr.update(interactive=tier_features["export_enabled"]))
241
+
242
+ # --- Build Gradio Interface (Main Structure is Yours, Components are Styled) ---
243
+ def build_interface(logo_path_param: Optional[str], favicon_path_param: Optional[str]) -> gr.Blocks:
244
+ theme = gr.themes.Base(font=[gr.themes.GoogleFont("Inter"), "sans-serif"])
245
+ initial_tier_name = get_user_tier("")
246
+ initial_tier_features = TIER_FEATURES.get(initial_tier_name, TIER_FEATURES["free"])
247
+
248
+ with gr.Blocks(theme=theme, css=zotheos_base_css, title=APP_TITLE) as demo:
249
+ with gr.Column(elem_classes="centered-container"):
250
+ # --- Header ---
251
+ with gr.Column(elem_id="header_column"):
252
+ if logo_path_param:
253
+ gr.Image(value=logo_path_param, elem_id="header_logo", show_label=False, container=False, interactive=False)
254
+ gr.Markdown("Ethical Fusion AI for Synthesized Intelligence", elem_id="header_subtitle")
255
+
256
+ gr.Markdown("Fusing perspectives for deeper truth.", elem_id="welcome_message")
257
+
258
+ # --- Authentication & Tier Status ---
259
+ with gr.Row(equal_height=False):
260
+ user_token_input = gr.Textbox(label="Access Token", placeholder="Enter token...", type="password", scale=3, container=False)
261
+ tier_status_display = gr.Markdown(value=format_tier_status_for_ui(initial_tier_name), elem_id="tier_status_display", scale=2)
262
+
263
+ # --- Core Input ---
264
+ with gr.Group():
265
+ query_input_component = gr.Textbox(label="Your Inquiry:", placeholder="e.g., Analyze the ethical implications of AI in art...", lines=6, elem_id="query_input")
266
+ status_indicator_component = gr.HTML(elem_id="status_indicator", visible=False)
267
+ with gr.Row():
268
+ clear_button_component = gr.Button("Clear", elem_id="clear_button", variant="secondary")
269
+ submit_button_component = gr.Button("Process Inquiry", elem_id="submit_button", variant="primary", scale=3)
270
+
271
+ # --- Main Outputs ---
272
+ with gr.Group():
273
+ synthesized_summary_component = gr.Markdown(elem_id="synthesized_summary_output", value="Synthesized insight will appear here...", visible=True)
274
+ fused_response_output_component = gr.Markdown(elem_id="fusion_output", value="Detailed perspectives will appear here...", visible=True)
275
+
276
+ # --- Tools & Info ---
277
+ export_memory_button = gr.Button("Export Memory Log", elem_id="export_memory_button", interactive=initial_tier_features["export_enabled"])
278
+ with gr.Accordion("System Status & Active Models", open=False):
279
+ active_models_display_component = gr.Markdown("**Status:** Initializing...")
280
+ with gr.Accordion("Recent Interaction Chronicle", open=False):
281
+ memory_display_panel_html = gr.HTML("<div class='memory-entry'>No memory entries yet.</div>")
282
+
283
+ # --- Footer ---
284
+ gr.Markdown("---", elem_id="footer_separator")
285
+ gr.Markdown("ZOTHEOS Β© 2025 ZOTHEOS LLC. System Architect: David A. Garcia. All Rights Reserved.", elem_id="footer_attribution")
286
+
287
+ # --- Backend Logic & Event Handlers (Your existing code is perfect) ---
288
+ async def process_query_wrapper_internal(query, token):
289
+ tier_name = get_user_tier(token or ""); display_name = TIER_FEATURES.get(tier_name, {})["display_name"]
290
+ loading_html = f"<div class='cosmic-loading'><div class='orbital-spinner'></div><div class='thinking-text'>Synthesizing (Tier: {display_name})...</div></div>"
291
+ yield (gr.update(value=loading_html, visible=True), gr.update(interactive=False), gr.update(interactive=False), "", "", "", "Loading...")
292
+ if not ai_system:
293
+ yield (gr.update(value="<p style='color:red;'>SYSTEM OFFLINE</p>", visible=True), gr.update(interactive=True), gr.update(interactive=True), "Error", "Error", "Offline", "Error")
294
+ return
295
+ response = await ai_system.process_query_with_fusion(query, user_token=token, fusion_mode_override=DEFAULT_INFERENCE_PRESET_INTERFACE)
296
+ # Simple response parsing for demo
297
+ summary = response[:response.find("###")] if "###" in response else response
298
+ perspectives = response[response.find("###"):] if "###" in response else "Details integrated in summary."
299
+ mem_data = await ai_system.memory_bank.retrieve_recent_memories_async(limit=5) if TIER_FEATURES[tier_name]['memory_enabled'] and hasattr(ai_system, 'memory_bank') else []
300
+ mem_html = render_memory_entries_as_html(mem_data)
301
+ status_report = await ai_system.get_status_report()
302
+ status_md = f"**Last Used:** {', '.join(status_report.get('models_last_queried_for_perspectives', ['N/A']))}"
303
+ yield (gr.update(visible=False), gr.update(interactive=True), gr.update(interactive=True), summary, perspectives, status_md, mem_html)
304
+
305
+ submit_button_component.click(fn=process_query_wrapper_internal, inputs=[query_input_component, user_token_input], outputs=[status_indicator_component, submit_button_component, clear_button_component, synthesized_summary_component, fused_response_output_component, active_models_display_component, memory_display_panel_html], show_progress="hidden")
306
+ clear_button_component.click(lambda: ("", "", "", "Synthesized insight...", "Detailed perspectives..."), outputs=[query_input_component, user_token_input, synthesized_summary_component, fused_response_output_component])
307
+ user_token_input.change(fn=update_tier_display_and_features_ui, inputs=[user_token_input], outputs=[tier_status_display, export_memory_button])
308
+ export_memory_button.click(fn=export_user_memory_data_for_download, inputs=[user_token_input], outputs=[])
309
+
310
+ return demo
311
+
312
+ # --- Main Execution Block (Your existing code is perfect) ---
313
+ if __name__ == "__main__":
314
+ logger.info("--- Initializing ZOTHEOS Gradio Interface (V12 - Walsh Redesign) ---")
315
+ zotheos_interface = build_interface(logo_path_verified, favicon_path_verified)
316
+ logger.info("βœ… ZOTHEOS Gradio UI built.")
317
+ launch_kwargs = {"server_name": "0.0.0.0", "server_port": int(os.getenv("PORT", 7860)), "share": os.getenv("GRADIO_SHARE", "False").lower() == "true"}
318
+ zotheos_interface.queue().launch(**launch_kwargs)