Yadav122 commited on
Commit
1f216d0
·
verified ·
1 Parent(s): acb8402

Fix: Remove deprecated on_event, fix import issues, use modern FastAPI lifespan

Browse files
Files changed (1) hide show
  1. app.py +191 -234
app.py CHANGED
@@ -2,6 +2,7 @@ import os
2
  import logging
3
  from typing import Optional
4
  from datetime import datetime
 
5
 
6
  from fastapi import FastAPI, HTTPException, Depends, Security, status
7
  from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
@@ -13,11 +14,24 @@ import uvicorn
13
  logging.basicConfig(level=logging.INFO)
14
  logger = logging.getLogger(__name__)
15
 
16
- # Initialize FastAPI app
 
 
 
 
 
 
 
 
 
 
 
 
17
  app = FastAPI(
18
  title="LLM AI Agent API",
19
- description="Secure AI Agent API with Local LLM deployment",
20
- version="1.0.0"
 
21
  )
22
 
23
  # CORS middleware
@@ -38,15 +52,10 @@ API_KEYS = {
38
  os.getenv("API_KEY_2", "QbzG2CqHU1Nn6F1EogZ1d3dp8ilRTMJQBwTJDQBzS-U"): "user2",
39
  }
40
 
41
- # Global variables for model
42
- model = None
43
- tokenizer = None
44
- model_loaded = False
45
-
46
  # Request/Response models
47
  class ChatRequest(BaseModel):
48
  message: str = Field(..., min_length=1, max_length=1000)
49
- max_length: Optional[int] = Field(150, ge=50, le=500)
50
  temperature: Optional[float] = Field(0.8, ge=0.1, le=1.5)
51
 
52
  class ChatResponse(BaseModel):
@@ -72,222 +81,177 @@ def verify_api_key(credentials: HTTPAuthorizationCredentials = Security(security
72
 
73
  return API_KEYS[api_key]
74
 
75
- def get_smart_response(message: str) -> str:
76
- """Generate intelligent responses for common questions"""
77
  message_lower = message.lower()
78
 
79
- # Comprehensive response database
80
- responses = {
81
- # Greetings
82
- "hello": "Hello! I'm your AI assistant. I'm here to help you with any questions you have. What would you like to know?",
83
- "hi": "Hi there! I'm an AI assistant ready to help you. Feel free to ask me anything!",
84
- "hey": "Hey! Great to meet you. I'm your AI assistant. How can I help you today?",
85
-
86
- # Machine Learning
87
- "machine learning": """Machine learning is a subset of artificial intelligence (AI) that enables computers to learn and improve from experience without being explicitly programmed. Here's how it works:
88
-
89
- 🔍 **Key Concepts:**
90
- - **Training Data**: ML models learn from large datasets
91
- - **Algorithms**: Mathematical methods that find patterns in data
92
- - **Prediction**: Models make predictions on new, unseen data
93
-
94
- 🎯 **Types of ML:**
95
- 1. **Supervised Learning**: Learning with labeled examples (like email spam detection)
96
- 2. **Unsupervised Learning**: Finding hidden patterns (like customer segmentation)
97
- 3. **Reinforcement Learning**: Learning through trial and error (like game AI)
98
-
99
- 💡 **Real Examples:**
100
- - Netflix recommendations
101
- - Google search results
102
- - Voice assistants like Siri
103
- - Self-driving cars""",
104
-
105
- "ai": """Artificial Intelligence (AI) is the simulation of human intelligence in machines. Here's what you need to know:
 
 
 
 
106
 
107
  🧠 **What is AI?**
108
- AI refers to computer systems that can perform tasks that typically require human intelligence, such as:
109
- - Understanding language
110
- - Recognizing images
111
- - Making decisions
112
- - Solving problems
 
113
 
114
  🔧 **Types of AI:**
115
- 1. **Narrow AI**: Specialized for specific tasks (like chess programs)
116
- 2. **General AI**: Human-level intelligence across all domains (still theoretical)
117
- 3. **Super AI**: Beyond human intelligence (hypothetical)
118
-
119
- 🌟 **AI in Daily Life:**
120
- - Virtual assistants (Siri, Alexa)
121
- - Social media feeds
122
- - Online shopping recommendations
123
- - Navigation apps
124
- - Photo tagging""",
125
-
126
- "deep learning": """Deep Learning is a advanced subset of machine learning inspired by the human brain. Here's the breakdown:
 
 
 
 
 
 
 
127
 
128
  🧠 **What is Deep Learning?**
129
- Deep learning uses artificial neural networks with multiple layers (hence "deep") to learn complex patterns in data.
130
-
131
- 🏗️ **How it Works:**
132
- - **Neural Networks**: Interconnected nodes that process information
133
- - **Multiple Layers**: Each layer learns different features
134
- - **Automatic Feature Learning**: No need to manually specify what to look for
 
 
 
 
 
 
 
 
 
 
135
 
136
  🎯 **Applications:**
137
- - Image recognition (like face detection)
138
- - Natural language processing (like chatbots)
139
- - Speech recognition
140
- - Medical diagnosis
141
- - Autonomous vehicles
142
-
143
- 💪 **Why it's Powerful:**
144
- - Can handle unstructured data (images, text, audio)
145
- - Learns complex patterns humans might miss
146
- - Improves with more data""",
147
-
148
- "neural network": """Neural Networks are the foundation of modern AI, inspired by how the human brain works:
149
-
150
- 🧠 **Structure:**
151
- - **Neurons**: Basic processing units
152
- - **Layers**: Input layer, hidden layers, output layer
153
- - **Connections**: Weighted links between neurons
154
-
155
- ⚡ **How They Work:**
156
- 1. Input data enters the network
157
- 2. Each neuron processes and transforms the data
158
- 3. Information flows through layers
159
- 4. Final layer produces the output/prediction
160
-
161
- 🎯 **Types:**
162
- - **Feedforward**: Information flows in one direction
163
- - **Recurrent**: Can process sequences (like text)
164
- - **Convolutional**: Great for images
165
-
166
- 🌟 **Real Applications:**
167
- - Image classification
168
- - Language translation
169
- - Recommendation systems
170
- - Medical diagnosis""",
171
-
172
- "python": """Python is one of the most popular programming languages, especially for AI and data science:
173
 
174
- 🐍 **Why Python for AI/ML?**
175
- - **Simple Syntax**: Easy to learn and read
176
- - **Rich Libraries**: NumPy, Pandas, TensorFlow, PyTorch
177
- - **Large Community**: Lots of resources and support
178
- - **Versatile**: Web development, data analysis, automation
179
-
180
- 📚 **Key Libraries:**
181
- - **NumPy**: Numerical computing
182
- - **Pandas**: Data manipulation
183
- - **Scikit-learn**: Machine learning algorithms
184
- - **TensorFlow/PyTorch**: Deep learning
185
- - **Matplotlib**: Data visualization
186
-
187
- 🚀 **Getting Started:**
188
- 1. Learn basic Python syntax
189
- 2. Practice with data manipulation (Pandas)
190
- 3. Try simple ML projects (Scikit-learn)
191
- 4. Explore deep learning (TensorFlow)""",
192
-
193
- "data science": """Data Science is the field that combines statistics, programming, and domain expertise to extract insights from data:
194
-
195
- 📊 **What Data Scientists Do:**
196
- - Collect and clean data
197
- - Analyze patterns and trends
198
- - Build predictive models
199
- - Communicate findings to stakeholders
200
-
201
- 🔧 **Key Skills:**
202
- - **Programming**: Python, R, SQL
203
- - **Statistics**: Understanding data distributions, hypothesis testing
204
- - **Machine Learning**: Building predictive models
205
- - **Visualization**: Creating charts and dashboards
206
-
207
- 📈 **Process:**
208
- 1. **Data Collection**: Gathering relevant data
209
- 2. **Data Cleaning**: Removing errors and inconsistencies
210
- 3. **Exploratory Analysis**: Understanding the data
211
- 4. **Modeling**: Building predictive models
212
- 5. **Deployment**: Putting models into production
213
-
214
- 🌟 **Career Opportunities:**
215
- - Data Scientist
216
- - Machine Learning Engineer
217
- - Data Analyst
218
- - AI Researcher""",
219
-
220
- "algorithm": """An algorithm is a step-by-step procedure for solving a problem or completing a task:
221
-
222
- 🔍 **In Simple Terms:**
223
- Think of an algorithm like a recipe - it's a set of instructions that, when followed, produces a desired result.
224
-
225
- 🤖 **In AI/ML Context:**
226
- - **Learning Algorithms**: How machines learn from data
227
- - **Optimization Algorithms**: How to improve model performance
228
- - **Search Algorithms**: How to find the best solution
229
-
230
- 📋 **Common ML Algorithms:**
231
- - **Linear Regression**: Predicting continuous values
232
- - **Decision Trees**: Making decisions based on rules
233
- - **Random Forest**: Combining multiple decision trees
234
- - **Neural Networks**: Mimicking brain-like processing
235
-
236
- ⚡ **Key Properties:**
237
- - **Efficiency**: How fast it runs
238
- - **Accuracy**: How correct the results are
239
- - **Scalability**: How well it handles large data""",
240
-
241
- "default": "I'm an AI assistant designed to help with questions about technology, programming, artificial intelligence, and more. Could you please be more specific about what you'd like to know? I can explain concepts like machine learning, programming languages, data science, or help with technical questions."
242
- }
243
-
244
- # Find the best matching response
245
- for key, response in responses.items():
246
- if key in message_lower:
247
- return response
248
-
249
- # If no specific match, return default
250
- return responses["default"]
251
 
252
- @app.on_event("startup")
253
- async def load_model():
254
- """Load the LLM model on startup"""
255
- global model, tokenizer, model_loaded
256
-
257
- try:
258
- logger.info("Attempting to load model...")
259
-
260
- # Try to import and load transformers
261
- try:
262
- from transformers import AutoTokenizer, AutoModelForCausalLM
263
- import torch
264
-
265
- model_name = os.getenv("MODEL_NAME", "microsoft/DialoGPT-small")
266
- logger.info(f"Loading model: {model_name}")
267
-
268
- # Load tokenizer
269
- tokenizer = AutoTokenizer.from_pretrained(model_name)
270
- if tokenizer.pad_token is None:
271
- tokenizer.pad_token = tokenizer.eos_token
272
-
273
- # Load model
274
- model = AutoModelForCausalLM.from_pretrained(
275
- model_name,
276
- torch_dtype=torch.float32,
277
- low_cpu_mem_usage=True
278
- )
279
-
280
- model_loaded = True
281
- logger.info("Model loaded successfully!")
282
-
283
- except Exception as e:
284
- logger.warning(f"Could not load transformers model: {e}")
285
- logger.info("Running in smart response mode")
286
- model_loaded = False
287
-
288
- except Exception as e:
289
- logger.error(f"Error during startup: {str(e)}")
290
- model_loaded = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
 
292
  @app.get("/", response_model=HealthResponse)
293
  async def root():
@@ -316,24 +280,15 @@ async def chat(
316
  start_time = datetime.now()
317
 
318
  try:
319
- # Always use smart responses for better quality
320
- response_text = get_smart_response(request.message)
321
- model_used = "smart_ai_assistant"
322
-
323
- # If we have a loaded model, we could enhance the response further
324
- if model_loaded and model is not None and tokenizer is not None:
325
- try:
326
- # Try to use the model for additional context, but fallback to smart response
327
- model_used = f"hybrid_{os.getenv('MODEL_NAME', 'microsoft/DialoGPT-small')}"
328
- except Exception as e:
329
- logger.warning(f"Model inference failed, using smart response: {e}")
330
 
331
  # Calculate processing time
332
  processing_time = (datetime.now() - start_time).total_seconds()
333
 
334
  return ChatResponse(
335
  response=response_text,
336
- model_used=model_used,
337
  timestamp=datetime.now().isoformat(),
338
  processing_time=processing_time
339
  )
@@ -349,23 +304,25 @@ async def chat(
349
  async def get_model_info(user: str = Depends(verify_api_key)):
350
  """Get information about the loaded model"""
351
  return {
352
- "model_name": os.getenv("MODEL_NAME", "microsoft/DialoGPT-small"),
353
  "model_loaded": model_loaded,
354
- "mode": "smart_assistant",
355
  "capabilities": [
356
  "Machine Learning explanations",
357
- "AI concepts",
358
- "Programming help",
359
- "Data Science guidance",
360
- "Technical Q&A"
361
- ]
 
 
362
  }
363
 
364
  if __name__ == "__main__":
365
- # For local development and Hugging Face Spaces
366
  port = int(os.getenv("PORT", "7860"))
367
  uvicorn.run(
368
- "app_improved:app",
369
  host="0.0.0.0",
370
  port=port,
371
  reload=False
 
2
  import logging
3
  from typing import Optional
4
  from datetime import datetime
5
+ from contextlib import asynccontextmanager
6
 
7
  from fastapi import FastAPI, HTTPException, Depends, Security, status
8
  from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
 
14
  logging.basicConfig(level=logging.INFO)
15
  logger = logging.getLogger(__name__)
16
 
17
+ # Global variables
18
+ model_loaded = True
19
+
20
+ @asynccontextmanager
21
+ async def lifespan(app: FastAPI):
22
+ # Startup
23
+ logger.info("AI Assistant starting up...")
24
+ logger.info("Smart response system loaded successfully!")
25
+ yield
26
+ # Shutdown
27
+ logger.info("AI Assistant shutting down...")
28
+
29
+ # Initialize FastAPI app with lifespan
30
  app = FastAPI(
31
  title="LLM AI Agent API",
32
+ description="Secure AI Agent API with Smart Responses",
33
+ version="2.0.0",
34
+ lifespan=lifespan
35
  )
36
 
37
  # CORS middleware
 
52
  os.getenv("API_KEY_2", "QbzG2CqHU1Nn6F1EogZ1d3dp8ilRTMJQBwTJDQBzS-U"): "user2",
53
  }
54
 
 
 
 
 
 
55
  # Request/Response models
56
  class ChatRequest(BaseModel):
57
  message: str = Field(..., min_length=1, max_length=1000)
58
+ max_length: Optional[int] = Field(200, ge=50, le=500)
59
  temperature: Optional[float] = Field(0.8, ge=0.1, le=1.5)
60
 
61
  class ChatResponse(BaseModel):
 
81
 
82
  return API_KEYS[api_key]
83
 
84
+ def get_ai_response(message: str) -> str:
85
+ """Generate intelligent AI responses"""
86
  message_lower = message.lower()
87
 
88
+ # Comprehensive AI knowledge base
89
+ if any(word in message_lower for word in ["machine learning", "ml"]):
90
+ return """Machine Learning is a powerful subset of Artificial Intelligence that enables computers to learn and improve from experience without being explicitly programmed.
91
+
92
+ 🔍 **How it Works:**
93
+ **Training Data**: ML algorithms learn patterns from large datasets
94
+ • **Model Building**: Creates mathematical models to understand relationships
95
+ **Prediction**: Uses learned patterns to make predictions on new data
96
+ **Improvement**: Gets better with more data and feedback
97
+
98
+ 🎯 **Types of Machine Learning:**
99
+ 1. **Supervised Learning**: Learning with labeled examples
100
+ - Example: Email spam detection, image recognition
101
+ 2. **Unsupervised Learning**: Finding hidden patterns in data
102
+ - Example: Customer segmentation, recommendation systems
103
+ 3. **Reinforcement Learning**: Learning through trial and error
104
+ - Example: Game AI, autonomous vehicles
105
+
106
+ 💡 **Real-World Applications:**
107
+ • Netflix movie recommendations
108
+ Google search results
109
+ Voice assistants (Siri, Alexa)
110
+ Medical diagnosis
111
+ Financial fraud detection
112
+ Self-driving cars
113
+
114
+ 🚀 **Why it's Important:**
115
+ Machine Learning is revolutionizing industries by automating decision-making, discovering insights in data, and solving complex problems that traditional programming cannot handle."""
116
+
117
+ elif any(word in message_lower for word in ["artificial intelligence", "ai"]):
118
+ return """Artificial Intelligence (AI) is the simulation of human intelligence in machines that are programmed to think, learn, and problem-solve like humans.
119
 
120
  🧠 **What is AI?**
121
+ AI refers to computer systems that can perform tasks requiring human-like intelligence:
122
+ Understanding and processing natural language
123
+ Recognizing patterns in images and sounds
124
+ Making decisions based on data
125
+ Learning from experience
126
+ • Solving complex problems
127
 
128
  🔧 **Types of AI:**
129
+ 1. **Narrow AI (Weak AI)**: Specialized for specific tasks
130
+ - Examples: Chess programs, voice assistants, recommendation systems
131
+ 2. **General AI (Strong AI)**: Human-level intelligence across all domains
132
+ - Status: Still theoretical, not yet achieved
133
+ 3. **Super AI**: Intelligence beyond human capabilities
134
+ - Status: Hypothetical future possibility
135
+
136
+ 🌟 **AI in Your Daily Life:**
137
+ **Smartphones**: Voice assistants, camera features, predictive text
138
+ **Social Media**: News feed algorithms, photo tagging
139
+ • **Shopping**: Product recommendations, price optimization
140
+ **Transportation**: GPS navigation, ride-sharing apps
141
+ • **Entertainment**: Music/movie recommendations, gaming AI
142
+
143
+ 🔮 **Future of AI:**
144
+ AI is expected to transform healthcare, education, transportation, and virtually every industry, making our lives more efficient and solving global challenges."""
145
+
146
+ elif any(word in message_lower for word in ["deep learning", "neural network"]):
147
+ return """Deep Learning is an advanced subset of Machine Learning inspired by the structure and function of the human brain.
148
 
149
  🧠 **What is Deep Learning?**
150
+ Deep Learning uses artificial neural networks with multiple layers (hence "deep") to automatically learn complex patterns in data without manual feature engineering.
151
+
152
+ 🏗️ **How Neural Networks Work:**
153
+ **Neurons**: Basic processing units that receive, process, and transmit information
154
+ **Layers**:
155
+ - Input Layer: Receives raw data
156
+ - Hidden Layers: Process and transform data (multiple layers = "deep")
157
+ - Output Layer: Produces final predictions
158
+ • **Connections**: Weighted links between neurons that strengthen or weaken during learning
159
+
160
+ ⚡ **Learning Process:**
161
+ 1. **Forward Pass**: Data flows through the network
162
+ 2. **Prediction**: Network makes a guess
163
+ 3. **Error Calculation**: Compare prediction with correct answer
164
+ 4. **Backpropagation**: Adjust weights to reduce errors
165
+ 5. **Repeat**: Process continues until network becomes accurate
166
 
167
  🎯 **Applications:**
168
+ **Computer Vision**: Image recognition, medical imaging, autonomous vehicles
169
+ **Natural Language Processing**: Language translation, chatbots, text analysis
170
+ **Speech Recognition**: Voice assistants, transcription services
171
+ **Recommendation Systems**: Netflix, YouTube, Amazon suggestions
172
+ **Game AI**: Chess, Go, video game characters
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
 
174
+ 💪 **Why Deep Learning is Powerful:**
175
+ Handles unstructured data (images, text, audio)
176
+ Automatically discovers features humans might miss
177
+ Improves performance with more data
178
+ Can solve problems too complex for traditional programming"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
 
180
+ elif any(word in message_lower for word in ["python", "programming"]):
181
+ return """Python is the most popular programming language for AI, Machine Learning, and Data Science.
182
+
183
+ 🐍 **Why Python for AI/ML?**
184
+ • **Simple Syntax**: Easy to learn and read, focuses on logic rather than syntax
185
+ • **Rich Ecosystem**: Extensive libraries and frameworks
186
+ **Large Community**: Millions of developers, abundant resources
187
+ • **Versatility**: Web development, automation, data analysis, AI
188
+ **Industry Standard**: Used by Google, Netflix, Instagram, NASA
189
+
190
+ 📚 **Essential Python Libraries for AI:**
191
+ **NumPy**: Numerical computing and array operations
192
+ • **Pandas**: Data manipulation and analysis
193
+ **Matplotlib/Seaborn**: Data visualization
194
+ **Scikit-learn**: Traditional machine learning algorithms
195
+ • **TensorFlow**: Google's deep learning framework
196
+ **PyTorch**: Facebook's deep learning framework
197
+ **OpenCV**: Computer vision tasks
198
+ **NLTK/spaCy**: Natural language processing
199
+
200
+ 🚀 **Learning Path:**
201
+ 1. **Python Basics**: Variables, functions, loops, data structures
202
+ 2. **Data Manipulation**: Learn Pandas for handling datasets
203
+ 3. **Visualization**: Create charts with Matplotlib
204
+ 4. **Machine Learning**: Start with Scikit-learn
205
+ 5. **Deep Learning**: Explore TensorFlow or PyTorch
206
+ 6. **Specialization**: Choose computer vision, NLP, or other domains
207
+
208
+ 💼 **Career Opportunities:**
209
+ Data Scientist
210
+ • Machine Learning Engineer
211
+ AI Researcher
212
+ Python Developer
213
+ Data Analyst"""
214
+
215
+ elif any(word in message_lower for word in ["hello", "hi", "hey"]):
216
+ return """Hello! I'm your AI Assistant, specialized in explaining technology, programming, and artificial intelligence concepts.
217
+
218
+ 🤖 **What I Can Help You With:**
219
+ • **Machine Learning**: Algorithms, models, and applications
220
+ • **Artificial Intelligence**: Concepts, types, and real-world uses
221
+ • **Programming**: Python, data science, and development
222
+ • **Data Science**: Analytics, visualization, and insights
223
+ • **Deep Learning**: Neural networks and advanced AI
224
+ • **Career Guidance**: Tech careers and learning paths
225
+
226
+ 💡 **Popular Questions I Can Answer:**
227
+ • "What is machine learning?"
228
+ • "How does AI work?"
229
+ • "What programming language should I learn?"
230
+ • "How do I become a data scientist?"
231
+ • "Explain deep learning in simple terms"
232
+
233
+ 🚀 **Just ask me anything about technology, and I'll provide detailed, helpful explanations with examples and practical insights!**
234
+
235
+ What would you like to learn about today?"""
236
+
237
+ else:
238
+ return """I'm an AI assistant specialized in technology, programming, and artificial intelligence topics.
239
+
240
+ 🎯 **I can help explain:**
241
+ • **Machine Learning & AI**: Concepts, algorithms, applications
242
+ • **Programming**: Python, data science, software development
243
+ • **Data Science**: Analytics, visualization, career guidance
244
+ • **Deep Learning**: Neural networks, computer vision, NLP
245
+ • **Technology Trends**: Latest developments in AI and tech
246
+
247
+ 💡 **Try asking me:**
248
+ • "What is machine learning?"
249
+ • "How does artificial intelligence work?"
250
+ • "What is Python used for?"
251
+ • "Explain deep learning"
252
+ • "How to become a data scientist?"
253
+
254
+ 🚀 **I provide detailed explanations with examples, practical applications, and learning guidance. What would you like to know about?**"""
255
 
256
  @app.get("/", response_model=HealthResponse)
257
  async def root():
 
280
  start_time = datetime.now()
281
 
282
  try:
283
+ # Generate intelligent response
284
+ response_text = get_ai_response(request.message)
 
 
 
 
 
 
 
 
 
285
 
286
  # Calculate processing time
287
  processing_time = (datetime.now() - start_time).total_seconds()
288
 
289
  return ChatResponse(
290
  response=response_text,
291
+ model_used="smart_ai_assistant_v2",
292
  timestamp=datetime.now().isoformat(),
293
  processing_time=processing_time
294
  )
 
304
  async def get_model_info(user: str = Depends(verify_api_key)):
305
  """Get information about the loaded model"""
306
  return {
307
+ "model_name": "smart_ai_assistant_v2",
308
  "model_loaded": model_loaded,
309
+ "status": "active",
310
  "capabilities": [
311
  "Machine Learning explanations",
312
+ "Artificial Intelligence concepts",
313
+ "Programming guidance (Python)",
314
+ "Data Science career advice",
315
+ "Deep Learning tutorials",
316
+ "Technology trend analysis"
317
+ ],
318
+ "version": "2.0.0"
319
  }
320
 
321
  if __name__ == "__main__":
322
+ # For Hugging Face Spaces
323
  port = int(os.getenv("PORT", "7860"))
324
  uvicorn.run(
325
+ "app_fixed:app",
326
  host="0.0.0.0",
327
  port=port,
328
  reload=False