ZOTHEOS commited on
Commit
a85df84
·
verified ·
1 Parent(s): 26425e8

Update main_web.py

Browse files
Files changed (1) hide show
  1. main_web.py +36 -285
main_web.py CHANGED
@@ -1,285 +1,36 @@
1
- import gradio as gr
2
- import asyncio
3
- import logging
4
- import os
5
- import sys
6
- import time
7
- import html
8
- import json
9
- import tempfile
10
- from typing import Optional, Dict, List, Tuple
11
-
12
- # --- Constants & Logger (Your original, stable code) ---
13
- APP_TITLE = "ZOTHEOS - Ethical Fusion AI"
14
- FAVICON_FILENAME = "favicon_blackBW.ico"
15
- LOGO_FILENAME = "zotheos_logo.png"
16
-
17
- # Using your robust logger setup
18
- def init_logger():
19
- logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
20
- logger_instance = logging.getLogger("ZOTHEOS_Interface")
21
- if not logger_instance.handlers:
22
- 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)
23
- return logger_instance
24
- logger = init_logger()
25
-
26
- # --- Asset Path Helper (Your original, stable code) ---
27
- def get_asset_path(filename: str) -> Optional[str]:
28
- base_dir = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
29
- for path in [os.path.join(base_dir, 'assets', filename), os.path.join(base_dir, filename)]:
30
- if os.path.exists(path):
31
- logger.info(f"Asset found: '{filename}' -> '{path}'")
32
- return path
33
- logger.warning(f"Asset NOT FOUND: '{filename}'.")
34
- return None
35
-
36
- logo_path_verified = get_asset_path(LOGO_FILENAME)
37
- favicon_path_verified = get_asset_path(FAVICON_FILENAME)
38
-
39
- # --- Core Logic & AI System Initialization (Your original, stable code) ---
40
- MainFusionPublic = None; initialization_error: Optional[Exception] = None; DEFAULT_INFERENCE_PRESET_INTERFACE = "balanced"; get_user_tier = lambda token: "error (auth module failed)"
41
- try:
42
- script_dir = os.path.dirname(os.path.abspath(__file__)); project_root = script_dir
43
- if project_root not in sys.path: sys.path.insert(0, project_root);
44
- from modules.main_fusion_public import MainFusionPublic
45
- try: from modules.config_settings_public import DEFAULT_INFERENCE_PRESET as CONFIG_DEFAULT_PRESET; DEFAULT_INFERENCE_PRESET_INTERFACE = CONFIG_DEFAULT_PRESET
46
- except ImportError: logger.warning("Could not import DEFAULT_INFERENCE_PRESET.")
47
- from modules.user_auth import get_user_tier as imported_get_user_tier; get_user_tier = imported_get_user_tier; logger.info("✅ Successfully imported MainFusionPublic and user_auth.")
48
- except Exception as e:
49
- logger.error(f"❌ Error importing modules: {e}", exc_info=True); initialization_error = e
50
-
51
- ai_system: Optional[MainFusionPublic] = None
52
- if 'MainFusionPublic' in globals() and MainFusionPublic is not None and initialization_error is None:
53
- try: logger.info("Initializing ZOTHEOS AI System..."); ai_system = MainFusionPublic(); logger.info("✅ ZOTHEOS AI System Initialized.")
54
- except Exception as e_init: initialization_error = e_init; logger.error(f"❌ AI System Init Failed: {e_init}", exc_info=True); ai_system = None
55
- elif initialization_error is None: initialization_error = ModuleNotFoundError("MainFusionPublic could not be imported."); logger.error(f"❌ {initialization_error}")
56
-
57
-
58
- # --- TIER_FEATURES Dictionary (Your original, stable code) ---
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
- # --- NEW DESIGN: "ANCESTRAL TECH" (BLACK, WHITE, AZTEC TURQUOISE) ---
63
- #
64
- zotheos_base_css = """
65
- @import url('https://fonts.googleapis.com/css2?family=Teko:wght@400;600&family=Inter:wght@400;500&display=swap');
66
-
67
- :root {
68
- --bg-main: #0A0A0A;
69
- --bg-surface: #141414;
70
- --text-primary: #E0E0E0;
71
- --text-secondary: #707070;
72
- --border-color: #282828;
73
- --accent-turquoise: #40E0D0;
74
- --accent-turquoise-dark: #32B3A6;
75
-
76
- --font-display: 'Teko', 'Staatliches', sans-serif;
77
- --font-body: 'Inter', sans-serif;
78
-
79
- --radius: 4px; /* Sharp, geometric corners */
80
- --glow-shadow: 0 0 12px 0px rgba(64, 224, 208, 0.4);
81
- }
82
-
83
- /* --- Base Resets --- */
84
- footer, canvas { display: none !important; }
85
- html, body {
86
- background-color: var(--bg-main) !important;
87
- font-family: var(--font-body);
88
- color: var(--text-primary);
89
- }
90
- .gradio-container {
91
- max-width: 840px !important;
92
- margin: 0 auto !important;
93
- padding: 2rem 1.5rem !important;
94
- background-color: transparent !important;
95
- }
96
-
97
- /* --- Header & Typography --- */
98
- #header_column { text-align: center; margin-bottom: 2rem; }
99
- #header_logo img {
100
- max-height: 80px;
101
- filter: brightness(0) invert(1); /* Ensure logo is pure white */
102
- text-shadow: 0 0 10px rgba(255,255,255,0.3);
103
- }
104
- #header_subtitle {
105
- font-family: var(--font-display) !important;
106
- font-size: 1.4rem !important;
107
- letter-spacing: 2px;
108
- color: var(--text-secondary);
109
- text-transform: uppercase;
110
- }
111
- #welcome_message {
112
- font-family: var(--font-display) !important;
113
- font-size: 1.8rem !important;
114
- letter-spacing: 1px;
115
- text-transform: uppercase;
116
- color: var(--text-primary);
117
- border-top: 1px solid var(--border-color);
118
- border-bottom: 1px solid var(--border-color);
119
- padding: 0.5rem 0;
120
- margin-bottom: 2rem;
121
- }
122
-
123
- /* --- Input & Interactive Elements --- */
124
- .gradio-textbox textarea, .gradio-textbox input {
125
- background-color: var(--bg-surface) !important;
126
- border: 1px solid var(--border-color) !important;
127
- border-radius: var(--radius) !important;
128
- color: var(--text-primary) !important;
129
- transition: all 0.2s ease-in-out;
130
- }
131
- .gradio-textbox textarea:focus, .gradio-textbox input:focus {
132
- border-color: var(--accent-turquoise) !important;
133
- box-shadow: var(--glow-shadow);
134
- background-color: #181818 !important;
135
- }
136
- #query_input textarea { min-height: 150px !important; font-size: 1rem; }
137
-
138
- /* --- Buttons --- */
139
- .gradio-button { border-radius: var(--radius) !important; transition: all 0.2s ease; border: 1px solid transparent; }
140
- #submit_button {
141
- background: var(--accent-turquoise) !important;
142
- color: #000 !important;
143
- font-weight: 600 !important;
144
- text-transform: uppercase;
145
- letter-spacing: 1px;
146
- border-color: var(--accent-turquoise) !important;
147
- }
148
- #submit_button:hover { background: var(--text-primary) !important; border-color: var(--text-primary) !important; transform: scale(1.02); }
149
- #clear_button { background: var(--bg-surface) !important; color: var(--text-secondary) !important; border-color: var(--border-color) !important; }
150
- #clear_button:hover { color: var(--text-primary) !important; border-color: var(--text-secondary) !important; }
151
- #export_memory_button { background: transparent !important; color: var(--text-secondary) !important; border: 1px dashed var(--border-color); }
152
- #export_memory_button.interactive_button_enabled { color: var(--accent-turquoise) !important; border-color: var(--accent-turquoise) !important; }
153
- #export_memory_button.interactive_button_enabled:hover { background: rgba(64, 224, 208, 0.1) !important; }
154
-
155
- /* --- Output & Accordions --- */
156
- #synthesized_summary_output, #fusion_output {
157
- background-color: transparent !important;
158
- border: 1px solid var(--border-color) !important;
159
- border-radius: var(--radius) !important;
160
- padding: 1rem 1.5rem !important;
161
- }
162
- .gradio-accordion > .label-wrap {
163
- background-color: var(--bg-surface) !important;
164
- border: 1px solid var(--border-color) !important;
165
- border-radius: var(--radius) !important;
166
- }
167
-
168
- /* --- Tier Status & Footer --- */
169
- #tier_status_display small { color: var(--text-secondary) !important; font-size: 0.8rem; }
170
- #footer_attribution { font-size: 0.75rem; color: #444; text-align: center; margin-top: 3rem; }
171
- """
172
-
173
- # --- All Helper Functions (Your original, stable code) ---
174
- def render_memory_entries_as_html(memory_entries: List[dict]) -> str:
175
- # This function is fine as-is. The new CSS will style the output.
176
- if not memory_entries: return "<div class='memory-entry'>No stored memory entries or memory disabled.</div>"
177
- html_blocks = [];
178
- for entry in reversed(memory_entries[-5:]):
179
- query = html.escape(entry.get("query", "N/A")); ts_iso = entry.get("metadata", {}).get("timestamp_iso", "Unknown");
180
- 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)
181
- except: formatted_ts = html.escape(ts_iso)
182
- models_list = entry.get("metadata", {}).get("active_models_queried", []); models_str = html.escape(", ".join(models_list)) if models_list else "N/A"
183
- summary_raw = entry.get("metadata", {}).get("synthesized_summary_text", "No summary."); summary = html.escape(summary_raw[:300]) + ("..." if len(summary_raw) > 300 else "")
184
- 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>")
185
- return "\n".join(html_blocks)
186
-
187
- def format_tier_status_for_ui(tier_name: str) -> str:
188
- features = TIER_FEATURES.get(tier_name, TIER_FEATURES["error (auth module failed)"])
189
- return f"<small>Tier: **{features['display_name']}** | Memory: {'✅' if features['memory_enabled'] else '❌'} | Export: {'✅' if features['export_enabled'] else '❌'}</small>"
190
-
191
- def update_tier_display_and_features_ui(user_token_str: Optional[str]) -> Tuple:
192
- tier_name = get_user_tier(user_token_str or "")
193
- tier_features = TIER_FEATURES.get(tier_name, TIER_FEATURES["free"])
194
- return (gr.update(value=format_tier_status_for_ui(tier_name)), gr.update(interactive=tier_features["export_enabled"], elem_classes="interactive_button_enabled" if tier_features["export_enabled"] else ""))
195
-
196
- def clear_all_fields():
197
- default_tier_name = get_user_tier(""); default_features = TIER_FEATURES.get(default_tier_name, TIER_FEATURES["free"])
198
- return ("", "", gr.update(value=format_tier_status_for_ui(default_tier_name)), "Detailed perspectives...", "Synthesized insight...", "**Status:** Awaiting Input", "No memory entries loaded.", gr.update(interactive=default_features["export_enabled"], elem_classes="interactive_button_enabled" if default_features["export_enabled"] else ""), None)
199
-
200
- async def export_user_memory_data_for_download(user_token_str: Optional[str]) -> Optional[str]:
201
- # This function is fine as-is.
202
- try:
203
- if not (tier_features := TIER_FEATURES.get(get_user_tier(user_token_str or ""), TIER_FEATURES["free"]))['export_enabled']: gr.Warning("🚫 Export is a Pro Tier feature."); return None
204
- if not ai_system or not hasattr(ai_system, 'memory_bank'): gr.Error("⚠️ Memory system unavailable."); return None
205
- memory_data = await ai_system.memory_bank.get_all_memories_for_export_async() if hasattr(ai_system.memory_bank, 'get_all_memories_for_export_async') else ai_system.memory_bank.get_all_memories_for_export()
206
- if not memory_data: gr.Info("ℹ️ No memory to export."); return None
207
- with tempfile.NamedTemporaryFile(delete=False, mode="w", suffix=".json", encoding="utf-8") as f: f.write(json.dumps(memory_data, indent=2)); return f.name
208
- except Exception as e: logger.error(f"❌ Export error: {e}", exc_info=True); gr.Error(f"⚠️ Export error: {e}"); return None
209
-
210
-
211
- # --- Build Gradio Interface (Using your stable layout with the new CSS) ---
212
- def build_interface(logo_path_param: Optional[str], favicon_path_param: Optional[str]) -> gr.Blocks:
213
- theme = gr.themes.Base(font=[gr.themes.GoogleFont("Inter"), "sans-serif"])
214
- initial_tier_name = get_user_tier("")
215
- initial_tier_features = TIER_FEATURES.get(initial_tier_name, TIER_FEATURES["free"])
216
-
217
- # The favicon_path is correctly passed here, which will make the logo appear in the browser tab.
218
- with gr.Blocks(theme=theme, css=zotheos_base_css, title=APP_TITLE, favicon_path=favicon_path_param) as demo:
219
- with gr.Column(elem_classes="centered-container"):
220
- # Using your proven layout structure
221
- with gr.Column(elem_id="header_column"):
222
- if logo_path_param: gr.Image(value=logo_path_param, elem_id="header_logo", show_label=False, container=False, interactive=False)
223
- gr.Markdown("Ethical Fusion AI for Synthesized Intelligence", elem_id="header_subtitle")
224
- gr.Markdown("💡 Fusing perspectives for deeper truth.", elem_id="welcome_message")
225
-
226
- # Auth Row
227
- with gr.Row(elem_id="auth_row", equal_height=False):
228
- user_token_input = gr.Textbox(label="🔑 Access Token", placeholder="Enter token...", type="password", elem_id="user_token_input", scale=3, container=False)
229
- tier_status_display = gr.Markdown(value=format_tier_status_for_ui(initial_tier_name), elem_id="tier_status_display")
230
-
231
- # Input Group
232
- with gr.Group(elem_classes="interface-section"):
233
- 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")
234
- status_indicator_component = gr.HTML(elem_id="status_indicator", visible=False)
235
- with gr.Row():
236
- submit_button_component = gr.Button("Process Inquiry", elem_id="submit_button", variant="primary", scale=2)
237
- clear_button_component = gr.Button("Clear All", elem_id="clear_button", variant="secondary", scale=1)
238
-
239
- # Output Group
240
- with gr.Group(elem_classes="interface-section"):
241
- synthesized_summary_component = gr.Markdown(elem_id="synthesized_summary_output", value="Synthesized insight will appear here...")
242
- fused_response_output_component = gr.Markdown(elem_id="fusion_output", value="Detailed perspectives will appear here...")
243
-
244
- # Tools & Footer (Your proven layout)
245
- export_memory_button = gr.Button("⬇️ Export Memory Log", interactive=initial_tier_features["export_enabled"], elem_classes="interactive_button_enabled" if initial_tier_features["export_enabled"] else "")
246
- with gr.Accordion("💡 System Status & Active Models", open=False): active_models_display_component = gr.Markdown("**Status:** Initializing...")
247
- with gr.Accordion("🧠 Recent Interaction Chronicle (Last 5)", open=False): memory_display_panel_html = gr.HTML("No memory entries yet.")
248
- gr.Markdown("--- \n ZOTHEOS © 2025 ZOTHEOS LLC. System Architect: David A. Garcia.", elem_id="footer_attribution")
249
-
250
- # --- Event Handlers (Using your stable, robust logic) ---
251
- # This is your original, stable processing wrapper.
252
- async def process_query_wrapper_internal(query, token):
253
- loading_html = f"<div class='cosmic-loading'><div class='orbital-spinner'></div><div class='thinking-text'>ZOTHEOS is synthesizing...</div></div>"
254
- yield (gr.update(value=loading_html, visible=True), gr.update(interactive=False), gr.update(interactive=False), "", "", "", "Loading...")
255
- if not ai_system or initialization_error:
256
- error_html = f"🚫 Core System Error: {html.escape(str(initialization_error))}"
257
- yield (gr.update(value=error_html, visible=True), gr.update(interactive=True), gr.update(interactive=True), "System error.", "System error.", "Offline", "Memory unavailable.")
258
- return
259
- response = await ai_system.process_query_with_fusion(query, user_token=token, fusion_mode_override=DEFAULT_INFERENCE_PRESET_INTERFACE)
260
- # Your original parsing logic here
261
- summary = "## ✨ ZOTHEOS Final Synthesized Insight ✨\n" + (res.split("## ✨ ZOTHEOS Final Synthesized Insight ✨")[-1] if "## ✨ ZOTHEOS Final Synthesized Insight ✨" in (res:=response) else res)
262
- perspectives = "## 🧠 ZOTHEOS Fused Perspectives 🧠\n" + (res.split("## ✨ ZOTHEOS Final Synthesized Insight ✨")[0] if "## ✨ ZOTHEOS Final Synthesized Insight ✨" in res else "Details in summary.")
263
- tier_name = get_user_tier(token or "")
264
- mem_html = render_memory_entries_as_html(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 "Memory disabled."
265
- status_report = await ai_system.get_status_report()
266
- status_md = f"**Active Cores:** `{', '.join(status_report.get('models_last_queried_for_perspectives', ['N/A']))}`"
267
- yield (gr.update(visible=False), gr.update(interactive=True), gr.update(interactive=True), summary, perspectives, status_md, mem_html)
268
-
269
- 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")
270
- clear_button_component.click(fn=clear_all_fields, outputs=[query_input_component, user_token_input, tier_status_display, fused_response_output_component, synthesized_summary_component, active_models_display_component, memory_display_panel_html, export_memory_button, None], show_progress="hidden")
271
- user_token_input.change(fn=update_tier_display_and_features_ui, inputs=[user_token_input], outputs=[tier_status_display, export_memory_button], show_progress="hidden")
272
- export_memory_button.click(fn=export_user_memory_data_for_download, inputs=[user_token_input], outputs=[])
273
-
274
- return demo
275
-
276
- # --- Main Execution Block (Your original, stable code) ---
277
- if __name__ == "__main__":
278
- logger.info("--- Initializing ZOTHEOS Gradio Interface (V13 - Ancestral Tech) ---")
279
- zotheos_interface = build_interface(logo_path_verified, favicon_path_verified)
280
- logger.info("✅ ZOTHEOS Gradio UI built.")
281
- if initialization_error: print(f"‼️ WARNING: ZOTHEOS AI System failed to initialize fully: {initialization_error}")
282
- elif not ai_system: print(f"‼️ WARNING: ZOTHEOS AI System object is None. Backend will not function.")
283
- else: print("✅ ZOTHEOS AI System appears initialized.")
284
- launch_kwargs = {"server_name": "0.0.0.0", "server_port": int(os.getenv("PORT", 7860)), "share": os.getenv("GRADIO_SHARE", "False").lower() == "true"}
285
- zotheos_interface.queue().launch(**launch_kwargs)
 
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.")