Bryceeee commited on
Commit
301b4c9
Β·
verified Β·
1 Parent(s): 439677e

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -58
app.py CHANGED
@@ -13,6 +13,9 @@ IS_SPACES = os.getenv("SPACE_ID") is not None or os.getenv("HF_SPACE") is not No
13
  # Add the current directory to Python path for Spaces environment
14
  sys.path.insert(0, str(Path(__file__).parent))
15
 
 
 
 
16
  from openai import OpenAI
17
  from src.config import Config
18
  from src.vector_store import VectorStoreManager
@@ -212,71 +215,98 @@ def create_app():
212
 
213
  # Build Gradio interface
214
  print("\n🌐 Building Gradio interface...")
215
- interface_builder = GradioInterfaceBuilder(
216
- rag_engine=components["rag_engine"],
217
- question_generator=components["question_generator"],
218
- knowledge_graph=components["knowledge_graph"],
219
- config=components["config"],
220
- user_profiling=components["user_profiling"],
221
- adaptive_engine=components["adaptive_engine"],
222
- proactive_engine=components["proactive_engine"]
223
- )
224
-
225
- # Create interface (without auth parameter to avoid compatibility issues)
226
- demo = interface_builder.create_interface()
227
-
228
- # Set authentication for Hugging Face Spaces
229
- # Note: In Gradio 6.0 on Spaces, auth should be set via launch() parameters
230
- # Since Spaces auto-launches, we'll store auth config for potential use
231
- if auth_username and auth_password:
232
- auth_config = (auth_username, auth_password)
233
- # Store auth config - Spaces may use this when auto-launching
234
- # For Gradio 6.0, we can't directly set demo.auth before launch
235
- # Spaces will handle authentication if configured properly
236
- demo._hf_auth = auth_config
237
- print("βœ… Authentication credentials stored (Spaces will handle on launch)")
238
-
239
- return demo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
 
241
 
242
  # Create the app for Hugging Face Spaces
243
  # Spaces will automatically detect Gradio and run this
244
- # Wrap in try-except to ensure demo is always defined
245
- try:
246
- demo = create_app()
247
- print("βœ… App created successfully!")
248
- except Exception as e:
249
- print(f"❌ Fatal error creating app: {e}")
250
- import traceback
251
- traceback.print_exc()
252
-
253
- # Create a minimal error interface
254
- import gradio as gr
255
-
256
- def show_error():
257
- return f"""
258
- # ❌ Application Error
259
 
260
- **Fatal Error:** {str(e)}
 
261
 
262
- Please check:
263
- 1. OPENAI_API_KEY is set in Spaces Secrets
264
- 2. All required files are uploaded
265
- 3. Check the logs for detailed error information
 
 
 
 
 
 
 
 
 
 
 
 
266
 
267
- **Traceback:**
268
- ```
269
- {traceback.format_exc()}
270
- ```
271
- """
272
-
273
- demo = gr.Interface(
274
- fn=show_error,
275
- inputs=None,
276
- outputs=gr.Markdown(),
277
- title="CSRC Car Manual RAG System - Error",
278
- description="An error occurred. Please check the logs."
279
- )
 
 
280
 
281
  # Note: Do NOT call demo.launch() here
282
  # Hugging Face Spaces will automatically detect and launch the demo
 
13
  # Add the current directory to Python path for Spaces environment
14
  sys.path.insert(0, str(Path(__file__).parent))
15
 
16
+ # Global flag to prevent duplicate initialization
17
+ _app_initialized = False
18
+
19
  from openai import OpenAI
20
  from src.config import Config
21
  from src.vector_store import VectorStoreManager
 
215
 
216
  # Build Gradio interface
217
  print("\n🌐 Building Gradio interface...")
218
+ try:
219
+ interface_builder = GradioInterfaceBuilder(
220
+ rag_engine=components["rag_engine"],
221
+ question_generator=components["question_generator"],
222
+ knowledge_graph=components["knowledge_graph"],
223
+ config=components["config"],
224
+ user_profiling=components["user_profiling"],
225
+ adaptive_engine=components["adaptive_engine"],
226
+ proactive_engine=components["proactive_engine"]
227
+ )
228
+
229
+ # Create interface (without auth parameter to avoid compatibility issues)
230
+ print("Creating Gradio Blocks...")
231
+ demo = interface_builder.create_interface()
232
+ print("βœ… Gradio interface created successfully!")
233
+
234
+ # Set authentication for Hugging Face Spaces
235
+ # Note: In Gradio 6.0 on Spaces, auth should be set via launch() parameters
236
+ # Since Spaces auto-launches, we'll store auth config for potential use
237
+ if auth_username and auth_password:
238
+ auth_config = (auth_username, auth_password)
239
+ # Store auth config - Spaces may use this when auto-launching
240
+ # For Gradio 6.0, we can't directly set demo.auth before launch
241
+ # Spaces will handle authentication if configured properly
242
+ demo._hf_auth = auth_config
243
+ print("βœ… Authentication credentials stored (Spaces will handle on launch)")
244
+
245
+ return demo
246
+ except Exception as e:
247
+ print(f"❌ Error building Gradio interface: {e}")
248
+ import traceback
249
+ traceback.print_exc()
250
+ # Return a simple error interface
251
+ import gradio as gr
252
+ error_demo = gr.Interface(
253
+ fn=lambda: f"Error building interface: {str(e)}",
254
+ inputs=None,
255
+ outputs="text",
256
+ title="CSRC Car Manual RAG System - Interface Error"
257
+ )
258
+ return error_demo
259
 
260
 
261
  # Create the app for Hugging Face Spaces
262
  # Spaces will automatically detect Gradio and run this
263
+ # Use global flag to prevent duplicate initialization
264
+ if not _app_initialized:
265
+ _app_initialized = True
266
+ try:
267
+ demo = create_app()
268
+ print("βœ… App created successfully!")
269
+ print(f"βœ… Demo type: {type(demo)}")
270
+ except Exception as e:
271
+ print(f"❌ Fatal error creating app: {e}")
272
+ import traceback
273
+ traceback.print_exc()
 
 
 
 
274
 
275
+ # Create a minimal error interface
276
+ import gradio as gr
277
 
278
+ def show_error():
279
+ return f"""
280
+ # ❌ Application Error
281
+
282
+ **Fatal Error:** {str(e)}
283
+
284
+ Please check:
285
+ 1. OPENAI_API_KEY is set in Spaces Secrets
286
+ 2. All required files are uploaded
287
+ 3. Check the logs for detailed error information
288
+
289
+ **Traceback:**
290
+ ```
291
+ {traceback.format_exc()}
292
+ ```
293
+ """
294
 
295
+ demo = gr.Interface(
296
+ fn=show_error,
297
+ inputs=None,
298
+ outputs=gr.Markdown(),
299
+ title="CSRC Car Manual RAG System - Error",
300
+ description="An error occurred. Please check the logs."
301
+ )
302
+ else:
303
+ # If already initialized, skip to avoid duplicate initialization
304
+ print("⚠️ App already initialized, skipping duplicate initialization")
305
+ # demo should already be defined from first initialization
306
+ if 'demo' not in globals():
307
+ # Fallback: create a simple demo if somehow not defined
308
+ import gradio as gr
309
+ demo = gr.Interface(fn=lambda: "App is initializing...", inputs=None, outputs="text")
310
 
311
  # Note: Do NOT call demo.launch() here
312
  # Hugging Face Spaces will automatically detect and launch the demo