Rid3 commited on
Commit
206ca90
·
verified ·
1 Parent(s): 4bb16fc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +5 -24
app.py CHANGED
@@ -8,7 +8,6 @@ from huggingface_hub import hf_hub_download
8
 
9
  app = FastAPI()
10
 
11
- # Разрешаем все подключения
12
  app.add_middleware(
13
  CORSMiddleware,
14
  allow_origins=["*"],
@@ -17,7 +16,6 @@ app.add_middleware(
17
  allow_headers=["*"],
18
  )
19
 
20
- # Глобальная переменная для модели
21
  model = None
22
  current_id = ""
23
 
@@ -29,39 +27,33 @@ class ChatRequest(BaseModel):
29
  max_tokens: int = 512
30
  temperature: float = 0.7
31
 
 
32
  @app.get("/")
33
  async def health():
34
- return {"status": "online", "info": "Server is running. Send POST to /chat"}
35
 
36
  @app.post("/chat")
37
  async def chat(request: ChatRequest):
38
  global model, current_id
39
-
40
  new_id = f"{request.repo_id}/{request.filename}"
41
 
42
  try:
43
- # 1. Загружаем модель, если она еще не в памяти
44
  if model is None or current_id != new_id:
45
- print(f"--- Loading model: {new_id} ---")
46
  if model is not None:
47
  del model
48
  gc.collect()
49
 
50
- # Скачивание файла (использует кэш HF)
51
  path = hf_hub_download(repo_id=request.repo_id, filename=request.filename)
52
-
53
  model = Llama(
54
  model_path=path,
55
- n_ctx=2048, # Оптимально для 16ГБ RAM
56
  n_threads=os.cpu_count() or 4,
57
- n_gpu_layers=0, # Только CPU
58
  verbose=False
59
  )
60
  current_id = new_id
61
 
62
- # 2. Форматируем промпт и генерируем ответ
63
  full_prompt = f"System: {request.system_prompt}\nUser: {request.prompt}\nAssistant:"
64
-
65
  output = model.create_completion(
66
  prompt=full_prompt,
67
  max_tokens=request.max_tokens,
@@ -73,21 +65,10 @@ async def chat(request: ChatRequest):
73
  "response": output["choices"][0]["text"].strip(),
74
  "model": current_id
75
  }
76
-
77
  except Exception as e:
78
- print(f"Error: {e}")
79
  raise HTTPException(status_code=500, detail=str(e))
80
 
81
  if __name__ == "__main__":
82
  import uvicorn
83
-
84
- # Автоматический вывод ссылки для подключения
85
- space_id = os.getenv("SPACE_ID")
86
- if space_id:
87
- # Прямая ссылка на API для внешних программ
88
- host_link = f"https://{space_id.replace('/', '-').lower()}.hf.space/chat"
89
- print("\n" + "="*50)
90
- print(f"URL ДЛЯ ПОДКЛЮЧЕНИЯ:\n{host_link}")
91
- print("="*50 + "\n")
92
-
93
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
8
 
9
  app = FastAPI()
10
 
 
11
  app.add_middleware(
12
  CORSMiddleware,
13
  allow_origins=["*"],
 
16
  allow_headers=["*"],
17
  )
18
 
 
19
  model = None
20
  current_id = ""
21
 
 
27
  max_tokens: int = 512
28
  temperature: float = 0.7
29
 
30
+ # Это главная страница. Если ты перейдешь по ссылке в браузере, ты должен увидеть это:
31
  @app.get("/")
32
  async def health():
33
+ return {"status": "online", "message": "API is running. Use POST /chat to interact."}
34
 
35
  @app.post("/chat")
36
  async def chat(request: ChatRequest):
37
  global model, current_id
 
38
  new_id = f"{request.repo_id}/{request.filename}"
39
 
40
  try:
 
41
  if model is None or current_id != new_id:
 
42
  if model is not None:
43
  del model
44
  gc.collect()
45
 
 
46
  path = hf_hub_download(repo_id=request.repo_id, filename=request.filename)
 
47
  model = Llama(
48
  model_path=path,
49
+ n_ctx=2048,
50
  n_threads=os.cpu_count() or 4,
51
+ n_gpu_layers=0,
52
  verbose=False
53
  )
54
  current_id = new_id
55
 
 
56
  full_prompt = f"System: {request.system_prompt}\nUser: {request.prompt}\nAssistant:"
 
57
  output = model.create_completion(
58
  prompt=full_prompt,
59
  max_tokens=request.max_tokens,
 
65
  "response": output["choices"][0]["text"].strip(),
66
  "model": current_id
67
  }
 
68
  except Exception as e:
 
69
  raise HTTPException(status_code=500, detail=str(e))
70
 
71
  if __name__ == "__main__":
72
  import uvicorn
73
+ # Hugging Face всегда использует порт 7860
 
 
 
 
 
 
 
 
 
74
  uvicorn.run(app, host="0.0.0.0", port=7860)