Bryceeee commited on
Commit
e0b680e
ยท
verified ยท
1 Parent(s): 6b12097

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +290 -95
app.py CHANGED
@@ -1,113 +1,308 @@
 
 
 
 
 
1
  import os
2
- import gradio as gr
 
3
 
4
- def test_auth():
5
- """ๆต‹่ฏ•่ฎค่ฏๅŠŸ่ƒฝ"""
6
- # ไปŽ็Žฏๅขƒๅ˜้‡่ฏปๅ–็”จๆˆทๅๅ’Œๅฏ†็ 
7
- username = os.getenv("APP_USERNAME", "")
8
- password = os.getenv("APP_PASSWORD", "")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- print("=" * 60)
11
- print("๐Ÿ” Authentication Test - Environment Variables")
12
- print("=" * 60)
13
- print(f"APP_USERNAME: {'โœ… Set' if username else 'โŒ Not Set'}")
14
- print(f"APP_PASSWORD: {'โœ… Set' if password else 'โŒ Not Set'}")
15
 
16
- if username:
17
- print(f"Username value: {username}")
18
- if password:
19
- print(f"Password value: {'*' * len(password)} (length: {len(password)})")
20
 
21
- # ๅˆ›ๅปบ็ฎ€ๅ•็š„็•Œ้ข
22
- def greet(name):
23
- return f"Hello, {name}! Authentication is working correctly."
24
 
25
- # ๅˆ›ๅปบ Gradio ็•Œ้ข
26
- with gr.Blocks(title="Authentication Test") as demo:
27
- gr.Markdown("# ๐Ÿ” Authentication Test")
28
- gr.Markdown("This is a minimal test to verify username/password authentication works in Hugging Face Spaces.")
29
 
30
- with gr.Row():
31
- with gr.Column():
32
- gr.Markdown("## Environment Variables Status")
33
- username_status = "โœ… Set" if username else "โŒ Not Set"
34
- password_status = "โœ… Set" if password else "โŒ Not Set"
35
-
36
- gr.Markdown(f"""
37
- - **APP_USERNAME**: {username_status}
38
- - **APP_PASSWORD**: {password_status}
39
- """)
40
-
41
- if username:
42
- gr.Markdown(f"- Username value: `{username}`")
43
- if password:
44
- gr.Markdown(f"- Password length: {len(password)} characters")
45
 
46
- with gr.Row():
47
- with gr.Column():
48
- gr.Markdown("## Test Function")
49
- name_input = gr.Textbox(
50
- label="Enter your name",
51
- placeholder="Type your name here..."
52
- )
53
- output = gr.Textbox(label="Output")
54
- greet_btn = gr.Button("Test", variant="primary")
55
-
56
- greet_btn.click(
57
- fn=greet,
58
- inputs=name_input,
59
- outputs=output
60
- )
61
 
62
- gr.Markdown("---")
63
- gr.Markdown("### Instructions")
64
- gr.Markdown("""
65
- 1. If you see this page, the app is running
66
- 2. Check if authentication is required (you should see a login prompt)
67
- 3. Use the username and password set in Spaces Secrets
68
- 4. If authentication works, you can access this page
69
- 5. If authentication fails, check the Spaces Secrets configuration
70
- """)
71
-
72
- # ่ฎพ็ฝฎ่ฎค่ฏ๏ผˆๅฆ‚ๆžœ็”จๆˆทๅๅ’Œๅฏ†็ ้ƒฝๅทฒ่ฎพ็ฝฎ๏ผ‰
73
- if username and password:
74
- print(f"โœ… Setting authentication for user: {username}")
75
- demo.auth = (username, password)
76
- print("โœ… Authentication configured on demo object")
77
  else:
78
- print("โš ๏ธ Authentication not configured - missing username or password")
79
- if not username:
80
- print(" - APP_USERNAME is not set in Spaces Secrets")
81
- if not password:
82
- print(" - APP_PASSWORD is not set in Spaces Secrets")
 
 
 
 
 
 
 
 
 
 
83
 
84
- return demo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
- # ๅˆ›ๅปบๆต‹่ฏ•ๅบ”็”จ
87
- print("=" * 60)
88
- print("๏ฟฝ๏ฟฝ Starting Authentication Test App")
89
- print("=" * 60)
90
 
91
- try:
92
- demo = test_auth()
93
- print("โœ… Test app created successfully!")
94
- print(f"โœ… Demo type: {type(demo)}")
95
- print(f"โœ… Demo.auth: {getattr(demo, 'auth', 'Not set')}")
96
- except Exception as e:
97
- print(f"โŒ Error creating test app: {e}")
98
- import traceback
99
- traceback.print_exc()
100
 
101
- # ๅˆ›ๅปบ้”™่ฏฏ็•Œ้ข
102
- def show_error():
103
- return f"Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
- demo = gr.Interface(
106
- fn=show_error,
107
- inputs=None,
108
- outputs="text",
109
- title="Authentication Test - Error"
110
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
  # Note: Do NOT call demo.launch() here
113
  # Hugging Face Spaces will automatically detect and launch the demo
 
1
+ """
2
+ Hugging Face Spaces Entry Point for CSRC Car Manual RAG System
3
+ This is the entry point for Hugging Face Spaces deployment
4
+ Note: For local development, use main.py instead.
5
+ """
6
  import os
7
+ import sys
8
+ from pathlib import Path
9
 
10
+ # Detect if running in Hugging Face Spaces
11
+ IS_SPACES = os.getenv("SPACE_ID") is not None or os.getenv("HF_SPACE") is not None
12
+
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
+ _demo_created = False
19
+
20
+ from openai import OpenAI
21
+ from src.config import Config
22
+ from src.vector_store import VectorStoreManager
23
+ from src.rag_query import RAGQueryEngine
24
+ from src.question_generator import QuestionGenerator
25
+ from src.knowledge_graph import KnowledgeGraphGenerator
26
+ from src.gradio_interface import GradioInterfaceBuilder
27
+
28
+ # Import personalized learning if available
29
+ try:
30
+ from modules.personalized_learning import UserProfilingSystem, LearningPathGenerator, AdaptiveLearningEngine
31
+ PERSONALIZED_LEARNING_AVAILABLE = True
32
+ except ImportError:
33
+ PERSONALIZED_LEARNING_AVAILABLE = False
34
+ print("โš ๏ธ Personalized learning modules not available")
35
+
36
+ # Import proactive learning if available
37
+ try:
38
+ from modules.proactive_learning import ProactiveLearningEngine
39
+ PROACTIVE_LEARNING_AVAILABLE = True
40
+ except ImportError:
41
+ PROACTIVE_LEARNING_AVAILABLE = False
42
+ print("โš ๏ธ Proactive learning modules not available")
43
+
44
+ # Import scenario contextualization if available
45
+ try:
46
+ from modules.scenario_contextualization.database.scenario_database import ScenarioDatabase
47
+ from modules.scenario_contextualization.integration.feature_extractor import ADASFeatureExtractor
48
+ from modules.scenario_contextualization.retrieval.scenario_retriever import ScenarioRetriever
49
+ from modules.scenario_contextualization.formatting.constructive_formatter import ConstructiveFormatter
50
+ from modules.scenario_contextualization.integration.enhanced_rag_engine import EnhancedRAGEngine
51
+ SCENARIO_CONTEXTUALIZATION_AVAILABLE = True
52
+ except ImportError as e:
53
+ SCENARIO_CONTEXTUALIZATION_AVAILABLE = False
54
+ print(f"โš ๏ธ Scenario contextualization modules not available: {e}")
55
+
56
+
57
+ def initialize_system(config: Config) -> dict:
58
+ """Initialize the RAG system components"""
59
+ # Initialize OpenAI client
60
+ if not config.openai_api_key:
61
+ raise ValueError(
62
+ "OPENAI_API_KEY not found! Please set it in Hugging Face Spaces Secrets. "
63
+ "Go to Settings > Secrets and add OPENAI_API_KEY"
64
+ )
65
 
66
+ client = OpenAI(api_key=config.openai_api_key)
 
 
 
 
67
 
68
+ # Initialize vector store manager
69
+ vector_store_manager = VectorStoreManager(client)
 
 
70
 
71
+ # Get or create vector store
72
+ vector_store_id = config.get_vector_store_id()
 
73
 
74
+ if not vector_store_id:
75
+ print("๐Ÿ“ฆ Creating new vector store...")
76
+ pdf_files = config.get_pdf_files()
 
77
 
78
+ if not pdf_files:
79
+ raise ValueError(f"No PDF files found in {config.car_manual_dir}")
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
+ vector_store_details = vector_store_manager.create_vector_store(config.vector_store_name)
82
+ if not vector_store_details:
83
+ raise RuntimeError("Failed to create vector store")
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
+ vector_store_id = vector_store_details["id"]
86
+ config.save_vector_store_id(vector_store_id, config.vector_store_name)
87
+
88
+ # Upload files
89
+ upload_stats = vector_store_manager.upload_pdf_files(pdf_files, vector_store_id)
90
+ if upload_stats["successful_uploads"] == 0:
91
+ raise RuntimeError("Failed to upload any files")
 
 
 
 
 
 
 
 
92
  else:
93
+ print(f"โœ… Using existing vector store: {vector_store_id}")
94
+
95
+ # Initialize RAG query engine
96
+ rag_engine = RAGQueryEngine(client, vector_store_id, config.model)
97
+
98
+ # Initialize question generator
99
+ question_generator = QuestionGenerator(client, rag_engine)
100
+
101
+ # Initialize knowledge graph generator
102
+ knowledge_graph = KnowledgeGraphGenerator(client, vector_store_id, str(config.output_dir))
103
+
104
+ # Initialize personalized learning (if available)
105
+ user_profiling = None
106
+ learning_path_generator = None
107
+ adaptive_engine = None
108
 
109
+ if PERSONALIZED_LEARNING_AVAILABLE:
110
+ try:
111
+ user_profiling = UserProfilingSystem()
112
+ learning_path_generator = LearningPathGenerator(user_profiling, config.available_topics)
113
+ adaptive_engine = AdaptiveLearningEngine(user_profiling, learning_path_generator)
114
+ print("โœ… Personalized Learning System initialized!")
115
+ except Exception as e:
116
+ print(f"โš ๏ธ Error initializing Personalized Learning System: {e}")
117
+
118
+ # Initialize proactive learning (if available)
119
+ proactive_engine = None
120
+ if PROACTIVE_LEARNING_AVAILABLE and user_profiling:
121
+ try:
122
+ proactive_engine = ProactiveLearningEngine(
123
+ client, rag_engine, user_profiling, adaptive_engine, config.available_topics
124
+ )
125
+ print("โœ… Proactive Learning Assistance initialized!")
126
+ except Exception as e:
127
+ print(f"โš ๏ธ Error initializing Proactive Learning Assistance: {e}")
128
+
129
+ # Initialize scenario contextualization (if available)
130
+ enhanced_rag_engine = None
131
+ if SCENARIO_CONTEXTUALIZATION_AVAILABLE:
132
+ try:
133
+ scenario_database = ScenarioDatabase()
134
+ feature_extractor = ADASFeatureExtractor(use_llm=False, client=client)
135
+ scenario_retriever = ScenarioRetriever(
136
+ scenario_database=scenario_database,
137
+ scenario_vector_store_id=None,
138
+ client=client
139
+ )
140
+ formatter = ConstructiveFormatter()
141
+ enhanced_rag_engine = EnhancedRAGEngine(
142
+ base_rag_engine=rag_engine,
143
+ scenario_retriever=scenario_retriever,
144
+ feature_extractor=feature_extractor,
145
+ formatter=formatter
146
+ )
147
+ print("โœ… Scenario Contextualization initialized!")
148
+ except Exception as e:
149
+ print(f"โš ๏ธ Error initializing Scenario Contextualization: {e}")
150
+ import traceback
151
+ traceback.print_exc()
152
+
153
+ return {
154
+ "client": client,
155
+ "vector_store_manager": vector_store_manager,
156
+ "rag_engine": rag_engine,
157
+ "question_generator": question_generator,
158
+ "knowledge_graph": knowledge_graph,
159
+ "user_profiling": user_profiling,
160
+ "learning_path_generator": learning_path_generator,
161
+ "adaptive_engine": adaptive_engine,
162
+ "proactive_engine": proactive_engine,
163
+ "enhanced_rag_engine": enhanced_rag_engine,
164
+ "config": config
165
+ }
166
 
 
 
 
 
167
 
168
+ def create_app():
169
+ """Create and return the Gradio app for Hugging Face Spaces"""
170
+ print("=" * 60)
171
+ print("๐Ÿš— CSRC Car Manual RAG System - Hugging Face Spaces")
172
+ print("=" * 60)
 
 
 
 
173
 
174
+ # Load configuration
175
+ config = Config()
176
+
177
+ # Initialize system
178
+ try:
179
+ components = initialize_system(config)
180
+ except Exception as e:
181
+ print(f"โŒ Error initializing system: {e}")
182
+ import gradio as gr
183
+
184
+ # Create error interface
185
+ error_msg = f"""
186
+ # โŒ Initialization Error
187
+
188
+ **Error:** {str(e)}
189
+
190
+ **Possible solutions:**
191
+ 1. Check if OPENAI_API_KEY is set in Spaces Secrets (Settings > Secrets)
192
+ 2. Ensure PDF files are in the `car_manual/` directory
193
+ 3. Check the logs for more details
194
+ """
195
+
196
+ def error_display():
197
+ return error_msg
198
+
199
+ error_interface = gr.Interface(
200
+ fn=error_display,
201
+ inputs=None,
202
+ outputs=gr.Markdown(),
203
+ title="CSRC Car Manual RAG System",
204
+ description="An error occurred during initialization. Please check the logs."
205
+ )
206
+ return error_interface
207
 
208
+ # Build Gradio interface
209
+ print("\n๐ŸŒ Building Gradio interface...")
210
+ try:
211
+ interface_builder = GradioInterfaceBuilder(
212
+ rag_engine=components["rag_engine"],
213
+ question_generator=components["question_generator"],
214
+ knowledge_graph=components["knowledge_graph"],
215
+ config=components["config"],
216
+ user_profiling=components["user_profiling"],
217
+ adaptive_engine=components["adaptive_engine"],
218
+ proactive_engine=components["proactive_engine"]
219
+ )
220
+
221
+ # Create interface
222
+ print("Creating Gradio Blocks...")
223
+ demo = interface_builder.create_interface()
224
+ print("โœ… Gradio interface created successfully!")
225
+
226
+ return demo
227
+ except Exception as e:
228
+ print(f"โŒ Error building Gradio interface: {e}")
229
+ import traceback
230
+ traceback.print_exc()
231
+ # Return a simple error interface
232
+ import gradio as gr
233
+ error_demo = gr.Interface(
234
+ fn=lambda: f"Error building interface: {str(e)}",
235
+ inputs=None,
236
+ outputs="text",
237
+ title="CSRC Car Manual RAG System - Interface Error"
238
+ )
239
+ return error_demo
240
+
241
+
242
+ # Create the app for Hugging Face Spaces
243
+ # Spaces will automatically detect Gradio and run this
244
+ # Use module-level variable and flag to prevent duplicate initialization
245
+
246
+ # Initialize demo variable to None
247
+ demo = None
248
+
249
+ # Check if demo was already created (prevent duplicate initialization)
250
+ if _demo_created and 'demo' in globals() and demo is not None:
251
+ print("โš ๏ธ Demo already created, skipping duplicate initialization")
252
+ print(f"โœ… Reusing existing demo: {type(demo)}")
253
+ else:
254
+ # First time initialization
255
+ if not _app_initialized:
256
+ _app_initialized = True
257
+ try:
258
+ print("๐Ÿ”„ Starting app initialization (first time)...")
259
+ demo = create_app()
260
+ _demo_created = True
261
+ print("โœ… App created successfully!")
262
+ print(f"โœ… Demo type: {type(demo)}")
263
+ except Exception as e:
264
+ print(f"โŒ Fatal error creating app: {e}")
265
+ import traceback
266
+ traceback.print_exc()
267
+
268
+ # Create a minimal error interface
269
+ import gradio as gr
270
+
271
+ def show_error():
272
+ return f"""
273
+ # โŒ Application Error
274
+
275
+ **Fatal Error:** {str(e)}
276
+
277
+ Please check:
278
+ 1. OPENAI_API_KEY is set in Spaces Secrets
279
+ 2. All required files are uploaded
280
+ 3. Check the logs for detailed error information
281
+
282
+ **Traceback:**
283
+ ```
284
+ {traceback.format_exc()}
285
+ ```
286
+ """
287
+
288
+ demo = gr.Interface(
289
+ fn=show_error,
290
+ inputs=None,
291
+ outputs=gr.Markdown(),
292
+ title="CSRC Car Manual RAG System - Error",
293
+ description="An error occurred. Please check the logs."
294
+ )
295
+ _demo_created = True
296
+ else:
297
+ # App was initialized but demo not created (shouldn't happen)
298
+ print("โš ๏ธ App initialized but demo not created, creating fallback...")
299
+ import gradio as gr
300
+ demo = gr.Interface(
301
+ fn=lambda: "App is initializing, please wait...",
302
+ inputs=None,
303
+ outputs="text",
304
+ title="CSRC Car Manual RAG System"
305
+ )
306
 
307
  # Note: Do NOT call demo.launch() here
308
  # Hugging Face Spaces will automatically detect and launch the demo