tudeplom commited on
Commit
d36cdf1
·
verified ·
1 Parent(s): 13c61e3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -57
app.py CHANGED
@@ -1,76 +1,48 @@
1
- from flask import Flask, request, jsonify
2
  import requests
3
  import os
4
- import logging
5
  from flask_cors import CORS
6
 
7
- # Cấu hình logging để debug
8
- logging.basicConfig(level=logging.INFO)
9
 
10
  app = Flask(__name__)
11
  CORS(app)
12
 
13
- # Model TinyLlama trên Hugging Face
14
- HF_MODEL = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
15
  HF_API_URL = f"https://api-inference.huggingface.co/models/{HF_MODEL}"
16
 
17
- # Lấy API Key từ biến môi trường
18
  HF_API_KEY = os.getenv("HF_API_KEY")
19
 
20
- if not HF_API_KEY:
21
- logging.error("Lỗi: API Key không tồn tại. Hãy thêm vào Hugging Face Secrets.")
22
 
23
- # Hàm gửi request đến API Hugging Face
24
- def chat_with_tinyllama(prompt):
 
25
  if not HF_API_KEY:
26
- return "Lỗi: API Key không tồn tại."
27
-
28
- logging.info(f"Gửi request đến API: {HF_API_URL}")
29
- logging.info(f"Nội dung gửi: {prompt}")
30
-
31
- headers = {"Authorization": f"Bearer {HF_API_KEY}"}
32
- payload = {"inputs": prompt, "parameters": {"max_new_tokens": 150}}
33
-
34
- try:
35
- response = requests.post(HF_API_URL, headers=headers, json=payload, timeout=60)
36
- logging.info(f"Trạng thái API: {response.status_code}")
37
-
38
- if response.status_code == 200:
39
- result = response.json()
40
- # Kiểm tra định dạng JSON trả về
41
- if isinstance(result, list) and "generated_text" in result[0]:
42
- return result[0]["generated_text"]
43
- elif isinstance(result, dict) and "generated_text" in result:
44
- return result["generated_text"]
45
- else:
46
- return "Lỗi: Định dạng phản hồi không hợp lệ."
47
- elif response.status_code == 503:
48
- return "Mô hình đang quá tải, vui lòng thử lại sau."
49
- else:
50
- return f"Lỗi API: {response.status_code} - {response.text}"
51
-
52
- except requests.exceptions.Timeout:
53
- return "Lỗi: API phản hồi quá lâu. Hãy thử lại sau."
54
- except requests.exceptions.RequestException as e:
55
- return f"Lỗi mạng: {str(e)}"
56
-
57
- # Route API kiểm tra server
58
- @app.route('/')
59
- def index():
60
- return jsonify({'message': 'TinyLlama API is running!'})
61
 
62
- # Route API chat
63
- @app.route('/chat', methods=['POST'])
64
- def chat():
65
- data = request.json
66
- user_message = data.get("message", "").strip()
67
 
68
- if not user_message:
69
- return jsonify({'FROM': 'TinyLlama', 'MESSAGE': 'Lỗi: Tin nhắn không hợp lệ.'})
70
 
71
- bot_reply = chat_with_tinyllama(user_message)
72
- return jsonify({'FROM': 'TinyLlama', 'MESSAGE': bot_reply})
73
 
74
- # Chạy Flask server
 
 
 
 
 
 
 
75
  if __name__ == '__main__':
76
- app.run(host="0.0.0.0", port=7860, debug=True)
 
1
+ from flask import Flask, render_template, request, jsonify
2
  import requests
3
  import os
4
+
5
  from flask_cors import CORS
6
 
7
+
8
+
9
 
10
  app = Flask(__name__)
11
  CORS(app)
12
 
13
+ HF_MODEL = "google/gemma-2b"
 
14
  HF_API_URL = f"https://api-inference.huggingface.co/models/{HF_MODEL}"
15
 
16
+ # Lấy API Key từ Hugging Face Secrets
17
  HF_API_KEY = os.getenv("HF_API_KEY")
18
 
 
 
19
 
20
+
21
+ # Gửi request API để chat
22
+ def chat_with_gemma(prompt):
23
  if not HF_API_KEY:
24
+ return "Lỗi: API Key không tồn tại. Hãy thêm vào Hugging Face Secrets."
25
+
26
+ response = requests.post(
27
+ HF_API_URL,
28
+ headers={"Authorization": f"Bearer {HF_API_KEY}"},
29
+ json={"inputs": prompt}
30
+ )
31
+
32
+ if response.status_code == 200:
33
+ return response.json()[0].get('generated_text', "Không phản hồi.")
34
+ return f"Lỗi: {response.status_code} - {response.text}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
 
 
 
 
 
36
 
 
 
37
 
 
 
38
 
39
+
40
+
41
+
42
+
43
+ @app.route('/')
44
+ def index():
45
+ return jsonify({'FROM': 'Gemma-2B', 'MESSAGE': bot_reply})
46
+
47
  if __name__ == '__main__':
48
+ app.run(host="0.0.0.0", port=7860)