gijl commited on
Commit
2c2df71
·
verified ·
1 Parent(s): 52ca90a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -10
app.py CHANGED
@@ -2,9 +2,10 @@ import os
2
  import subprocess
3
  import time
4
  import requests
 
5
  from huggingface_hub import hf_hub_download
6
  from fastapi import FastAPI, Request
7
- from fastapi.responses import StreamingResponse
8
  import uvicorn
9
 
10
  APP_DIR = "/app"
@@ -15,6 +16,9 @@ LLAMA_PORT = 8080
15
 
16
  os.makedirs(MODEL_DIR, exist_ok=True)
17
 
 
 
 
18
 
19
  def build_llama_cpp():
20
  """بناء llama.cpp من المصدر إن لم يكن الملف التنفيذي موجودًا مسبقًا."""
@@ -90,22 +94,41 @@ def wait_for_server(timeout_seconds: int = 180):
90
  print("[run] تحذير: انتهت مهلة الانتظار، سيتم المتابعة رغم ذلك.")
91
 
92
 
93
- # ---------------------------------------------------------------------------
94
- # التنفيذ عند بدء التطبيق
95
- # ---------------------------------------------------------------------------
96
- build_llama_cpp()
97
- model_path, mmproj_path = download_model()
98
- llama_process = start_llama_server(model_path, mmproj_path)
99
- wait_for_server()
 
 
 
 
 
 
100
 
101
  # ---------------------------------------------------------------------------
102
- # Reverse proxy: أي طلب يصل إلى منفذ المساحة يُمرَّر مباشرة إلى واجهة llama.cpp
103
  # ---------------------------------------------------------------------------
104
  app = FastAPI()
105
 
 
 
 
 
 
 
106
 
107
  @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
108
  async def proxy(path: str, request: Request):
 
 
 
 
 
 
 
109
  url = f"http://127.0.0.1:{LLAMA_PORT}/{path}"
110
  body = await request.body()
111
  forward_headers = {
@@ -133,4 +156,4 @@ async def proxy(path: str, request: Request):
133
 
134
  if __name__ == "__main__":
135
  port = int(os.environ.get("PORT", 7860))
136
- uvicorn.run(app, host="0.0.0.0", port=port)
 
2
  import subprocess
3
  import time
4
  import requests
5
+ import threading
6
  from huggingface_hub import hf_hub_download
7
  from fastapi import FastAPI, Request
8
+ from fastapi.responses import StreamingResponse, JSONResponse
9
  import uvicorn
10
 
11
  APP_DIR = "/app"
 
16
 
17
  os.makedirs(MODEL_DIR, exist_ok=True)
18
 
19
+ # متغير عام لتتبع حالة الخادم الداخلي
20
+ backend_ready = False
21
+
22
 
23
  def build_llama_cpp():
24
  """بناء llama.cpp من المصدر إن لم يكن الملف التنفيذي موجودًا مسبقًا."""
 
94
  print("[run] تحذير: انتهت مهلة الانتظار، سيتم المتابعة رغم ذلك.")
95
 
96
 
97
+ def setup_backend():
98
+ """هذه الدالة تقوم بتجميع وتنزيل وتشغيل النموذج، وستعمل في الخلفية."""
99
+ global backend_ready
100
+ try:
101
+ build_llama_cpp()
102
+ model_path, mmproj_path = download_model()
103
+ start_llama_server(model_path, mmproj_path)
104
+ wait_for_server()
105
+ backend_ready = True
106
+ print("[setup] اكتمل إعداد النموذج وهو جاهز الآن لاستقبال الطلبات.")
107
+ except Exception as e:
108
+ print(f"[setup] حدث خطأ أثناء إعداد النموذج: {e}")
109
+
110
 
111
  # ---------------------------------------------------------------------------
112
+ # إعداد الواجهة (تطبيق FastAPI)
113
  # ---------------------------------------------------------------------------
114
  app = FastAPI()
115
 
116
+ @app.on_event("startup")
117
+ def startup_event():
118
+ # تشغيل عملية التنزيل والبناء في مسار منفصل (Thread)
119
+ # هذا يضمن أن يعمل تطبيق FastAPI فوراً دون انتظار التنزيل
120
+ thread = threading.Thread(target=setup_backend)
121
+ thread.start()
122
 
123
  @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
124
  async def proxy(path: str, request: Request):
125
+ # إذا لم يكتمل تنزيل النموذج بعد، يتم إرجاع رسالة توضيحية بدلاً من خطأ اتصال
126
+ if not backend_ready:
127
+ return JSONResponse(
128
+ status_code=503,
129
+ content={"error": "النموذج لا يزال قيد التنزيل والإعداد في الخلفية. يرجى المحاولة بعد قليل."}
130
+ )
131
+
132
  url = f"http://127.0.0.1:{LLAMA_PORT}/{path}"
133
  body = await request.body()
134
  forward_headers = {
 
156
 
157
  if __name__ == "__main__":
158
  port = int(os.environ.get("PORT", 7860))
159
+ uvicorn.run(app, host="0.0.0.0", port=port)