Speedofmastery commited on
Commit
4d08675
Β·
verified Β·
1 Parent(s): e4b3d6c

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +97 -71
app.py CHANGED
@@ -17,16 +17,27 @@ import uvicorn
17
 
18
  # HuggingFace Inference Client
19
  HF_TOKEN = os.getenv("HF_TOKEN", "")
20
- inference_client = InferenceClient(token=HF_TOKEN if HF_TOKEN else None)
 
 
 
21
 
22
  # Cloudflare Configuration
23
  CLOUDFLARE_CONFIG = {
24
  "api_token": os.getenv("CLOUDFLARE_API_TOKEN", ""),
25
- "account_id": os.getenv("CLOUDFLARE_ACCOUNT_ID", "62af59a7ac82b29543577ee6800735ee"),
26
- "d1_database_id": os.getenv("CLOUDFLARE_D1_DATABASE_ID", "6d887f74-98ac-4db7-bfed-8061903d1f6c"),
 
 
 
 
27
  "r2_bucket_name": os.getenv("CLOUDFLARE_R2_BUCKET_NAME", "openmanus-storage"),
28
- "kv_namespace_id": os.getenv("CLOUDFLARE_KV_NAMESPACE_ID", "87f4aa01410d4fb19821f61006f94441"),
29
- "kv_namespace_cache": os.getenv("CLOUDFLARE_KV_CACHE_ID", "7b58c88292c847d1a82c8e0dd5129f37"),
 
 
 
 
30
  "durable_objects_sessions": "AGENT_SESSIONS",
31
  "durable_objects_chatrooms": "CHAT_ROOMS",
32
  }
@@ -95,12 +106,14 @@ app.add_middleware(
95
  allow_headers=["*"],
96
  )
97
 
 
98
  # Database initialization
99
  def init_database():
100
  """Initialize SQLite database for user authentication"""
101
  conn = sqlite3.connect("openmanus.db")
102
  cursor = conn.cursor()
103
- cursor.execute("""
 
104
  CREATE TABLE IF NOT EXISTS users (
105
  id INTEGER PRIMARY KEY AUTOINCREMENT,
106
  mobile TEXT UNIQUE NOT NULL,
@@ -108,44 +121,54 @@ def init_database():
108
  password_hash TEXT NOT NULL,
109
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
110
  )
111
- """)
 
112
  conn.commit()
113
  conn.close()
114
 
 
115
  init_database()
116
 
 
117
  # Pydantic Models
118
  class SignupRequest(BaseModel):
119
  mobile: str
120
  name: str
121
  password: str
122
 
 
123
  class LoginRequest(BaseModel):
124
  mobile: str
125
  password: str
126
 
 
127
  class AIRequest(BaseModel):
128
  model: str
129
  prompt: str
130
  max_tokens: Optional[int] = 2000
131
  temperature: Optional[float] = 0.7
132
 
 
133
  class ChatRequest(BaseModel):
134
  message: str
135
  model: Optional[str] = "Qwen/Qwen2.5-72B-Instruct"
136
  history: Optional[List[Dict[str, str]]] = []
137
 
 
138
  # Helper Functions
139
  def hash_password(password: str) -> str:
140
  """Hash password using SHA-256"""
141
  return hashlib.sha256(password.encode()).hexdigest()
142
 
 
143
  def verify_password(password: str, password_hash: str) -> bool:
144
  """Verify password against hash"""
145
  return hash_password(password) == password_hash
146
 
 
147
  # API Endpoints
148
 
 
149
  @app.get("/")
150
  async def root():
151
  """Root endpoint"""
@@ -159,9 +182,10 @@ async def root():
159
  "auth": "/auth/signup, /auth/login",
160
  "ai": "/ai/chat, /ai/generate",
161
  "models": "/models/list",
162
- }
163
  }
164
 
 
165
  @app.get("/health")
166
  async def health_check():
167
  """Health check endpoint"""
@@ -174,100 +198,103 @@ async def health_check():
174
  "cloudflare_configured": bool(CLOUDFLARE_CONFIG["api_token"]),
175
  }
176
 
 
177
  @app.post("/auth/signup")
178
  async def signup(request: SignupRequest):
179
  """User registration endpoint"""
180
  try:
181
  if len(request.password) < 6:
182
- raise HTTPException(status_code=400, detail="Password must be at least 6 characters")
183
-
 
 
184
  conn = sqlite3.connect("openmanus.db")
185
  cursor = conn.cursor()
186
-
187
  # Check if user exists
188
  cursor.execute("SELECT mobile FROM users WHERE mobile = ?", (request.mobile,))
189
  if cursor.fetchone():
190
  conn.close()
191
- raise HTTPException(status_code=400, detail="Mobile number already registered")
192
-
 
 
193
  # Insert new user
194
  password_hash = hash_password(request.password)
195
  cursor.execute(
196
  "INSERT INTO users (mobile, name, password_hash) VALUES (?, ?, ?)",
197
- (request.mobile, request.name, password_hash)
198
  )
199
  conn.commit()
200
  conn.close()
201
-
202
  return {
203
  "success": True,
204
  "message": "Account created successfully",
205
  "mobile": request.mobile,
206
- "name": request.name
207
  }
208
-
209
  except HTTPException:
210
  raise
211
  except Exception as e:
212
  raise HTTPException(status_code=500, detail=f"Registration failed: {str(e)}")
213
 
 
214
  @app.post("/auth/login")
215
  async def login(request: LoginRequest):
216
  """User login endpoint"""
217
  try:
218
  conn = sqlite3.connect("openmanus.db")
219
  cursor = conn.cursor()
220
-
221
  cursor.execute(
222
- "SELECT name, password_hash FROM users WHERE mobile = ?",
223
- (request.mobile,)
224
  )
225
  result = cursor.fetchone()
226
  conn.close()
227
-
228
  if not result:
229
- raise HTTPException(status_code=401, detail="Invalid mobile number or password")
230
-
 
 
231
  name, password_hash = result
232
-
233
  if not verify_password(request.password, password_hash):
234
- raise HTTPException(status_code=401, detail="Invalid mobile number or password")
235
-
 
 
236
  return {
237
  "success": True,
238
  "message": "Login successful",
239
- "user": {
240
- "mobile": request.mobile,
241
- "name": name
242
- },
243
- "token": f"session_{hash_password(request.mobile + str(datetime.now()))[:32]}"
244
  }
245
-
246
  except HTTPException:
247
  raise
248
  except Exception as e:
249
  raise HTTPException(status_code=500, detail=f"Login failed: {str(e)}")
250
 
 
251
  @app.post("/ai/chat")
252
  async def ai_chat(request: ChatRequest):
253
  """AI chat endpoint - main endpoint for AI interactions"""
254
  try:
255
  # Prepare messages for chat completion
256
  messages = []
257
-
258
  # Add history
259
  for msg in request.history:
260
- messages.append({
261
- "role": msg.get("role", "user"),
262
- "content": msg.get("content", "")
263
- })
264
-
265
  # Add current message
266
- messages.append({
267
- "role": "user",
268
- "content": request.message
269
- })
270
-
271
  # Call HuggingFace Inference API
272
  response_text = ""
273
  for message in inference_client.chat_completion(
@@ -275,30 +302,31 @@ async def ai_chat(request: ChatRequest):
275
  messages=messages,
276
  max_tokens=2000,
277
  temperature=0.7,
278
- stream=True
279
  ):
280
- if hasattr(message, 'choices') and len(message.choices) > 0:
281
  delta = message.choices[0].delta
282
- if hasattr(delta, 'content') and delta.content:
283
  response_text += delta.content
284
-
285
  return {
286
  "success": True,
287
  "response": response_text,
288
  "model": request.model,
289
- "timestamp": datetime.now().isoformat()
290
  }
291
-
292
  except Exception as e:
293
  raise HTTPException(status_code=500, detail=f"AI generation failed: {str(e)}")
294
 
 
295
  @app.post("/ai/generate")
296
  async def ai_generate(request: AIRequest):
297
  """Generic AI generation endpoint"""
298
  try:
299
  # Determine task type based on model
300
  model_lower = request.model.lower()
301
-
302
  if "flux" in model_lower or "stable-diffusion" in model_lower:
303
  # Image generation
304
  return {
@@ -306,9 +334,9 @@ async def ai_generate(request: AIRequest):
306
  "type": "image",
307
  "message": f"Image generation with {request.model}",
308
  "prompt": request.prompt,
309
- "note": "Image will be generated using HuggingFace Inference API"
310
  }
311
-
312
  elif "video" in model_lower:
313
  # Video generation
314
  return {
@@ -316,51 +344,53 @@ async def ai_generate(request: AIRequest):
316
  "type": "video",
317
  "message": f"Video generation with {request.model}",
318
  "prompt": request.prompt,
319
- "note": "Video will be generated using HuggingFace Inference API"
320
  }
321
-
322
  else:
323
  # Text generation (default)
324
  messages = [{"role": "user", "content": request.prompt}]
325
  response_text = ""
326
-
327
  for message in inference_client.chat_completion(
328
  model=request.model,
329
  messages=messages,
330
  max_tokens=request.max_tokens,
331
  temperature=request.temperature,
332
- stream=True
333
  ):
334
- if hasattr(message, 'choices') and len(message.choices) > 0:
335
  delta = message.choices[0].delta
336
- if hasattr(delta, 'content') and delta.content:
337
  response_text += delta.content
338
-
339
  return {
340
  "success": True,
341
  "type": "text",
342
  "response": response_text,
343
  "model": request.model,
344
- "timestamp": datetime.now().isoformat()
345
  }
346
-
347
  except Exception as e:
348
  raise HTTPException(status_code=500, detail=f"Generation failed: {str(e)}")
349
 
 
350
  @app.get("/models/list")
351
  async def list_models():
352
  """List all available AI models"""
353
  return {
354
  "total": 211,
355
  "categories": AI_MODELS,
356
- "note": "All models are accessed via HuggingFace Inference API"
357
  }
358
 
 
359
  @app.get("/cloudflare/status")
360
  async def cloudflare_status():
361
  """Cloudflare services status"""
362
  services = []
363
-
364
  if CLOUDFLARE_CONFIG["api_token"]:
365
  services.append("βœ… API Token Configured")
366
  if CLOUDFLARE_CONFIG["d1_database_id"]:
@@ -375,17 +405,13 @@ async def cloudflare_status():
375
  services.append("βœ… Durable Objects (Agent Sessions)")
376
  if CLOUDFLARE_CONFIG["durable_objects_chatrooms"]:
377
  services.append("βœ… Durable Objects (Chat Rooms)")
378
-
379
  return {
380
  "configured": len(services) > 0,
381
  "services": services,
382
- "account_id": CLOUDFLARE_CONFIG["account_id"]
383
  }
384
 
 
385
  if __name__ == "__main__":
386
- uvicorn.run(
387
- app,
388
- host="0.0.0.0",
389
- port=7860,
390
- log_level="info"
391
- )
 
17
 
18
  # HuggingFace Inference Client
19
  HF_TOKEN = os.getenv("HF_TOKEN", "")
20
+ inference_client = InferenceClient(
21
+ token=HF_TOKEN if HF_TOKEN else None,
22
+ base_url="https://router.huggingface.co/hf-inference"
23
+ )
24
 
25
  # Cloudflare Configuration
26
  CLOUDFLARE_CONFIG = {
27
  "api_token": os.getenv("CLOUDFLARE_API_TOKEN", ""),
28
+ "account_id": os.getenv(
29
+ "CLOUDFLARE_ACCOUNT_ID", "62af59a7ac82b29543577ee6800735ee"
30
+ ),
31
+ "d1_database_id": os.getenv(
32
+ "CLOUDFLARE_D1_DATABASE_ID", "6d887f74-98ac-4db7-bfed-8061903d1f6c"
33
+ ),
34
  "r2_bucket_name": os.getenv("CLOUDFLARE_R2_BUCKET_NAME", "openmanus-storage"),
35
+ "kv_namespace_id": os.getenv(
36
+ "CLOUDFLARE_KV_NAMESPACE_ID", "87f4aa01410d4fb19821f61006f94441"
37
+ ),
38
+ "kv_namespace_cache": os.getenv(
39
+ "CLOUDFLARE_KV_CACHE_ID", "7b58c88292c847d1a82c8e0dd5129f37"
40
+ ),
41
  "durable_objects_sessions": "AGENT_SESSIONS",
42
  "durable_objects_chatrooms": "CHAT_ROOMS",
43
  }
 
106
  allow_headers=["*"],
107
  )
108
 
109
+
110
  # Database initialization
111
  def init_database():
112
  """Initialize SQLite database for user authentication"""
113
  conn = sqlite3.connect("openmanus.db")
114
  cursor = conn.cursor()
115
+ cursor.execute(
116
+ """
117
  CREATE TABLE IF NOT EXISTS users (
118
  id INTEGER PRIMARY KEY AUTOINCREMENT,
119
  mobile TEXT UNIQUE NOT NULL,
 
121
  password_hash TEXT NOT NULL,
122
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
123
  )
124
+ """
125
+ )
126
  conn.commit()
127
  conn.close()
128
 
129
+
130
  init_database()
131
 
132
+
133
  # Pydantic Models
134
  class SignupRequest(BaseModel):
135
  mobile: str
136
  name: str
137
  password: str
138
 
139
+
140
  class LoginRequest(BaseModel):
141
  mobile: str
142
  password: str
143
 
144
+
145
  class AIRequest(BaseModel):
146
  model: str
147
  prompt: str
148
  max_tokens: Optional[int] = 2000
149
  temperature: Optional[float] = 0.7
150
 
151
+
152
  class ChatRequest(BaseModel):
153
  message: str
154
  model: Optional[str] = "Qwen/Qwen2.5-72B-Instruct"
155
  history: Optional[List[Dict[str, str]]] = []
156
 
157
+
158
  # Helper Functions
159
  def hash_password(password: str) -> str:
160
  """Hash password using SHA-256"""
161
  return hashlib.sha256(password.encode()).hexdigest()
162
 
163
+
164
  def verify_password(password: str, password_hash: str) -> bool:
165
  """Verify password against hash"""
166
  return hash_password(password) == password_hash
167
 
168
+
169
  # API Endpoints
170
 
171
+
172
  @app.get("/")
173
  async def root():
174
  """Root endpoint"""
 
182
  "auth": "/auth/signup, /auth/login",
183
  "ai": "/ai/chat, /ai/generate",
184
  "models": "/models/list",
185
+ },
186
  }
187
 
188
+
189
  @app.get("/health")
190
  async def health_check():
191
  """Health check endpoint"""
 
198
  "cloudflare_configured": bool(CLOUDFLARE_CONFIG["api_token"]),
199
  }
200
 
201
+
202
  @app.post("/auth/signup")
203
  async def signup(request: SignupRequest):
204
  """User registration endpoint"""
205
  try:
206
  if len(request.password) < 6:
207
+ raise HTTPException(
208
+ status_code=400, detail="Password must be at least 6 characters"
209
+ )
210
+
211
  conn = sqlite3.connect("openmanus.db")
212
  cursor = conn.cursor()
213
+
214
  # Check if user exists
215
  cursor.execute("SELECT mobile FROM users WHERE mobile = ?", (request.mobile,))
216
  if cursor.fetchone():
217
  conn.close()
218
+ raise HTTPException(
219
+ status_code=400, detail="Mobile number already registered"
220
+ )
221
+
222
  # Insert new user
223
  password_hash = hash_password(request.password)
224
  cursor.execute(
225
  "INSERT INTO users (mobile, name, password_hash) VALUES (?, ?, ?)",
226
+ (request.mobile, request.name, password_hash),
227
  )
228
  conn.commit()
229
  conn.close()
230
+
231
  return {
232
  "success": True,
233
  "message": "Account created successfully",
234
  "mobile": request.mobile,
235
+ "name": request.name,
236
  }
237
+
238
  except HTTPException:
239
  raise
240
  except Exception as e:
241
  raise HTTPException(status_code=500, detail=f"Registration failed: {str(e)}")
242
 
243
+
244
  @app.post("/auth/login")
245
  async def login(request: LoginRequest):
246
  """User login endpoint"""
247
  try:
248
  conn = sqlite3.connect("openmanus.db")
249
  cursor = conn.cursor()
250
+
251
  cursor.execute(
252
+ "SELECT name, password_hash FROM users WHERE mobile = ?", (request.mobile,)
 
253
  )
254
  result = cursor.fetchone()
255
  conn.close()
256
+
257
  if not result:
258
+ raise HTTPException(
259
+ status_code=401, detail="Invalid mobile number or password"
260
+ )
261
+
262
  name, password_hash = result
263
+
264
  if not verify_password(request.password, password_hash):
265
+ raise HTTPException(
266
+ status_code=401, detail="Invalid mobile number or password"
267
+ )
268
+
269
  return {
270
  "success": True,
271
  "message": "Login successful",
272
+ "user": {"mobile": request.mobile, "name": name},
273
+ "token": f"session_{hash_password(request.mobile + str(datetime.now()))[:32]}",
 
 
 
274
  }
275
+
276
  except HTTPException:
277
  raise
278
  except Exception as e:
279
  raise HTTPException(status_code=500, detail=f"Login failed: {str(e)}")
280
 
281
+
282
  @app.post("/ai/chat")
283
  async def ai_chat(request: ChatRequest):
284
  """AI chat endpoint - main endpoint for AI interactions"""
285
  try:
286
  # Prepare messages for chat completion
287
  messages = []
288
+
289
  # Add history
290
  for msg in request.history:
291
+ messages.append(
292
+ {"role": msg.get("role", "user"), "content": msg.get("content", "")}
293
+ )
294
+
 
295
  # Add current message
296
+ messages.append({"role": "user", "content": request.message})
297
+
 
 
 
298
  # Call HuggingFace Inference API
299
  response_text = ""
300
  for message in inference_client.chat_completion(
 
302
  messages=messages,
303
  max_tokens=2000,
304
  temperature=0.7,
305
+ stream=True,
306
  ):
307
+ if hasattr(message, "choices") and len(message.choices) > 0:
308
  delta = message.choices[0].delta
309
+ if hasattr(delta, "content") and delta.content:
310
  response_text += delta.content
311
+
312
  return {
313
  "success": True,
314
  "response": response_text,
315
  "model": request.model,
316
+ "timestamp": datetime.now().isoformat(),
317
  }
318
+
319
  except Exception as e:
320
  raise HTTPException(status_code=500, detail=f"AI generation failed: {str(e)}")
321
 
322
+
323
  @app.post("/ai/generate")
324
  async def ai_generate(request: AIRequest):
325
  """Generic AI generation endpoint"""
326
  try:
327
  # Determine task type based on model
328
  model_lower = request.model.lower()
329
+
330
  if "flux" in model_lower or "stable-diffusion" in model_lower:
331
  # Image generation
332
  return {
 
334
  "type": "image",
335
  "message": f"Image generation with {request.model}",
336
  "prompt": request.prompt,
337
+ "note": "Image will be generated using HuggingFace Inference API",
338
  }
339
+
340
  elif "video" in model_lower:
341
  # Video generation
342
  return {
 
344
  "type": "video",
345
  "message": f"Video generation with {request.model}",
346
  "prompt": request.prompt,
347
+ "note": "Video will be generated using HuggingFace Inference API",
348
  }
349
+
350
  else:
351
  # Text generation (default)
352
  messages = [{"role": "user", "content": request.prompt}]
353
  response_text = ""
354
+
355
  for message in inference_client.chat_completion(
356
  model=request.model,
357
  messages=messages,
358
  max_tokens=request.max_tokens,
359
  temperature=request.temperature,
360
+ stream=True,
361
  ):
362
+ if hasattr(message, "choices") and len(message.choices) > 0:
363
  delta = message.choices[0].delta
364
+ if hasattr(delta, "content") and delta.content:
365
  response_text += delta.content
366
+
367
  return {
368
  "success": True,
369
  "type": "text",
370
  "response": response_text,
371
  "model": request.model,
372
+ "timestamp": datetime.now().isoformat(),
373
  }
374
+
375
  except Exception as e:
376
  raise HTTPException(status_code=500, detail=f"Generation failed: {str(e)}")
377
 
378
+
379
  @app.get("/models/list")
380
  async def list_models():
381
  """List all available AI models"""
382
  return {
383
  "total": 211,
384
  "categories": AI_MODELS,
385
+ "note": "All models are accessed via HuggingFace Inference API",
386
  }
387
 
388
+
389
  @app.get("/cloudflare/status")
390
  async def cloudflare_status():
391
  """Cloudflare services status"""
392
  services = []
393
+
394
  if CLOUDFLARE_CONFIG["api_token"]:
395
  services.append("βœ… API Token Configured")
396
  if CLOUDFLARE_CONFIG["d1_database_id"]:
 
405
  services.append("βœ… Durable Objects (Agent Sessions)")
406
  if CLOUDFLARE_CONFIG["durable_objects_chatrooms"]:
407
  services.append("βœ… Durable Objects (Chat Rooms)")
408
+
409
  return {
410
  "configured": len(services) > 0,
411
  "services": services,
412
+ "account_id": CLOUDFLARE_CONFIG["account_id"],
413
  }
414
 
415
+
416
  if __name__ == "__main__":
417
+ uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info")