reikernx commited on
Commit
7023b3d
·
verified ·
1 Parent(s): 8af3808

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -0
app.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM
3
+ import torch
4
+ import os
5
+ import json
6
+
7
+ app = Flask(__name__)
8
+
9
+ HISTORY_FILE = "history.json"
10
+ MAX_HISTORY = 10 # Keep only the last 10 lines per user
11
+
12
+ # Load history from file (or create empty)
13
+ if os.path.exists(HISTORY_FILE):
14
+ with open(HISTORY_FILE, "r", encoding="utf-8") as f:
15
+ user_histories = json.load(f)
16
+ else:
17
+ user_histories = {}
18
+
19
+ # Choose a Transformers-compatible DeepSeek Distill model
20
+ MODEL_NAME = "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B" # change to bigger model if GPU allows
21
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
22
+ model = AutoModelForCausalLM.from_pretrained(
23
+ MODEL_NAME,
24
+ torch_dtype=torch.float16,
25
+ device_map="auto"
26
+ )
27
+
28
+ def save_history():
29
+ """Save all histories to a JSON file."""
30
+ with open(HISTORY_FILE, "w", encoding="utf-8") as f:
31
+ json.dump(user_histories, f, ensure_ascii=False, indent=2)
32
+
33
+ @app.route("/message", methods=["GET"])
34
+ def handle_message():
35
+ user_message = request.args.get("message")
36
+ user_id = request.args.get("userid")
37
+
38
+ if not user_message or not user_id:
39
+ return jsonify({"error": "Both 'message' and 'userid' are required"}), 400
40
+
41
+ # Retrieve or initialize history
42
+ history = user_histories.get(user_id, [])
43
+
44
+
45
+ history.append(f"User: {user_message}")
46
+
47
+
48
+ history = history[-MAX_HISTORY:]
49
+
50
+
51
+ conversation_text = "\n".join(history) + "\nAI:"
52
+
53
+
54
+ inputs = tokenizer(conversation_text, return_tensors="pt").to(model.device)
55
+ outputs = model.generate(
56
+ **inputs,
57
+ max_new_tokens=256,
58
+ temperature=0.6,
59
+ do_sample=True
60
+ )
61
+
62
+ reply = tokenizer.decode(outputs[0], skip_special_tokens=True)
63
+
64
+
65
+ if "AI:" in reply:
66
+ reply_text = reply.split("AI:")[-1].strip()
67
+ else:
68
+ reply_text = reply.strip()
69
+
70
+
71
+ history.append(f"AI: {reply_text}")
72
+ user_histories[user_id] = history
73
+
74
+
75
+ save_history()
76
+
77
+ return jsonify({"response": reply_text})
78
+
79
+ if __name__ == "__main__":
80
+ app.run(host="0.0.0.0", port=5000, debug=True)