import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
from peft import PeftModel
from threading import Thread
from flask import Flask, render_template_string, request, Response

app = Flask(__name__)

base_path = r"D:\soft\llama\lora\qwen800m"
lora_path = r"D:\soft\llama\lora\train_output\lora_adapter"

tokenizer = AutoTokenizer.from_pretrained(base_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
    base_path,
    dtype=torch.bfloat16,
    trust_remote_code=True,
    low_cpu_mem_usage=True,
    device_map="auto"
)
model = PeftModel.from_pretrained(model, lora_path)
model.eval()

HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>本地微调模型</title>
<style>
body{max-width:900px;margin:20px auto;padding:0 20px;font-family:system-ui}
#chat{border:1px solid #ddd;padding:15px;height:500px;overflow-y:auto;margin-bottom:15px}
.msg{margin:8px 0;padding:10px;border-radius:8px;white-space:pre-wrap}
.user{background:#e7f5ff;text-align:right}
.bot{background:#f7f8fa;text-align:left}
#input_area{display:flex;gap:8px}
#prompt{flex:1;padding:10px;font-size:16px}
button{padding:10px 20px;cursor:pointer}
</style>
</head>
<body>
    <h2>本地Qwen+LoRA聊天</h2>
    <div id="chat"></div>
    <div id="input_area">
        <input id="prompt" placeholder="输入消息...">
        <button onclick="send()">发送</button>
    </div>
<script>
const chatDiv = document.getElementById("chat");
async function send(){
    const text = document.getElementById("prompt").value.trim();
    if(!text) return;
    chatDiv.innerHTML += `<div class="msg user">${text}</div>`;
    document.getElementById("prompt").value = "";
    const botDiv = document.createElement("div");
    botDiv.className = "msg bot";
    chatDiv.appendChild(botDiv);
    const resp = await fetch("/chat", {
        method:"POST",
        body:new URLSearchParams({msg:text})
    });
    const reader = resp.body.getReader();
    const decoder = new TextDecoder();
    let full = "";
    while(true){
        const {done,value} = await reader.read();
        if(done) break;
        full += decoder.decode(value);
        botDiv.innerText = full;
        chatDiv.scrollTop = chatDiv.scrollHeight;
    }
}
</script>
</body>
</html>
"""

@app.get("/")
def index():
    return render_template_string(HTML_TEMPLATE)

@app.post("/chat")
def chat():
    msg = request.form.get("msg")
    messages = [{"role":"user", "content": msg}]
    prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    inputs = tokenizer(prompt, return_tensors="pt")
    inputs = inputs.to("cuda")

    streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
    gen_kwargs = dict(
        **inputs,
        streamer=streamer,
        max_new_tokens=256,
        temperature=0.6,
        top_p=0.9,
        do_sample=True,
        pad_token_id=tokenizer.eos_token_id
    )
    t = Thread(target=model.generate, kwargs=gen_kwargs)
    t.start()

    def stream():
        for chunk in streamer:
            yield chunk.encode("utf-8")
    return Response(stream(), mimetype="text/plain")

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=3031, debug=False)