import asyncio import queue import threading import json import os import sys from urllib.parse import urlparse from fastapi import FastAPI, Request, Query from fastapi.responses import StreamingResponse from fastapi.staticfiles import StaticFiles # Add the current directory to sys.path so we can import crawler_core sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from crawler_core import EnhancedWebCrawler, ddg_find_urls app = FastAPI(title="Enhanced Web Crawler Web API") @app.get("/api/crawl") async def api_crawl(request: Request, url: str = Query(...), keyword: str = Query(...), mode: str = Query(...)): if keyword == "Custom": keywords = ["gowithguide"] else: keywords = [k.strip() for k in keyword.split(",")] event_queue = queue.Queue() state = { "crawler_done": False, "search_done": False, "user_stopped": False } def status_callback(msg): event_queue.put(("status", msg)) def progress_callback(val): event_queue.put(("progress", val)) def result_callback(res): event_queue.put(("match", res)) # Create the crawler instance crawler = EnhancedWebCrawler( start_url=url, crawl_mode=mode, keywords=keywords, status_callback=status_callback, progress_callback=progress_callback, result_callback=result_callback ) # Multi-threaded crawler task def crawler_task(): results = [] try: results = crawler.start_crawling() except Exception as e: status_callback(f"Error in crawling process: {str(e)}") event_queue.put(("crawler_finish", len(results))) state["crawler_done"] = True crawling_thread = threading.Thread(target=crawler_task, daemon=True) crawling_thread.start() # Multi-threaded search task (runs automatically in parallel) def search_task(): event_queue.put(("search_start", None)) domain = "" try: parsed = urlparse(url if url.startswith(("http://", "https://")) else "https://" + url) domain = parsed.netloc except Exception: pass if not domain: event_queue.put(("search_finish", {"results": [], "error": "Could not determine domain from URL.", "is_warning": False})) state["search_done"] = True return query = f'site:{domain} "{keywords[0] if keywords else ""}"' try: results, method, error = ddg_find_urls(query, domain=domain, keywords=keywords, max_results=20) is_warning = False if error == 'NO_KEYWORD_DOMAIN_MATCH': is_warning = True results = [] event_queue.put(("search_finish", { "results": results, "error": error if error != 'NO_KEYWORD_DOMAIN_MATCH' else '', "is_warning": is_warning })) except Exception as e: event_queue.put(("search_finish", {"results": [], "error": str(e), "is_warning": False})) state["search_done"] = True search_thread = threading.Thread(target=search_task, daemon=True) search_thread.start() # Generator function yielding Server-Sent Events (SSE) async def event_generator(): try: while not (state["crawler_done"] and state["search_done"] and event_queue.empty()): # If the user disconnected (closed connection/tab or clicked stop) if await request.is_disconnected(): crawler.user_stopped = True state["user_stopped"] = True break # Stream all queued items immediately while not event_queue.empty(): try: event_type, data = event_queue.get_nowait() yield f"event: {event_type}\ndata: {json.dumps(data)}\n\n" except queue.Empty: break await asyncio.sleep(0.1) except Exception as e: # Handle client-specific stream breakages gracefully pass finally: crawler.user_stopped = True return StreamingResponse(event_generator(), media_type="text/event-stream") # Mount the static files UI directory at the root URL path # We mount it at the end so it doesn't mask our API routes ui_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'ui') app.mount("/", StaticFiles(directory=ui_dir, html=True), name="ui") if __name__ == "__main__": import uvicorn # Default to 8080 or port specified by environment (Hugging Face specifies port via ENV or runs on 7860) port = int(os.environ.get("PORT", 8080)) print(f"Starting web server on http://0.0.0.0:{port}") uvicorn.run("web_app:app", host="0.0.0.0", port=port, reload=True)