NightPrince commited on
Commit
97250e9
·
1 Parent(s): fde590b

Hotfix: Pre-load HF Model and Fix HTML Error Responses

Browse files
Files changed (2) hide show
  1. app.py +13 -1
  2. assets/script.js +12 -2
app.py CHANGED
@@ -12,6 +12,15 @@ from hadith_mcp import search_hadith
12
  logging.basicConfig(level=logging.INFO)
13
  logger = logging.getLogger(__name__)
14
 
 
 
 
 
 
 
 
 
 
15
  app = FastAPI(title="Hadith Search API")
16
 
17
  # Allow CORS for HuggingFace Spaces
@@ -55,8 +64,11 @@ if os.path.isdir(assets_dir):
55
  # Serve index.html at root
56
  @app.get("/{full_path:path}")
57
  async def serve_frontend(full_path: str):
 
 
 
58
  path_to_file = os.path.join(base_dir, full_path)
59
- if os.path.isfile(path_to_file) and not full_path.startswith("api/"):
60
  return FileResponse(path_to_file)
61
  return FileResponse(os.path.join(base_dir, "index.html"))
62
 
 
12
  logging.basicConfig(level=logging.INFO)
13
  logger = logging.getLogger(__name__)
14
 
15
+ # Pre-download the model during server boot so the first request doesn't timeout
16
+ try:
17
+ logger.info("Pre-downloading HF model during boot...")
18
+ from sentence_transformers import SentenceTransformer
19
+ SentenceTransformer('sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2')
20
+ logger.info("Model ready!")
21
+ except Exception as e:
22
+ logger.warning(f"Could not pre-download model: {e}")
23
+
24
  app = FastAPI(title="Hadith Search API")
25
 
26
  # Allow CORS for HuggingFace Spaces
 
64
  # Serve index.html at root
65
  @app.get("/{full_path:path}")
66
  async def serve_frontend(full_path: str):
67
+ if full_path.startswith("api/"):
68
+ raise HTTPException(status_code=404, detail="API route not found")
69
+
70
  path_to_file = os.path.join(base_dir, full_path)
71
+ if os.path.isfile(path_to_file):
72
  return FileResponse(path_to_file)
73
  return FileResponse(os.path.join(base_dir, "index.html"))
74
 
assets/script.js CHANGED
@@ -40,8 +40,18 @@ document.addEventListener('DOMContentLoaded', () => {
40
  });
41
 
42
  if (!response.ok) {
43
- const errData = await response.json();
44
- throw new Error(errData.detail || 'حدث خطأ أثناء الاتصال بالخادم');
 
 
 
 
 
 
 
 
 
 
45
  }
46
 
47
  const data = await response.json();
 
40
  });
41
 
42
  if (!response.ok) {
43
+ const contentType = response.headers.get("content-type");
44
+ if (contentType && contentType.includes("application/json")) {
45
+ const errData = await response.json();
46
+ throw new Error(errData.detail || 'حدث خطأ أثناء الاتصال بالخادم');
47
+ } else {
48
+ const text = await response.text();
49
+ console.error("Non-JSON Server Error:", text);
50
+ if (response.status === 504 || response.status === 503) {
51
+ throw new Error("تأخر الخادم في الاستجابة (جاري تهيئة مساحة HuggingFace). يرجى المحاولة مرة أخرى.");
52
+ }
53
+ throw new Error(`خطأ في الخادم (الكود ${response.status}) - يرجى الانتظار والمحاولة لاحقاً.`);
54
+ }
55
  }
56
 
57
  const data = await response.json();