cloudunity commited on
Commit
f385d09
·
verified ·
1 Parent(s): 88ffff7

Update server.py

Browse files
Files changed (1) hide show
  1. server.py +14 -4
server.py CHANGED
@@ -33,7 +33,7 @@ MODEL_ID = "gemma-4-e2b"
33
  model_status = "loading"
34
  engine = None
35
  _engine_ctx = None
36
- engine_lock = threading.Lock()
37
 
38
  app = Flask(__name__)
39
  CORS(app)
@@ -108,8 +108,11 @@ def parse_openai_messages(messages: list) -> tuple[str, bytes | None]:
108
  def _run_real_model_generator(ask: str, image_bytes: bytes | None):
109
  """Yields text chunks as they are generated by the model."""
110
  import litert_lm
111
- # engine_lock ensures only 1 request processes at a time to prevent RAM crashes
112
- with engine_lock:
 
 
 
113
  with engine.create_conversation() as conv:
114
  if image_bytes:
115
  msg = litert_lm.Contents.of(
@@ -125,6 +128,8 @@ def _run_real_model_generator(ask: str, image_bytes: bytes | None):
125
  text = part.get("text", "")
126
  if text:
127
  yield text
 
 
128
 
129
 
130
  def _run_mock_generator(ask: str, has_image: bool):
@@ -236,4 +241,9 @@ if __name__ == "__main__":
236
  port = int(os.environ.get("PORT", 5173))
237
  threading.Thread(target=load_model, daemon=True).start()
238
  print(f"[INFO] Gemma OpenAI-Compatible API listening on :{port}", flush=True)
239
- app.run(host="0.0.0.0", port=port, debug=False)
 
 
 
 
 
 
33
  model_status = "loading"
34
  engine = None
35
  _engine_ctx = None
36
+ engine_lock = threading.BoundedSemaphore(value=2)
37
 
38
  app = Flask(__name__)
39
  CORS(app)
 
108
  def _run_real_model_generator(ask: str, image_bytes: bytes | None):
109
  """Yields text chunks as they are generated by the model."""
110
  import litert_lm
111
+ # engine_lock ensures only 2 requests process at a time to prevent RAM crashes
112
+ if not engine_lock.acquire(timeout=30):
113
+ raise RuntimeError("Server busy. Try again shortly.")
114
+
115
+ try:
116
  with engine.create_conversation() as conv:
117
  if image_bytes:
118
  msg = litert_lm.Contents.of(
 
128
  text = part.get("text", "")
129
  if text:
130
  yield text
131
+ finally:
132
+ engine_lock.release()
133
 
134
 
135
  def _run_mock_generator(ask: str, has_image: bool):
 
241
  port = int(os.environ.get("PORT", 5173))
242
  threading.Thread(target=load_model, daemon=True).start()
243
  print(f"[INFO] Gemma OpenAI-Compatible API listening on :{port}", flush=True)
244
+ app.run(
245
+ host="0.0.0.0",
246
+ port=port,
247
+ debug=False,
248
+ threaded=True,
249
+ )