Reza1880044 commited on
Commit
0c8d779
·
verified ·
1 Parent(s): 223efa7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -36
app.py CHANGED
@@ -4,6 +4,7 @@ T = __import__("to" + "rch")
4
  TF = __import__("trans" + "formers")
5
  from fastapi import FastAPI, Request
6
  import uvicorn
 
7
 
8
  SECRET = "yara-man-reza-am"
9
  MODEL_NAME = "Qwen/Qwen2.5-Coder-7B-Instruct"
@@ -20,31 +21,43 @@ def load_memory():
20
  MEMORY = load_memory()
21
 
22
  @spaces.GPU
 
 
 
23
  def make_reply(message, history):
24
  global MODEL, TOKENIZER
25
- if MODEL is None:
26
- print("Yara dare maghz ro miarad...")
27
- TOKENIZER = TF.AutoTokenizer.from_pretrained(MODEL_NAME)
28
- MODEL = TF.AutoModelForCausalLM.from_pretrained(MODEL_NAME, dtype=T.float16, device_map="auto", trust_remote_code=True)
29
- print("Maghz amade shod, rafiq!")
30
- messages = [{"role": "system", "content": "You are Yara, coder brain of Reza. Your boss is Reza, your assistant name is rafiq. " + MEMORY}]
31
- for h in history:
32
- if isinstance(h, dict):
33
- messages.append(h)
34
- else:
35
- messages.append({"role": "user", "content": h[0]})
36
- messages.append({"role": "assistant", "content": h[1]})
37
- messages.append({"role": "user", "content": message})
38
- text = TOKENIZER.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
39
- inputs = TOKENIZER([text], return_tensors="pt").to(MODEL.device)
40
- with T.no_grad():
41
- out = MODEL.generate(**inputs, max_new_tokens=512, temperature=0.7, do_sample=True)
42
- reply = TOKENIZER.decode(out[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
43
- return reply
 
 
 
 
 
44
 
45
  def chat(message, password, history):
46
  if password != SECRET:
47
  return history + [{"role": "user", "content": message}, {"role": "assistant", "content": "Password eshtebah ast, rafiq."}], ""
 
 
 
 
48
  reply = make_reply(message, history)
49
  history = history + [{"role": "user", "content": message}, {"role": "assistant", "content": reply}]
50
  return history, ""
@@ -66,23 +79,28 @@ async def list_models():
66
 
67
  @app.post("/v1/chat/completions")
68
  async def v1_chat(req: Request):
69
- j = await req.json()
70
- msgs = j.get("messages", [])
71
- last = ""
72
- hist = []
73
- for m in msgs:
74
- role = m.get("role", "")
75
- content = m.get("content", "")
76
- if isinstance(content, list):
77
- content = " ".join([str(x.get("text", "")) for x in content if isinstance(x, dict)])
78
- if role == "user":
79
- last = str(content)
80
- if role in ("user", "assistant") and str(content):
81
- hist.append({"role": role, "content": str(content)})
82
- if hist and hist[-1].get("role") == "user":
83
- hist = hist[:-1]
84
- reply = make_reply(last, hist)
85
- return {"id": "chatcmpl-yara", "object": "chat.completion", "choices": [{"index": 0, "message": {"role": "assistant", "content": reply}, "finish_reason": "stop"}]}
 
 
 
 
 
86
 
87
  app = gr.mount_gradio_app(app, demo, path="/ui")
88
 
 
4
  TF = __import__("trans" + "formers")
5
  from fastapi import FastAPI, Request
6
  import uvicorn
7
+ import traceback
8
 
9
  SECRET = "yara-man-reza-am"
10
  MODEL_NAME = "Qwen/Qwen2.5-Coder-7B-Instruct"
 
21
  MEMORY = load_memory()
22
 
23
  @spaces.GPU
24
+ def gpu_keepalive():
25
+ return "ok"
26
+
27
  def make_reply(message, history):
28
  global MODEL, TOKENIZER
29
+ try:
30
+ if MODEL is None:
31
+ print("Yara dare maghz ro miarad...")
32
+ TOKENIZER = TF.AutoTokenizer.from_pretrained(MODEL_NAME)
33
+ MODEL = TF.AutoModelForCausalLM.from_pretrained(MODEL_NAME, dtype=T.float16, device_map="auto", trust_remote_code=True)
34
+ print("Maghz amade shod, rafiq!")
35
+ messages = [{"role": "system", "content": "You are Yara, coder brain of Reza. Your boss is Reza, your assistant name is rafiq. " + MEMORY}]
36
+ for h in history:
37
+ if isinstance(h, dict):
38
+ messages.append(h)
39
+ else:
40
+ messages.append({"role": "user", "content": h[0]})
41
+ messages.append({"role": "assistant", "content": h[1]})
42
+ messages.append({"role": "user", "content": message})
43
+ text = TOKENIZER.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
44
+ inputs = TOKENIZER([text], return_tensors="pt").to(MODEL.device)
45
+ with T.no_grad():
46
+ out = MODEL.generate(**inputs, max_new_tokens=512, temperature=0.7, do_sample=True)
47
+ reply = TOKENIZER.decode(out[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
48
+ return reply
49
+ except Exception as e:
50
+ print("MAKE_REPLY ERROR: " + str(e))
51
+ traceback.print_exc()
52
+ return "ERROR in brain: " + str(e)
53
 
54
  def chat(message, password, history):
55
  if password != SECRET:
56
  return history + [{"role": "user", "content": message}, {"role": "assistant", "content": "Password eshtebah ast, rafiq."}], ""
57
+ try:
58
+ gpu_keepalive()
59
+ except:
60
+ pass
61
  reply = make_reply(message, history)
62
  history = history + [{"role": "user", "content": message}, {"role": "assistant", "content": reply}]
63
  return history, ""
 
79
 
80
  @app.post("/v1/chat/completions")
81
  async def v1_chat(req: Request):
82
+ try:
83
+ j = await req.json()
84
+ msgs = j.get("messages", [])
85
+ last = ""
86
+ hist = []
87
+ for m in msgs:
88
+ role = m.get("role", "")
89
+ content = m.get("content", "")
90
+ if isinstance(content, list):
91
+ content = " ".join([str(x.get("text", "")) for x in content if isinstance(x, dict)])
92
+ if role == "user":
93
+ last = str(content)
94
+ if role in ("user", "assistant") and str(content):
95
+ hist.append({"role": role, "content": str(content)})
96
+ if hist and hist[-1].get("role") == "user":
97
+ hist = hist[:-1]
98
+ reply = make_reply(last, hist)
99
+ return {"id": "chatcmpl-yara", "object": "chat.completion", "choices": [{"index": 0, "message": {"role": "assistant", "content": reply}, "finish_reason": "stop"}]}
100
+ except Exception as e:
101
+ print("V1 ERROR: " + str(e))
102
+ traceback.print_exc()
103
+ return {"id": "chatcmpl-yara", "object": "chat.completion", "choices": [{"index": 0, "message": {"role": "assistant", "content": "ERROR in brain: " + str(e)}, "finish_reason": "stop"}]}
104
 
105
  app = gr.mount_gradio_app(app, demo, path="/ui")
106