Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import requests
|
| 3 |
import json
|
| 4 |
from flask import Flask, render_template, request, Response
|
| 5 |
import logging
|
| 6 |
|
| 7 |
-
# ==================
|
| 8 |
class PersianLogFormatter(logging.Formatter):
|
| 9 |
LEVEL_MAP = {
|
| 10 |
logging.DEBUG: "دیباگ",
|
|
@@ -21,11 +23,14 @@ def setup_logging():
|
|
| 21 |
log_format = '[%(asctime)s] [%(levelname)s]: %(message)s'
|
| 22 |
date_format = '%Y-%m-%d %H:%M:%S'
|
| 23 |
formatter = PersianLogFormatter(log_format, datefmt=date_format)
|
|
|
|
| 24 |
root_logger = logging.getLogger()
|
| 25 |
if root_logger.hasHandlers():
|
| 26 |
root_logger.handlers.clear()
|
|
|
|
| 27 |
console_handler = logging.StreamHandler()
|
| 28 |
console_handler.setFormatter(formatter)
|
|
|
|
| 29 |
root_logger.addHandler(console_handler)
|
| 30 |
root_logger.setLevel(logging.INFO)
|
| 31 |
|
|
@@ -33,26 +38,27 @@ setup_logging()
|
|
| 33 |
|
| 34 |
app = Flask(__name__)
|
| 35 |
|
| 36 |
-
#
|
| 37 |
HF_API_URL = "https://umint-ai.hf.space/api/chat"
|
| 38 |
|
| 39 |
@app.route('/')
|
| 40 |
def index():
|
| 41 |
-
"""
|
| 42 |
return render_template('index.html')
|
| 43 |
|
| 44 |
@app.route('/chat', methods=['POST'])
|
| 45 |
def chat():
|
| 46 |
"""
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
"""
|
| 51 |
data = request.json
|
| 52 |
if not data:
|
| 53 |
logging.error("درخواست نامعتبر: JSON وجود ندارد.")
|
| 54 |
return Response(json.dumps({"error": "Invalid request"}), status=400, mimetype='application/json')
|
| 55 |
|
|
|
|
| 56 |
payload = {
|
| 57 |
"messages": data.get("messages", []),
|
| 58 |
"id": data.get("id", "chat_unknown"),
|
|
@@ -63,12 +69,13 @@ def chat():
|
|
| 63 |
|
| 64 |
def stream_response():
|
| 65 |
try:
|
|
|
|
| 66 |
with requests.post(HF_API_URL, json=payload, stream=True, timeout=720) as response:
|
| 67 |
response.raise_for_status()
|
| 68 |
|
| 69 |
logging.info(f"اتصال موفقیتآمیز با HF Space برای چت {payload.get('id')}. در حال استریم پاسخ...")
|
| 70 |
|
| 71 |
-
#
|
| 72 |
for chunk in response.iter_content(chunk_size=1024):
|
| 73 |
yield chunk
|
| 74 |
|
|
@@ -81,10 +88,13 @@ def chat():
|
|
| 81 |
"type": "error",
|
| 82 |
"message": "متاسفانه در ارتباط با سرور اصلی خطایی رخ داد. لطفا دوباره تلاش کنید."
|
| 83 |
}
|
|
|
|
| 84 |
yield f"data: {json.dumps(error_payload)}\n\n"
|
| 85 |
|
| 86 |
return Response(stream_response(), mimetype='text/event-stream')
|
| 87 |
|
| 88 |
if __name__ == '__main__':
|
| 89 |
-
#
|
| 90 |
-
app.run(debug=True, host='0.0.0.0', port=os.environ.get("PORT", 7860))
|
|
|
|
|
|
|
|
|
| 1 |
+
# --- START OF FILE app.py ---
|
| 2 |
+
|
| 3 |
import os
|
| 4 |
import requests
|
| 5 |
import json
|
| 6 |
from flask import Flask, render_template, request, Response
|
| 7 |
import logging
|
| 8 |
|
| 9 |
+
# ================== بخش تنظیمات لاگنویسی (فارسی) ==================
|
| 10 |
class PersianLogFormatter(logging.Formatter):
|
| 11 |
LEVEL_MAP = {
|
| 12 |
logging.DEBUG: "دیباگ",
|
|
|
|
| 23 |
log_format = '[%(asctime)s] [%(levelname)s]: %(message)s'
|
| 24 |
date_format = '%Y-%m-%d %H:%M:%S'
|
| 25 |
formatter = PersianLogFormatter(log_format, datefmt=date_format)
|
| 26 |
+
|
| 27 |
root_logger = logging.getLogger()
|
| 28 |
if root_logger.hasHandlers():
|
| 29 |
root_logger.handlers.clear()
|
| 30 |
+
|
| 31 |
console_handler = logging.StreamHandler()
|
| 32 |
console_handler.setFormatter(formatter)
|
| 33 |
+
|
| 34 |
root_logger.addHandler(console_handler)
|
| 35 |
root_logger.setLevel(logging.INFO)
|
| 36 |
|
|
|
|
| 38 |
|
| 39 |
app = Flask(__name__)
|
| 40 |
|
| 41 |
+
# آدرس API اسپیس Hugging Face که به عنوان بکاند عمل میکند
|
| 42 |
HF_API_URL = "https://umint-ai.hf.space/api/chat"
|
| 43 |
|
| 44 |
@app.route('/')
|
| 45 |
def index():
|
| 46 |
+
"""فایل اصلی HTML را نمایش میدهد."""
|
| 47 |
return render_template('index.html')
|
| 48 |
|
| 49 |
@app.route('/chat', methods=['POST'])
|
| 50 |
def chat():
|
| 51 |
"""
|
| 52 |
+
این اندپوینت به عنوان یک پراکسی امن به اسپیس Hugging Face عمل میکند.
|
| 53 |
+
درخواست چت را از فرانتاند دریافت کرده، آن را به اسپیس HF ارسال میکند،
|
| 54 |
+
و پاسخ را بدون تغییر در فرمت SSE به کلاینت بازمیگرداند.
|
| 55 |
"""
|
| 56 |
data = request.json
|
| 57 |
if not data:
|
| 58 |
logging.error("درخواست نامعتبر: JSON وجود ندارد.")
|
| 59 |
return Response(json.dumps({"error": "Invalid request"}), status=400, mimetype='application/json')
|
| 60 |
|
| 61 |
+
# ساختار پیام را مطابق با نیاز اسپیس مقصد آماده میکنیم
|
| 62 |
payload = {
|
| 63 |
"messages": data.get("messages", []),
|
| 64 |
"id": data.get("id", "chat_unknown"),
|
|
|
|
| 69 |
|
| 70 |
def stream_response():
|
| 71 |
try:
|
| 72 |
+
# ارسال درخواست به اسپیس دیگر و دریافت پاسخ به صورت استریم
|
| 73 |
with requests.post(HF_API_URL, json=payload, stream=True, timeout=720) as response:
|
| 74 |
response.raise_for_status()
|
| 75 |
|
| 76 |
logging.info(f"اتصال موفقیتآمیز با HF Space برای چت {payload.get('id')}. در حال استریم پاسخ...")
|
| 77 |
|
| 78 |
+
# ارسال مستقیم قطعههای خام برای حفظ مرزهای پیام SSE (مانند '\n\n')
|
| 79 |
for chunk in response.iter_content(chunk_size=1024):
|
| 80 |
yield chunk
|
| 81 |
|
|
|
|
| 88 |
"type": "error",
|
| 89 |
"message": "متاسفانه در ارتباط با سرور اصلی خطایی رخ داد. لطفا دوباره تلاش کنید."
|
| 90 |
}
|
| 91 |
+
# ارسال پیام خطا در فرمت SSE
|
| 92 |
yield f"data: {json.dumps(error_payload)}\n\n"
|
| 93 |
|
| 94 |
return Response(stream_response(), mimetype='text/event-stream')
|
| 95 |
|
| 96 |
if __name__ == '__main__':
|
| 97 |
+
# این بخش فقط برای اجرای محلی است. در هاگینگ فیس از Gunicorn استفاده میشود.
|
| 98 |
+
app.run(debug=True, host='0.0.0.0', port=os.environ.get("PORT", 7860))
|
| 99 |
+
|
| 100 |
+
# --- END OF FILE app.py ---
|