asmaa105 commited on
Commit
a20a584
Β·
verified Β·
1 Parent(s): 74952b9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -58
app.py CHANGED
@@ -1,4 +1,4 @@
1
- # app.py - HF Spaces compatible version
2
  import os
3
  import re
4
  import json
@@ -6,9 +6,6 @@ from datetime import datetime
6
  from typing import List, Dict, Any
7
 
8
  import gradio as gr
9
- from fastapi import FastAPI, Request, BackgroundTasks
10
- from fastapi.middleware.cors import CORSMiddleware
11
- from pydantic import BaseModel
12
 
13
  # Configuration - Use HF Spaces secrets
14
  WEBHOOK_SECRET = os.getenv("WEBHOOK_SECRET")
@@ -32,12 +29,6 @@ RECOGNIZED_TAGS = {
32
  "llamacpp", "onnx", "mlx"
33
  }
34
 
35
- class WebhookEvent(BaseModel):
36
- event: Dict[str, str]
37
- comment: Dict[str, Any]
38
- discussion: Dict[str, Any]
39
- repo: Dict[str, str]
40
-
41
  def extract_tags_from_text(text: str) -> List[str]:
42
  """Extract potential tags from discussion text"""
43
  text_lower = text.lower()
@@ -240,50 +231,6 @@ async def process_webhook_comment(webhook_data: Dict[str, Any]):
240
  print(f"❌ {error_msg}")
241
  return error_msg
242
 
243
- # Create FastAPI app for webhook handling
244
- fastapi_app = FastAPI(title="HF Tagging Bot API")
245
- fastapi_app.add_middleware(CORSMiddleware, allow_origins=["*"])
246
-
247
- @fastapi_app.post("/webhook")
248
- async def webhook_handler(request: Request, background_tasks: BackgroundTasks):
249
- """Handle HF Hub webhooks"""
250
- # Verify webhook secret if configured
251
- if WEBHOOK_SECRET:
252
- webhook_secret = request.headers.get("X-Webhook-Secret")
253
- if webhook_secret != WEBHOOK_SECRET:
254
- print("❌ Invalid webhook secret")
255
- return {"error": "Invalid webhook secret"}
256
-
257
- try:
258
- payload = await request.json()
259
- print(f"πŸ“₯ Received webhook: {payload.get('event', {})}")
260
-
261
- event = payload.get("event", {})
262
- scope = event.get("scope")
263
- action = event.get("action")
264
-
265
- # Only process discussion comment creation (not PRs)
266
- if (scope == "discussion" and
267
- action == "create" and
268
- not payload.get("discussion", {}).get("isPullRequest", False)):
269
-
270
- background_tasks.add_task(process_webhook_comment, payload)
271
- return {"status": "processing"}
272
-
273
- return {"status": "ignored"}
274
- except Exception as e:
275
- print(f"❌ Webhook error: {e}")
276
- return {"error": str(e)}
277
-
278
- @fastapi_app.get("/health")
279
- async def health_check():
280
- return {
281
- "status": "healthy",
282
- "hf_token_configured": bool(HF_TOKEN),
283
- "webhook_secret_configured": bool(WEBHOOK_SECRET),
284
- "operations_processed": len(tag_operations_store)
285
- }
286
-
287
  def create_gradio_interface():
288
  """Create Gradio interface for monitoring"""
289
  with gr.Blocks(title="HF Tagging Bot", theme=gr.themes.Soft()) as interface:
@@ -383,12 +330,54 @@ Visit: `https://your-space-name.hf.space/health`
383
  # Create the Gradio interface
384
  demo = create_gradio_interface()
385
 
386
- # Mount FastAPI to Gradio (for HF Spaces)
387
- app = gr.mount_gradio_app(fastapi_app, demo, path="/")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
388
 
389
- # This is the main app that HF Spaces will use
390
  if __name__ == "__main__":
391
  print("πŸš€ HF Tagging Bot - Gradio interface ready")
392
  print(f"πŸ”‘ HF_TOKEN: {'βœ… Configured' if HF_TOKEN else '❌ Missing'}")
393
  print(f"πŸ” Webhook Secret: {'βœ… Configured' if WEBHOOK_SECRET else '❌ Missing'}")
394
- demo.launch()
 
1
+ # app.py - HF Spaces compatible version (Fixed)
2
  import os
3
  import re
4
  import json
 
6
  from typing import List, Dict, Any
7
 
8
  import gradio as gr
 
 
 
9
 
10
  # Configuration - Use HF Spaces secrets
11
  WEBHOOK_SECRET = os.getenv("WEBHOOK_SECRET")
 
29
  "llamacpp", "onnx", "mlx"
30
  }
31
 
 
 
 
 
 
 
32
  def extract_tags_from_text(text: str) -> List[str]:
33
  """Extract potential tags from discussion text"""
34
  text_lower = text.lower()
 
231
  print(f"❌ {error_msg}")
232
  return error_msg
233
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234
  def create_gradio_interface():
235
  """Create Gradio interface for monitoring"""
236
  with gr.Blocks(title="HF Tagging Bot", theme=gr.themes.Soft()) as interface:
 
330
  # Create the Gradio interface
331
  demo = create_gradio_interface()
332
 
333
+ # Add webhook handling using Gradio's built-in FastAPI integration
334
+ from fastapi import Request
335
+ import asyncio
336
+
337
+ @demo.app.post("/webhook")
338
+ async def webhook_handler(request: Request):
339
+ """Handle HF Hub webhooks"""
340
+ # Verify webhook secret if configured
341
+ if WEBHOOK_SECRET:
342
+ webhook_secret = request.headers.get("X-Webhook-Secret")
343
+ if webhook_secret != WEBHOOK_SECRET:
344
+ print("❌ Invalid webhook secret")
345
+ return {"error": "Invalid webhook secret"}
346
+
347
+ try:
348
+ payload = await request.json()
349
+ print(f"πŸ“₯ Received webhook: {payload.get('event', {})}")
350
+
351
+ event = payload.get("event", {})
352
+ scope = event.get("scope")
353
+ action = event.get("action")
354
+
355
+ # Only process discussion comment creation (not PRs)
356
+ if (scope == "discussion" and
357
+ action == "create" and
358
+ not payload.get("discussion", {}).get("isPullRequest", False)):
359
+
360
+ # Process webhook in background
361
+ asyncio.create_task(process_webhook_comment(payload))
362
+ return {"status": "processing"}
363
+
364
+ return {"status": "ignored"}
365
+ except Exception as e:
366
+ print(f"❌ Webhook error: {e}")
367
+ return {"error": str(e)}
368
+
369
+ @demo.app.get("/health")
370
+ async def health_check():
371
+ return {
372
+ "status": "healthy",
373
+ "hf_token_configured": bool(HF_TOKEN),
374
+ "webhook_secret_configured": bool(WEBHOOK_SECRET),
375
+ "operations_processed": len(tag_operations_store)
376
+ }
377
 
378
+ # Launch the interface
379
  if __name__ == "__main__":
380
  print("πŸš€ HF Tagging Bot - Gradio interface ready")
381
  print(f"πŸ”‘ HF_TOKEN: {'βœ… Configured' if HF_TOKEN else '❌ Missing'}")
382
  print(f"πŸ” Webhook Secret: {'βœ… Configured' if WEBHOOK_SECRET else '❌ Missing'}")
383
+ demo.launch(server_name="0.0.0.0", server_port=7860)