1
+ # Gradio_Related_Fixed.py
2
+ # Enhanced version with better error handling and fixes
3
+
4
+ import os
5
+ import sys
6
+ import webbrowser
7
+ import traceback
8
+ import gradio as gr
9
+ from pathlib import Path
10
+
11
+ # Import with error handling
12
+ try :
13
+ from App_Function_Libraries .DB .DB_Manager import get_db_config
14
+ from App_Function_Libraries .DB .RAG_QA_Chat_DB import create_tables
15
+ from App_Function_Libraries .Utils .Utils import load_and_log_configs , logging
16
+ except ImportError as e :
17
+ print (f"Import error: { e } " )
18
+ print ("Make sure all dependencies are installed and paths are correct." )
19
+ sys .exit (1 )
20
+
21
+ # Ensure directories exist
22
+ def ensure_directories ():
23
+ """Create necessary directories if they don't exist"""
24
+ dirs = [
25
+ 'Databases' ,
26
+ 'Logs' ,
27
+ 'Config_Files'
28
+ ]
29
+ for dir_path in dirs :
30
+ Path (dir_path ).mkdir (exist_ok = True )
31
+
32
+ def safe_import_tabs ():
33
+ """Import all tab creation functions with error handling"""
34
+ tab_imports = {}
35
+
36
+ # List of all tab modules to import
37
+ tab_modules = [
38
+ ('Anki_tab' , ['create_anki_validation_tab' , 'create_anki_generator_tab' ]),
39
+ ('Arxiv_tab' , ['create_arxiv_tab' ]),
40
+ ('Audio_ingestion_tab' , ['create_audio_processing_tab' ]),
41
+ ('Video_transcription_tab' , ['create_video_transcription_tab' ]),
42
+ # Add more as needed
43
+ ]
44
+
45
+ for module_name , functions in tab_modules :
46
+ try :
47
+ module = __import__ (f'App_Function_Libraries.Gradio_UI.{ module_name } ' , fromlist = functions )
48
+ for func_name in functions :
49
+ tab_imports [func_name ] = getattr (module , func_name )
50
+ except Exception as e :
51
+ logging .error (f"Failed to import { module_name } : { e } " )
52
+ # Create a dummy function that shows an error tab
53
+ for func_name in functions :
54
+ tab_imports [func_name ] = lambda : gr .Markdown (f"Error loading { func_name } : { str (e )} " )
55
+
56
+ return tab_imports
57
+
58
+ def launch_ui_safe (share_public = None , server_mode = False , demo_mode = False ):
59
+ """Enhanced launch_ui with better error handling"""
60
+
61
+ # Ensure directories exist
62
+ ensure_directories ()
63
+
64
+ # Don't open browser in demo mode
65
+ if not demo_mode :
66
+ try :
67
+ webbrowser .open_new_tab ('http://127.0.0.1:7860/?__theme=dark' )
68
+ except Exception as e :
69
+ logging .warning (f"Could not open browser: { e } " )
70
+
71
+ share = share_public
72
+
73
+ # CSS styling
74
+ css = """
75
+ .result-box {
76
+ margin-bottom: 20px;
77
+ border: 1px solid #ddd;
78
+ padding: 10px;
79
+ }
80
+ .result-box.error {
81
+ border-color: #ff0000;
82
+ background-color: #ffeeee;
83
+ }
84
+ .transcription, .summary {
85
+ max-height: 800px;
86
+ overflow-y: auto;
87
+ border: 1px solid #eee;
88
+ padding: 10px;
89
+ margin-top: 10px;
90
+ }
91
+ #scrollable-textbox textarea {
92
+ max-height: 500px !important;
93
+ overflow-y: auto !important;
94
+ }
95
+ """
96
+
97
+ try :
98
+ # Load configuration with error handling
99
+ config = load_and_log_configs ()
100
+ if not config :
101
+ logging .error ("Failed to load configuration" )
102
+ config = {'db_config' : {'sqlite_path' : './Databases/media_db.db' , 'type' : 'sqlite' }}
103
+
104
+ # Get database paths
105
+ db_config = config .get ('db_config' , {})
106
+ media_db_path = db_config .get ('sqlite_path' , './Databases/media_db.db' )
107
+
108
+ # Ensure database directory exists
109
+ db_dir = os .path .dirname (media_db_path )
110
+ if not os .path .exists (db_dir ):
111
+ os .makedirs (db_dir , exist_ok = True )
112
+ logging .info (f"Created database directory: { db_dir } " )
113
+
114
+ character_chat_db_path = os .path .join (db_dir , "chatDB.db" )
115
+ rag_chat_db_path = os .path .join (db_dir , "rag_qa.db" )
116
+
117
+ # Initialize databases with error handling
118
+ try :
119
+ create_tables ()
120
+ logging .info ("Database tables created successfully" )
121
+ except Exception as e :
122
+ logging .error (f"Error creating database tables: { e } " )
123
+
124
+ # Import all tab functions
125
+ tabs = safe_import_tabs ()
126
+
127
+ # Create Gradio interface
128
+ with gr .Blocks (theme = 'default' , css = css ) as iface :
129
+ # Add dark mode script
130
+ gr .HTML ("""
131
+ <script>
132
+ document.addEventListener('DOMContentLoaded', (event) => {
133
+ document.body.classList.add('dark');
134
+ document.querySelector('gradio-app').style.backgroundColor = 'var(--color-background-primary)';
135
+ });
136
+ </script>
137
+ """ )
138
+
139
+ # Get database type
140
+ db_type = db_config .get ('type' , 'sqlite' )
141
+
142
+ # Header
143
+ gr .Markdown ("# tl/dw: Your LLM-powered Research Multi-tool" )
144
+ gr .Markdown (f"(Using { db_type .capitalize ()} Database)" )
145
+
146
+ # Create minimal interface for testing
147
+ with gr .Tabs ():
148
+ with gr .TabItem ("Status" , id = "status" ):
149
+ gr .Markdown ("## System Status" )
150
+ gr .Markdown (f"✅ Application loaded successfully" )
151
+ gr .Markdown (f"📁 Database path: { media_db_path } " )
152
+ gr .Markdown (f"🗄️ Database type: { db_type } " )
153
+
154
+ with gr .TabItem ("Test" , id = "test" ):
155
+ gr .Markdown ("## Test Tab" )
156
+ test_input = gr .Textbox (label = "Test Input" )
157
+ test_output = gr .Textbox (label = "Test Output" )
158
+ test_button = gr .Button ("Test" )
159
+
160
+ def test_function (text ):
161
+ return f"Echo: { text } "
162
+
163
+ test_button .click (test_function , inputs = test_input , outputs = test_output )
164
+
165
+ # Launch settings
166
+ server_port = int (os .getenv ('GRADIO_SERVER_PORT' , 7860 ))
167
+
168
+ # Disable analytics
169
+ os .environ ['GRADIO_ANALYTICS_ENABLED' ] = 'False'
170
+
171
+ # Launch the interface
172
+ launch_kwargs = {
173
+ 'share' : share ,
174
+ 'server_port' : server_port ,
175
+ 'show_error' : True
176
+ }
177
+
178
+ if server_mode :
179
+ launch_kwargs ['server_name' ] = "0.0.0.0"
180
+
181
+ try :
182
+ iface .launch (** launch_kwargs )
183
+ except Exception as e :
184
+ logging .error (f"Error launching Gradio interface: { e } " )
185
+ # Try alternative port
186
+ logging .info ("Trying alternative port 7861..." )
187
+ launch_kwargs ['server_port' ] = 7861
188
+ iface .launch (** launch_kwargs )
189
+
190
+ except Exception as e :
191
+ logging .error (f"Critical error in launch_ui: { e } " )
192
+ logging .error (traceback .format_exc ())
193
+
194
+ # Create minimal error interface
195
+ with gr .Blocks () as error_iface :
196
+ gr .Markdown ("# Error Loading Application" )
197
+ gr .Markdown (f"An error occurred: { str (e )} " )
198
+ gr .Markdown ("Please check the logs for more information." )
199
+
200
+ error_iface .launch (share = False , server_port = 7860 )
0 commit comments