-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
787 lines (647 loc) · 27.5 KB
/
Copy pathapp.py
File metadata and controls
787 lines (647 loc) · 27.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
# Copyright (C) 2025 CrispStrobe
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# app.py:
# E402 – intentional: env vars (GRADIO_TEMP_DIR, etc.) must be set before module imports
# F403/F405 – intentional: `from config import *` is the established pattern for this app
import os
import gradio as gr
os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
# Load .env file for local development (no-op if python-dotenv not installed or no .env)
try:
from pathlib import Path as _Path
from dotenv import load_dotenv
_env = _Path(__file__).parent / ".env"
if _env.exists():
load_dotenv(dotenv_path=_env)
except ImportError:
pass
# ==========================================
# IMPORTS FROM MODULES
# ==========================================
import config # alias used to MUTATE shared runtime state (STORAGE_AVAILABLE)
from config import *
# globals reachable; will be replaced when each tab moves to its own module)
# --- FORCE FFMPEG PATH ---
# Explicitly tell Python where to find the tools
os.environ["PATH"] += os.pathsep + "/usr/bin" + os.pathsep + "/usr/local/bin"
try:
from pydub import AudioSegment
AudioSegment.converter = "/usr/bin/ffmpeg"
AudioSegment.ffprobe = "/usr/bin/ffprobe"
except ImportError:
print("pydub cannot be imported")
pass
import logging
import sys
import time
APP_DIR = os.environ.get("AITOOLKIT_APP_DIR", "/var/www/aitoolkit")
if os.path.exists(APP_DIR):
print(f"ℹ️ Using default log file path: {APP_DIR}")
else:
# Local fallback: Use the directory where the script is located
APP_DIR = os.path.dirname(os.path.abspath(__file__))
print(f"ℹ️ Using local directory for log file: {APP_DIR}")
# Initialize Logging with robust error handling
try:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
handlers=[logging.FileHandler(LOG_FILE), logging.StreamHandler(sys.stdout)],
)
except (PermissionError, FileNotFoundError):
# Final fallback: If the log file can't be created at APP_DIR, log to console only
print(f"⚠️ Could not write to {LOG_FILE}. Logging to console only.")
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
)
logger = logging.getLogger(__name__)
# Log level read from $LOG_LEVEL (default INFO). DEBUG can leak request bodies
# and decryption intermediates into stdout / journald — never enable on prod.
_LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO").upper()
logger.setLevel(getattr(logging, _LOG_LEVEL, logging.INFO))
# Set Gradio file upload limits
os.environ["GRADIO_TEMP_DIR"] = "/tmp/gradio" # nosec B108
os.makedirs("/tmp/gradio", exist_ok=True) # nosec B108
import importlib.util as _importlib_util
HAS_POE = _importlib_util.find_spec("fastapi_poe") is not None
if not HAS_POE:
logger.warning("fastapi_poe not installed. Poe API will be unavailable.")
# Increase max file size
gr.set_static_paths(paths=[os.path.join(APP_DIR, "static")])
# --- IMPORTS & SETUP ---
try:
# Enable HEIF support if available
try:
from pillow_heif import register_heif_opener
register_heif_opener()
logger.info("✅ HEIF/HEIC image support enabled (pillow-heif)")
except ImportError:
logger.warning(
"⚠️ pillow-heif not installed. .heic files will be skipped or need conversion."
)
except ImportError:
print("⚠️ WARNUNG: Bitte 'pip install pillow' ausführen.")
from crypto_utils import HAS_PQ, KeyWrapper, crypto
# Initialize the wrapper
key_wrapper = KeyWrapper()
try:
FORMAT_TRANSPLANT_OK = True
FORMAT_TRANSPLANT_ERROR = None
except Exception as _ft_err:
FORMAT_TRANSPLANT_OK = False
FORMAT_TRANSPLANT_ERROR = str(_ft_err)
logger.warning("format_transplant not available: %s", _ft_err)
def _ft_get_provider_choices(user_state):
"""Reuses get_chat_provider_choices — delegates to app_helpers."""
from app_helpers import ft_get_provider_choices
return ft_get_provider_choices(user_state, FORMAT_TRANSPLANT_OK)
try:
from tools import (
DEFAULT_TOOLS_ADMIN,
DEFAULT_TOOLS_STANDARD,
DEFAULT_TOOLS_WITH_IMAGE,
HAS_MAYFLOWER_SANDBOX,
TOOL_CAPABLE_PROVIDERS,
)
HAS_TOOL_EXECUTOR = True
except ImportError:
HAS_TOOL_EXECUTOR = False
HAS_MAYFLOWER_SANDBOX = False
TOOL_CAPABLE_PROVIDERS = set()
DEFAULT_TOOLS_STANDARD = DEFAULT_TOOLS_WITH_IMAGE = DEFAULT_TOOLS_ADMIN = []
logger_placeholder = logging.getLogger(__name__)
logger_placeholder.warning("tools package not found — web search disabled")
# ==========================================
# 🗄️ DATABASE SETUP
# ==========================================
# 🎙️ TRANSCRIPTION UTILITIES
# ==========================================
# ====================================
# DOCUMENT TRANSLATION HELPERS
# ====================================
from app_helpers import (
get_file_explorer_root,
)
# ==========================================
from db_models import (
ensure_encryption,
)
# ==========================================
# 🔐 DATABASE HELPER FUNCTIONS
# ==========================================
from db_ops import (
create_default_users,
get_tool_preferences,
get_user_custom_prompts,
)
# All migrations (schema + security transitions + default users) already run
# at db_ops.py import time. No need to call them again here.
# ==========================================
# 🔌 PROVIDER UTILITIES
# ==========================================
from provider_utils import (
get_chat_provider_choices,
get_provider_lists_for_user,
)
# ==========================================
# 📦 STORAGE BOX HELPER
# ==========================================
# ==========================================
# 📁 STORAGE UTILITIES
# ==========================================
from storage_utils import (
ensure_user_storage_dirs,
)
from ui.admin_tab import build_admin_tab
from ui.chat_tab import build_chat_tab
from ui.dictation_tab import build_dictation_tab
from ui.doc_translator_tab import build_doc_translator_tab
from ui.format_transplant_tab import build_format_transplant_tab
from ui.history_tab import (
build_history_tab,
)
from ui.image_gen_tab import build_image_gen_tab
from ui.ocr_tab import build_ocr_tab
from ui.transcription_tab import build_transcription_tab
from ui.tts_tab import build_tts_tab
from ui.vision_tab import build_vision_tab
# ==========================================
# TOKEN MANAGEMENT & CHUNKING
# ==========================================
# ==========================================
# TOOL HANDLER CALLBACKS (app → tools bridge)
# These are injected into ToolRouter so tools/ stays standalone.
# Each function receives the LLM's JSON args dict + app context via closure.
# ==========================================
try:
import exchange as exchange_cli
HAS_EXCH = getattr(exchange_cli, "HAS_EXCH", False)
except (ImportError, Exception):
exchange_cli = None
HAS_EXCH = False
# ==========================================
# 💬 CHAT HANDLERS
# ==========================================
# --- CHAT UI UPDATE ---
# --- VISION UI UPDATE ---
# --- IMAGE UI UPDATE ---
# --- TRANSCRIPTION UI UPDATE ---
# Signature: (badge, t_model_update, gladia_vis, whisper_vis, deepgram_vis, assemblyai_vis)
# --- Chat functions ---
def user_msg(msg, hist):
"""
Bundles all parts into ONE turn, prevents history fragmentation.
"""
import os
print(f"\n{'=' * 60}")
print(f"[DEBUG] 👤 user_msg triggered at {time.time()}")
# Early exit for empty inputs
if not msg:
print("[DEBUG] ⚠️ msg is None or empty")
return gr.MultimodalTextbox(value=None, interactive=True), hist
typed_text = msg.get("text", "")
files = msg.get("files", [])
combined_content = []
# This will accumulate text from the box (including the cursor-pasted text from JS)
aggregated_text = typed_text if typed_text else ""
# 1. Process files
for file_path in files:
if not os.path.exists(file_path):
print(f"[DEBUG] ❌ File not found: {file_path}")
continue
ext = os.path.splitext(file_path)[1].lower()
is_image = ext in [
".jpg",
".jpeg",
".png",
".webp",
".gif",
".bmp",
".tiff",
".avif",
".heic",
".heif",
]
if is_image:
combined_content.append({"file": {"path": file_path}})
print(f"[DEBUG] 🖼️ Image turn part added: {file_path}")
else:
# Handle Drag & Drop / Manual Upload of text files (Extraction logic stays identical)
try:
print(f"[DEBUG] 📄 Non-image file detected ({ext}). Reading as text...")
with open(file_path, encoding="utf-8", errors="ignore") as f:
file_text = f.read()
if file_text.strip():
separator = "\n" if aggregated_text else ""
aggregated_text += separator + file_text
print(f"[DEBUG] ✅ Extracted {len(file_text)} chars from file.")
except Exception as e:
print(f"[DEBUG] ❌ Could not read file {file_path} as text: {e}")
# 2. Add the final aggregated text part
if aggregated_text.strip():
# WE INSERT AT POSITION 0 to ensure text instructions come before images
combined_content.insert(0, {"text": aggregated_text.strip(), "type": "text"})
print(f"[DEBUG] 📝 Total text content size: {len(aggregated_text)} chars")
# 3. Final validation
if not combined_content:
print("[DEBUG] ❌ No valid content (text or images) to add to history")
return gr.MultimodalTextbox(interactive=True), hist
# 4. Atomic Update
hist.append({"role": "user", "content": combined_content})
print(f"[DEBUG] ✅ Turn successfully bundled. History len: {len(hist)}")
print(f"{'=' * 60}\n")
return gr.update(value=None, interactive=False), hist
def select_chat_row(evt: gr.SelectData, state_data):
"""Smart Selection for Chat List"""
try:
if not state_data:
return None
row_idx = evt.index[0]
if row_idx < len(state_data):
real_row = state_data[row_idx]
# ID is in column 0
return int(real_row[0])
except Exception as e:
logger.error(f"Selection error: {e}")
return None
# ==========================================
# 📄 CONTENT EXTRACTOR
# ==========================================
import importlib as _importlib
def _check_module(name, warn_msg):
found = _importlib.util.find_spec(name) is not None
if not found:
logger.warning(warn_msg)
return found
HAS_OCR = _check_module("pytesseract", "⚠️ pytesseract missing")
HAS_PDF_IMG = _check_module("pdf2image", "⚠️ pdf2image missing")
HAS_DOCX = _check_module("docx", "⚠️ python-docx missing")
HAS_FITZ = _check_module("fitz", "⚠️ PyMuPDF (fitz) missing")
HAS_PDF_READER = _check_module("pypdf", "⚠️ pypdf missing")
HAS_PANDAS = _check_module("pandas", "⚠️ pandas missing")
HAS_PPTX = _check_module("pptx", "⚠️ python-pptx missing")
def get_user_prompt_choices(user_state):
"""Get list of user's custom prompt names for dropdown"""
if not user_state or not user_state.get("id"):
return gr.update(choices=[], value=None)
prompts = get_user_custom_prompts(user_state["id"])
names = [p.name for p in prompts]
# FIX: Return gr.update to set choices, not value
return gr.update(choices=names, value=None)
def clear_chat():
"""Clear current chat"""
return [], ""
# ==========================================
# 🔍 OCR UTILITIES
# ==========================================
# ==========================================
# 🖥️ GUI BUILDER
# ==========================================
with gr.Blocks(
title="AIToolkit",
# theme=gr.themes.Soft(),
# head=PWA_HEAD, # Only Meta tags/JS here
# css=CUSTOM_CSS # CSS goes here to override Theme defaults
) as demo:
# Print debug info on startup
print("=" * 60)
print("🎨 CSS DEBUG INFO:")
print(f"CSS length: {len(CUSTOM_CSS)} characters")
print(f"First 100 chars: {CUSTOM_CSS[:100]}")
print("=" * 60)
# 1. Define the Session "Backpack" (Stores data per browser tab)
session_state = gr.State({"id": None, "username": None, "is_admin": False})
# Set higher file size limits
gr.set_static_paths(paths=[os.path.join(APP_DIR, "static")])
# === 1. COMPACT HEADER ===
with gr.Row(elem_classes="compact-header", equal_height=True):
# Col 1: Title
with gr.Column(scale=4, min_width=80):
gr.Markdown("### ⛪ KI Toolkit")
# Col 2: User Status (Right Aligned via ID)
with gr.Column(scale=2, min_width=60):
with gr.Row(elem_id="user-status-row"):
login_status = gr.Markdown("👤", show_label=False)
# Col 3: Logout Button
with gr.Column(scale=0, min_width=50):
logout_btn = gr.Button(
"🚪 Abmelden", size="sm", elem_classes="mobile-icon-only btn-secondary"
)
# Main App — always visible (auth= gates access at framework level)
with gr.Column() as main_app:
with gr.Tabs(elem_classes="icon-nav"):
# --- TAB 1: CHAT ---
# 💬 Chat — see ui/chat_tab.py
_chat_components = build_chat_tab(session_state)
c_prov = _chat_components["c_prov"]
c_msg = _chat_components["c_msg"]
python_exec_row = _chat_components["python_exec_row"]
exchange_row = _chat_components["exchange_row"]
c_tool_web_search = _chat_components["c_tool_web_search"]
c_tool_calculate = _chat_components["c_tool_calculate"]
c_tool_fetch_url = _chat_components["c_tool_fetch_url"]
c_tool_image_gen = _chat_components["c_tool_image_gen"]
c_tool_vision_url = _chat_components["c_tool_vision_url"]
c_tool_library = _chat_components["c_tool_library"]
c_tool_exchange = _chat_components["c_tool_exchange"]
c_python_exec_enabled = _chat_components["c_python_exec_enabled"]
c_shell_enabled = _chat_components["c_shell_enabled"]
c_debug_mode = _chat_components["c_debug_mode"]
attach_sb_browser = _chat_components["attach_sb_browser"]
# --- TAB 2: TRANSKRIPTION ---
# 🎙️ Transkription — see ui/transcription_tab.py
_transcription_components = build_transcription_tab(session_state)
t_prov = _transcription_components["t_prov"]
t_storage_browser = _transcription_components["t_storage_browser"]
# --- TAB 3: VISION ---
# 👁️ Vision — see ui/vision_tab.py
_vision_components = build_vision_tab(session_state)
v_prov = _vision_components["v_prov"]
v_storage_browser = _vision_components["v_storage_browser"]
# --- TAB 4: BILDERZEUGUNG ---
# 🎨 Bilderzeugung — see ui/image_gen_tab.py
_image_gen_components = build_image_gen_tab(session_state)
g_provider = _image_gen_components["g_provider"]
# 📄 OCR — see ui/ocr_tab.py
build_ocr_tab(session_state)
# 🎙️ Diktieren — see ui/dictation_tab.py
build_dictation_tab(session_state)
# 🔊 Sprachsynthese (TTS) — see ui/tts_tab.py
build_tts_tab(session_state)
# --- TAB: DOKUMENTÜBERSETZUNG ---
# 📄 Dokument-Übersetzer — see ui/doc_translator_tab.py
build_doc_translator_tab(session_state)
# --- TAB: FORMAT-TRANSPLANT ---
# 📋 Format-Transplant — see ui/format_transplant_tab.py
_format_transplant_components = build_format_transplant_tab(session_state)
ft_llm_provider = _format_transplant_components["ft_llm_provider"]
# --- TAB 5: VERLAUF & VERWALTUNG ---
# 📚 Verlauf & Verwaltung — see ui/history_tab.py
build_history_tab(session_state, c_msg)
# --- TAB 6: USER MANAGEMENT (ADMIN ONLY) ---
# 👥 Benutzerverwaltung — see ui/admin_tab.py
_admin_components = build_admin_tab(session_state)
admin_tab = _admin_components["admin_tab"]
# Cross-tab bindings removed: duplicate of the correctly-wired
# versions at lines ~885, ~1183, ~1385 (which pass session_state).
# These were missing session_state and ran without auth.
# ── Session initialization on page load ──────────────────────────
# With auth=, the user is already authenticated when this fires.
# We use request.username to look up the user and set the UI state.
def initialize_session(request: gr.Request):
"""Initialize the UI for the authenticated user.
Called by demo.load() — fires on every page load/reconnect.
Gradio's auth= ensures request.username is set.
"""
username = request.username
if not username:
print("[SESSION] No username in request — should not happen with auth=")
return tuple(gr.update() for _ in range(21))
# Look up user from DB + retrieve cached UMK (derived during auth=)
from db_ops import get_cached_umk, get_user_by_username, get_user_settings
user = get_user_by_username(username)
if not user:
print(f"[SESSION] User {username} not found in DB")
return tuple(gr.update() for _ in range(21))
umk = get_cached_umk(username)
_max_model_b = 2.0
try:
_settings = get_user_settings(user.id)
if _settings and getattr(_settings, "max_model_size_b", None):
_max_model_b = float(_settings.max_model_size_b)
except Exception: # nosec B110
pass
state_data = {
"id": user.id,
"username": user.username,
"is_admin": user.is_admin,
"is_media_manager": getattr(user, "is_media_manager", False),
"has_sandbox_access": getattr(user, "has_sandbox_access", False),
"umk": umk,
"max_model_size_b": _max_model_b,
"must_change_password": getattr(user, "must_change_password", False),
}
ensure_user_storage_dirs(username)
storage_root = get_file_explorer_root(state_data)
chat_choices = get_chat_provider_choices(state_data)
new_c_val = (
DEFAULT_CHAT_PROVIDER
if DEFAULT_CHAT_PROVIDER in chat_choices
else (chat_choices[0] if chat_choices else None)
)
lists = get_provider_lists_for_user(state_data)
_tool_prefs = get_tool_preferences(state_data["id"])
_enabled_tools = _tool_prefs.get("enabled_tools", DEFAULT_TOOLS_STANDARD)
_is_admin = bool(state_data.get("is_admin", False))
_python_exec_val = bool(_tool_prefs.get("python_exec", False))
_shell_val = bool(_tool_prefs.get("shell", False))
_debug_val = bool(_tool_prefs.get("debug_mode", False)) and _is_admin
_exchange_val = bool(_tool_prefs.get("exchange", False)) and _is_admin
print(f"🔑 SESSION INIT: {username} (admin={_is_admin})")
return (
f"👤 {username}",
gr.update(visible=True), # logout_btn
gr.update(visible=_is_admin), # admin_tab
state_data, # session_state
gr.update(root_dir=storage_root), # t_storage
gr.update(root_dir=storage_root), # v_storage
gr.update(root_dir=storage_root), # attach_sb
gr.update(choices=chat_choices, value=new_c_val), # c_prov
gr.update(choices=lists["transcription"], value="Gladia"),
gr.update(choices=lists["vision"], value="Scaleway"),
gr.update(choices=lists["image"], value="Nebius"),
gr.update(choices=_ft_get_provider_choices(state_data), value="(none)"),
gr.update(
visible=(
state_data.get("is_admin", False)
or (state_data.get("has_sandbox_access", False) and HAS_MAYFLOWER_SANDBOX)
)
), # python_exec_row
gr.update(visible=_is_admin), # exchange_row
"web_search" in _enabled_tools,
"calculate" in _enabled_tools,
"fetch_url" in _enabled_tools,
"generate_image" in _enabled_tools,
"analyze_image_url" in _enabled_tools,
"library_search" in _enabled_tools,
_exchange_val,
)
demo.load(
fn=initialize_session,
inputs=None,
outputs=[
login_status,
logout_btn,
admin_tab,
session_state,
t_storage_browser,
v_storage_browser,
attach_sb_browser,
c_prov,
t_prov,
v_prov,
g_provider,
ft_llm_provider,
python_exec_row,
exchange_row,
c_tool_web_search,
c_tool_calculate,
c_tool_fetch_url,
c_tool_image_gen,
c_tool_vision_url,
c_tool_library,
c_tool_exchange,
],
)
# Logout: clear server-side UMK cache, then redirect to Gradio /logout
def _on_logout(user_state):
username = (user_state or {}).get("username")
if username:
from db_ops import clear_cached_umk
clear_cached_umk(username)
logout_btn.click(
fn=_on_logout,
inputs=[session_state],
outputs=None,
js="() => { window.location.href = '/logout'; }",
)
# CSS Mobile Fix elem_id is set inline via gr.Chatbot(..., elem_id="chat_window")
# in ui/chat_tab.py — no separate post-construction assignment needed.
# ==========================================
# 🚀 STARTUP SEQUENCE
# ==========================================
def initialize_application():
"""
Zentrale Initialisierung mit Mount-Überwachung und Fehlerbehandlung.
"""
# Mutate the canonical flag in `config` (single source of truth) so any
# module that imports it picks up the live value. The previous
# `global STORAGE_AVAILABLE` only updated app.py's own binding, which
# left helpers in other modules reading the False default.
print("=" * 60)
print("🔐 KI SUITE - STARTUP")
print("=" * 60)
# Lokale Verzeichnisse sicherstellen (unabhängig vom Mount)
for d in [STATIC_DIR, IMAGES_DIR, JOB_STATE_DIR]:
try:
os.makedirs(d, exist_ok=True)
print(f"✅ Lokal bereit: {os.path.basename(d)}")
except Exception as e:
print(f"❌ Fehler bei lokalem Verzeichnis {d}: {e}")
# Storage Mount Check
print(f"🔍 Prüfe Storage-Mount: {STORAGE_MOUNT_POINT}...")
# Erst prüfen, ob der Pfad überhaupt existiert (lokaler Check)
if not os.path.exists(STORAGE_MOUNT_POINT):
print("⚠️ Pfad fehlt. Versuche Mountpoint lokal zu erstellen...")
try:
os.makedirs(STORAGE_MOUNT_POINT, exist_ok=True)
except Exception as e:
print(f"❌ Konnte Mountpoint nicht erstellen: {e}")
# Aktiver Erreichbarkeits-Check (Netzwerk-Check)
if check_storage_health(STORAGE_MOUNT_POINT):
config.STORAGE_AVAILABLE = True
globals()["STORAGE_AVAILABLE"] = True # keep app.py's local mirror in sync
print(f"🟢 STORAGE ONLINE: {STORAGE_MOUNT_POINT}")
else:
config.STORAGE_AVAILABLE = False
globals()["STORAGE_AVAILABLE"] = False
print("🔴 STORAGE OFFLINE: Host nicht erreichbar oder Mount defekt.")
print(" -> Funktionen wie Archivierung werden deaktiviert.")
# 1. Database Schema (already ran at db_ops import time; just confirm)
print("\n1️⃣ Checking database schema...")
print(" ✅ Schema verified at import time")
# 2. Encryption Check
print("\n2️⃣ Checking encryption status...")
ensure_encryption() # Migrates old data if needed
# 3. Crypto Health Check
print("\n3️⃣ Cryptography status:")
print(f" Master Key: {'✅ Loaded' if crypto.master_key else '❌ Missing'}")
print(
f" Post-Quantum: {'✅ Enabled (Kyber-512)' if HAS_PQ else '⚠️ Disabled (pqcrypto not installed)'}"
)
# 4. Provider Mode
print("\n4️⃣ Provider access mode:")
print(
f" EU-Only Mode: {'✅ ENABLED (US providers blocked)' if EU_ONLY_MODE else '⚠️ DISABLED'}"
)
# 5. Default Users (already ran at db_ops import time)
print("\n5️⃣ Checking default users...")
create_default_users() # idempotent — just confirms
# 6. Security Recommendations
print("\n6️⃣ Security recommendations:")
if not EU_ONLY_MODE:
print(" ⚠️ WARNING: US providers are enabled! Set EU_ONLY_MODE=True")
if not HAS_PQ:
print(" ⚠️ INFO: Install pqcrypto for post-quantum encryption")
print("\n" + "=" * 60)
print("✅ Secure initialization complete!")
print("=" * 60 + "\n")
# initialize it before launching
initialize_application()
# ==========================================
# 🚀 LAUNCH CONFIGURATION - CLEAN VERSION
# ==========================================
if __name__ == "__main__":
# Configuration
# Ensure subdirectories exist relative to the detected APP_DIR
STATIC_DIR = os.path.join(APP_DIR, "static")
IMAGES_DIR = os.path.join(APP_DIR, "generated_images")
os.makedirs(STATIC_DIR, exist_ok=True)
os.makedirs(IMAGES_DIR, exist_ok=True)
# Ensure log file exists and is writable
if not os.path.exists(LOG_FILE):
try:
with open(LOG_FILE, "a") as f:
f.write("--- Log Initialized ---\n")
except Exception as e:
print(f"⚠️ Log file creation failed: {e}")
# Validate configuration — warn about missing keys before launch
from config import validate_config
_config_warnings = validate_config()
if _config_warnings:
for _w in _config_warnings:
print(f"⚠️ {_w}")
print("🚀 Starting Server on Port 7860...")
print(f"📂 Serving files from: {APP_DIR}")
# Print CSS debug
print("=" * 60)
print("🎨 CSS DEBUG INFO:")
print(f"CSS length: {len(CUSTOM_CSS)} characters")
print("=" * 60)
# ==========================================
# ✅ SIMPLE LAUNCH WITH CSS
# ==========================================
demo.queue()
from db_ops import gradio_auth_check
demo.launch(
server_name="127.0.0.1",
server_port=7860,
auth=gradio_auth_check,
auth_message="<h2>⛪ KI Toolkit</h2><p>Bitte anmelden.</p>",
theme=gr.themes.Soft(
font=["Helvetica", "ui-sans-serif", "system-ui", "sans-serif"],
primary_hue="blue",
secondary_hue="slate",
),
css=CUSTOM_CSS,
head=PWA_HEAD,
allowed_paths=[
STATIC_DIR,
IMAGES_DIR,
"/tmp/gradio",
"/tmp/gradio_downloads",
], # nosec B108
show_error=True,
footer_links=[],
app_kwargs={ # 🔒 Disable OpenAPI/API documentation endpoints
"docs_url": None,
"redoc_url": None,
"openapi_url": None,
},
)