Chuan0628 commited on
Commit
d01c9df
·
verified ·
1 Parent(s): f3afa7a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -28
app.py CHANGED
@@ -1,57 +1,62 @@
1
- from flask import Flask, request, jsonify
2
  from transformers import AutoTokenizer, AutoModelForCausalLM
3
  import torch
4
  import requests
5
 
 
6
  app = Flask(__name__)
7
 
8
- # 模型名稱
 
 
 
 
9
  model_name = "souljoy/gpt2-small-chinese-cluecorpussmall"
10
  tokenizer = AutoTokenizer.from_pretrained(model_name)
11
  model = AutoModelForCausalLM.from_pretrained(model_name)
12
 
13
- # Telegram 設定
14
- TELEGRAM_TOKEN = "7967078631:AAH9viY8zWZ6mi7krxw1RSz5eycrI9Lce8Q"
15
- TELEGRAM_URL = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
16
-
17
- # 基本對話生成函數
18
- def generate_reply(text):
19
- inputs = tokenizer(text, return_tensors="pt")
20
  outputs = model.generate(
21
  **inputs,
22
  max_new_tokens=40,
23
  do_sample=True,
24
  top_k=50,
25
  top_p=0.95,
26
- temperature=0.8
 
27
  )
28
  reply = tokenizer.decode(outputs[0], skip_special_tokens=True)
29
- return reply
30
 
31
- # 根目錄
32
  @app.route("/", methods=["GET"])
33
  def index():
34
- return "✅ Flask server is running."
35
 
36
- # Telegram webhook 端點
37
  @app.route("/telegram", methods=["POST"])
38
  def telegram_webhook():
39
  data = request.get_json()
40
- if not data:
41
- return jsonify({"error": "no data"}), 400
 
 
 
 
42
 
43
- message = data.get("message", {})
44
- chat_id = message.get("chat", {}).get("id")
45
- text = message.get("text", "")
46
 
47
- if text:
48
- reply = generate_reply(text)
49
- requests.post(TELEGRAM_URL, json={
50
- "chat_id": chat_id,
51
- "text": reply
52
- })
53
 
54
- return jsonify({"ok": True})
 
 
 
55
 
56
- if __name__ == "__main__":
57
- app.run()
 
1
+ from flask import Flask, request, jsonify, Response
2
  from transformers import AutoTokenizer, AutoModelForCausalLM
3
  import torch
4
  import requests
5
 
6
+ # 初始化 Flask
7
  app = Flask(__name__)
8
 
9
+ # Telegram Token 與 API URL
10
+ TELEGRAM_TOKEN = "7967078631:AAH9viY8zWZ6mi7krxw1RSz5eycrI9Lce8Q"
11
+ TELEGRAM_URL = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
12
+
13
+ # 載入中文輕量語言模型
14
  model_name = "souljoy/gpt2-small-chinese-cluecorpussmall"
15
  tokenizer = AutoTokenizer.from_pretrained(model_name)
16
  model = AutoModelForCausalLM.from_pretrained(model_name)
17
 
18
+ # 建立主回應函數
19
+ def generate_reply(prompt):
20
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
 
 
 
 
21
  outputs = model.generate(
22
  **inputs,
23
  max_new_tokens=40,
24
  do_sample=True,
25
  top_k=50,
26
  top_p=0.95,
27
+ temperature=0.8,
28
+ pad_token_id=tokenizer.eos_token_id
29
  )
30
  reply = tokenizer.decode(outputs[0], skip_special_tokens=True)
31
+ return reply.strip()
32
 
33
+ # ✅ Space首頁顯示
34
  @app.route("/", methods=["GET"])
35
  def index():
36
+ return Response("✅ Flask server is running and ready to receive Telegram messages!", mimetype="text/plain")
37
 
38
+ # Telegram webhook endpoint
39
  @app.route("/telegram", methods=["POST"])
40
  def telegram_webhook():
41
  data = request.get_json()
42
+ if not data or "message" not in data:
43
+ return jsonify({"status": "ignored"}), 200
44
+
45
+ message = data["message"]
46
+ chat_id = message["chat"]["id"]
47
+ user_text = message.get("text", "")
48
 
49
+ if not user_text:
50
+ return jsonify({"status": "no text"}), 200
 
51
 
52
+ try:
53
+ reply = generate_reply(user_text)
54
+ except Exception as e:
55
+ reply = "⚠️ 系統錯誤,請稍後再試。"
 
 
56
 
57
+ requests.post(TELEGRAM_URL, json={
58
+ "chat_id": chat_id,
59
+ "text": reply
60
+ })
61
 
62
+ return jsonify({"status": "ok"}), 200