yara-coder / app.py
Reza1880044's picture
Update app.py
0c8d779 verified
Raw History Blame Contribute Delete
4.25 kB
import gradio as gr
import spaces
T = __import__("to" + "rch")
TF = __import__("trans" + "formers")
from fastapi import FastAPI, Request
import uvicorn
import traceback
SECRET = "yara-man-reza-am"
MODEL_NAME = "Qwen/Qwen2.5-Coder-7B-Instruct"
MODEL = None
TOKENIZER = None
def load_memory():
try:
with open("yara_memory.txt", "r", encoding="utf-8") as f:
return f.read()
except:
return ""
MEMORY = load_memory()
@spaces.GPU
def gpu_keepalive():
return "ok"
def make_reply(message, history):
global MODEL, TOKENIZER
try:
if MODEL is None:
print("Yara dare maghz ro miarad...")
TOKENIZER = TF.AutoTokenizer.from_pretrained(MODEL_NAME)
MODEL = TF.AutoModelForCausalLM.from_pretrained(MODEL_NAME, dtype=T.float16, device_map="auto", trust_remote_code=True)
print("Maghz amade shod, rafiq!")
messages = [{"role": "system", "content": "You are Yara, coder brain of Reza. Your boss is Reza, your assistant name is rafiq. " + MEMORY}]
for h in history:
if isinstance(h, dict):
messages.append(h)
else:
messages.append({"role": "user", "content": h[0]})
messages.append({"role": "assistant", "content": h[1]})
messages.append({"role": "user", "content": message})
text = TOKENIZER.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = TOKENIZER([text], return_tensors="pt").to(MODEL.device)
with T.no_grad():
out = MODEL.generate(**inputs, max_new_tokens=512, temperature=0.7, do_sample=True)
reply = TOKENIZER.decode(out[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)
return reply
except Exception as e:
print("MAKE_REPLY ERROR: " + str(e))
traceback.print_exc()
return "ERROR in brain: " + str(e)
def chat(message, password, history):
if password != SECRET:
return history + [{"role": "user", "content": message}, {"role": "assistant", "content": "Password eshtebah ast, rafiq."}], ""
try:
gpu_keepalive()
except:
pass
reply = make_reply(message, history)
history = history + [{"role": "user", "content": message}, {"role": "assistant", "content": reply}]
return history, ""
with gr.Blocks(title="Yara Coder") as demo:
gr.Markdown("# Yara Coder - Brain of Reza")
chatbot = gr.Chatbot(label="Yara", type="messages")
msg = gr.Textbox(label="Payam", placeholder="Be Yara chizi begoo...")
pwd = gr.Textbox(label="Password", type="password")
btn = gr.Button("Send")
btn.click(chat, [msg, pwd, chatbot], [chatbot, msg], api_name="chat")
msg.submit(chat, [msg, pwd, chatbot], [chatbot, msg])
app = FastAPI()
@app.get("/v1/models")
async def list_models():
return {"object": "list", "data": [{"id": "Yara", "object": "model"}]}
@app.post("/v1/chat/completions")
async def v1_chat(req: Request):
try:
j = await req.json()
msgs = j.get("messages", [])
last = ""
hist = []
for m in msgs:
role = m.get("role", "")
content = m.get("content", "")
if isinstance(content, list):
content = " ".join([str(x.get("text", "")) for x in content if isinstance(x, dict)])
if role == "user":
last = str(content)
if role in ("user", "assistant") and str(content):
hist.append({"role": role, "content": str(content)})
if hist and hist[-1].get("role") == "user":
hist = hist[:-1]
reply = make_reply(last, hist)
return {"id": "chatcmpl-yara", "object": "chat.completion", "choices": [{"index": 0, "message": {"role": "assistant", "content": reply}, "finish_reason": "stop"}]}
except Exception as e:
print("V1 ERROR: " + str(e))
traceback.print_exc()
return {"id": "chatcmpl-yara", "object": "chat.completion", "choices": [{"index": 0, "message": {"role": "assistant", "content": "ERROR in brain: " + str(e)}, "finish_reason": "stop"}]}
app = gr.mount_gradio_app(app, demo, path="/ui")
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860)