Bryceeee commited on
Commit
505874e
Β·
verified Β·
1 Parent(s): 3146957

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +260 -0
app.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
5
+ Note: For local development, use main.py instead.
6
+ """
7
+ import os
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ # Detect if running in Hugging Face Spaces
12
+ IS_SPACES = os.getenv("SPACE_ID") is not None or os.getenv("HF_SPACE") is not None
13
+
14
+ # Add the current directory to Python path for Spaces environment
15
+ sys.path.insert(0, str(Path(__file__).parent))
16
+
17
+ from openai import OpenAI
18
+ from src.config import Config
19
+ from src.vector_store import VectorStoreManager
20
+ from src.rag_query import RAGQueryEngine
21
+ from src.question_generator import QuestionGenerator
22
+ from src.knowledge_graph import KnowledgeGraphGenerator
23
+ from src.gradio_interface import GradioInterfaceBuilder
24
+
25
+ # Import personalized learning if available
26
+ try:
27
+ from modules.personalized_learning import UserProfilingSystem, LearningPathGenerator, AdaptiveLearningEngine
28
+ PERSONALIZED_LEARNING_AVAILABLE = True
29
+ except ImportError:
30
+ PERSONALIZED_LEARNING_AVAILABLE = False
31
+ print("⚠️ Personalized learning modules not available")
32
+
33
+ # Import proactive learning if available
34
+ try:
35
+ from modules.proactive_learning import ProactiveLearningEngine
36
+ PROACTIVE_LEARNING_AVAILABLE = True
37
+ except ImportError:
38
+ PROACTIVE_LEARNING_AVAILABLE = False
39
+ print("⚠️ Proactive learning modules not available")
40
+
41
+ # Import scenario contextualization if available
42
+ try:
43
+ from modules.scenario_contextualization.database.scenario_database import ScenarioDatabase
44
+ from modules.scenario_contextualization.integration.feature_extractor import ADASFeatureExtractor
45
+ from modules.scenario_contextualization.retrieval.scenario_retriever import ScenarioRetriever
46
+ from modules.scenario_contextualization.formatting.constructive_formatter import ConstructiveFormatter
47
+ from modules.scenario_contextualization.integration.enhanced_rag_engine import EnhancedRAGEngine
48
+ SCENARIO_CONTEXTUALIZATION_AVAILABLE = True
49
+ except ImportError as e:
50
+ SCENARIO_CONTEXTUALIZATION_AVAILABLE = False
51
+ print(f"⚠️ Scenario contextualization modules not available: {e}")
52
+
53
+
54
+ def initialize_system(config: Config) -> dict:
55
+ """Initialize the RAG system components"""
56
+ # Initialize OpenAI client
57
+ if not config.openai_api_key:
58
+ raise ValueError(
59
+ "OPENAI_API_KEY not found! Please set it in Hugging Face Spaces Secrets. "
60
+ "Go to Settings > Secrets and add OPENAI_API_KEY"
61
+ )
62
+
63
+ client = OpenAI(api_key=config.openai_api_key)
64
+
65
+ # Initialize vector store manager
66
+ vector_store_manager = VectorStoreManager(client)
67
+
68
+ # Get or create vector store
69
+ vector_store_id = config.get_vector_store_id()
70
+
71
+ if not vector_store_id:
72
+ print("πŸ“¦ Creating new vector store...")
73
+ pdf_files = config.get_pdf_files()
74
+
75
+ if not pdf_files:
76
+ raise ValueError(f"No PDF files found in {config.car_manual_dir}")
77
+
78
+ vector_store_details = vector_store_manager.create_vector_store(config.vector_store_name)
79
+ if not vector_store_details:
80
+ raise RuntimeError("Failed to create vector store")
81
+
82
+ vector_store_id = vector_store_details["id"]
83
+ config.save_vector_store_id(vector_store_id, config.vector_store_name)
84
+
85
+ # Upload files
86
+ upload_stats = vector_store_manager.upload_pdf_files(pdf_files, vector_store_id)
87
+ if upload_stats["successful_uploads"] == 0:
88
+ raise RuntimeError("Failed to upload any files")
89
+ else:
90
+ print(f"βœ… Using existing vector store: {vector_store_id}")
91
+
92
+ # Initialize RAG query engine
93
+ rag_engine = RAGQueryEngine(client, vector_store_id, config.model)
94
+
95
+ # Initialize question generator
96
+ question_generator = QuestionGenerator(client, rag_engine)
97
+
98
+ # Initialize knowledge graph generator
99
+ knowledge_graph = KnowledgeGraphGenerator(client, vector_store_id, str(config.output_dir))
100
+
101
+ # Initialize personalized learning (if available)
102
+ user_profiling = None
103
+ learning_path_generator = None
104
+ adaptive_engine = None
105
+
106
+ if PERSONALIZED_LEARNING_AVAILABLE:
107
+ try:
108
+ user_profiling = UserProfilingSystem()
109
+ learning_path_generator = LearningPathGenerator(user_profiling, config.available_topics)
110
+ adaptive_engine = AdaptiveLearningEngine(user_profiling, learning_path_generator)
111
+ print("βœ… Personalized Learning System initialized!")
112
+ except Exception as e:
113
+ print(f"⚠️ Error initializing Personalized Learning System: {e}")
114
+
115
+ # Initialize proactive learning (if available)
116
+ proactive_engine = None
117
+ if PROACTIVE_LEARNING_AVAILABLE and user_profiling:
118
+ try:
119
+ proactive_engine = ProactiveLearningEngine(
120
+ client, rag_engine, user_profiling, adaptive_engine, config.available_topics
121
+ )
122
+ print("βœ… Proactive Learning Assistance initialized!")
123
+ except Exception as e:
124
+ print(f"⚠️ Error initializing Proactive Learning Assistance: {e}")
125
+
126
+ # Initialize scenario contextualization (if available)
127
+ enhanced_rag_engine = None
128
+ if SCENARIO_CONTEXTUALIZATION_AVAILABLE:
129
+ try:
130
+ scenario_database = ScenarioDatabase()
131
+ feature_extractor = ADASFeatureExtractor(use_llm=False, client=client)
132
+ scenario_retriever = ScenarioRetriever(
133
+ scenario_database=scenario_database,
134
+ scenario_vector_store_id=None,
135
+ client=client
136
+ )
137
+ formatter = ConstructiveFormatter()
138
+ enhanced_rag_engine = EnhancedRAGEngine(
139
+ base_rag_engine=rag_engine,
140
+ scenario_retriever=scenario_retriever,
141
+ feature_extractor=feature_extractor,
142
+ formatter=formatter
143
+ )
144
+ print("βœ… Scenario Contextualization initialized!")
145
+ except Exception as e:
146
+ print(f"⚠️ Error initializing Scenario Contextualization: {e}")
147
+ import traceback
148
+ traceback.print_exc()
149
+
150
+ return {
151
+ "client": client,
152
+ "vector_store_manager": vector_store_manager,
153
+ "rag_engine": rag_engine,
154
+ "question_generator": question_generator,
155
+ "knowledge_graph": knowledge_graph,
156
+ "user_profiling": user_profiling,
157
+ "learning_path_generator": learning_path_generator,
158
+ "adaptive_engine": adaptive_engine,
159
+ "proactive_engine": proactive_engine,
160
+ "enhanced_rag_engine": enhanced_rag_engine,
161
+ "config": config
162
+ }
163
+
164
+
165
+ def create_app():
166
+ """Create and return the Gradio app for Hugging Face Spaces"""
167
+ print("=" * 60)
168
+ print("πŸš— CSRC Car Manual RAG System - Hugging Face Spaces")
169
+ print("=" * 60)
170
+
171
+ # Load configuration
172
+ config = Config()
173
+
174
+ # Initialize system
175
+ try:
176
+ components = initialize_system(config)
177
+ except Exception as e:
178
+ print(f"❌ Error initializing system: {e}")
179
+ import gradio as gr
180
+
181
+ # Create error interface
182
+ error_msg = f"""
183
+ # ❌ Initialization Error
184
+
185
+ **Error:** {str(e)}
186
+
187
+ **Possible solutions:**
188
+ 1. Check if OPENAI_API_KEY is set in Spaces Secrets (Settings > Secrets)
189
+ 2. Ensure PDF files are in the `car_manual/` directory
190
+ 3. Check the logs for more details
191
+ """
192
+
193
+ def error_display():
194
+ return error_msg
195
+
196
+ error_interface = gr.Interface(
197
+ fn=error_display,
198
+ inputs=None,
199
+ outputs=gr.Markdown(),
200
+ title="CSRC Car Manual RAG System",
201
+ description="An error occurred during initialization. Please check the logs."
202
+ )
203
+ return error_interface
204
+
205
+ # Build Gradio interface
206
+ print("\n🌐 Building Gradio interface...")
207
+ interface_builder = GradioInterfaceBuilder(
208
+ rag_engine=components["rag_engine"],
209
+ question_generator=components["question_generator"],
210
+ knowledge_graph=components["knowledge_graph"],
211
+ config=components["config"],
212
+ user_profiling=components["user_profiling"],
213
+ adaptive_engine=components["adaptive_engine"],
214
+ proactive_engine=components["proactive_engine"]
215
+ )
216
+
217
+ demo = interface_builder.create_interface()
218
+ return demo
219
+
220
+
221
+ # Create the app for Hugging Face Spaces
222
+ # Spaces will automatically detect Gradio and run this
223
+ # Wrap in try-except to ensure demo is always defined
224
+ try:
225
+ demo = create_app()
226
+ except Exception as e:
227
+ print(f"❌ Fatal error creating app: {e}")
228
+ import traceback
229
+ traceback.print_exc()
230
+
231
+ # Create a minimal error interface
232
+ import gradio as gr
233
+
234
+ def show_error():
235
+ return f"""
236
+ # ❌ Application Error
237
+
238
+ **Fatal Error:** {str(e)}
239
+
240
+ Please check:
241
+ 1. OPENAI_API_KEY is set in Spaces Secrets
242
+ 2. All required files are uploaded
243
+ 3. Check the logs for detailed error information
244
+
245
+ **Traceback:**
246
+ ```
247
+ {traceback.format_exc()}
248
+ ```
249
+ """
250
+
251
+ demo = gr.Interface(
252
+ fn=show_error,
253
+ inputs=None,
254
+ outputs=gr.Markdown(),
255
+ title="CSRC Car Manual RAG System - Error",
256
+ description="An error occurred. Please check the logs."
257
+ )
258
+
259
+
260
+