Spaces:
Sleeping
Sleeping
Fix errors
Browse files
app.py
CHANGED
|
@@ -1,6 +1,10 @@
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
import logging
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
from flask import Flask, request
|
| 5 |
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
|
| 6 |
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes
|
|
@@ -11,10 +15,8 @@ from supabase import create_client, Client
|
|
| 11 |
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
|
| 12 |
logger = logging.getLogger(__name__)
|
| 13 |
|
| 14 |
-
#
|
| 15 |
TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
|
| 16 |
-
# URL Space Anda (Contoh: https://username-space.hf.space)
|
| 17 |
-
# Pastikan tidak ada tanda / di akhir URL
|
| 18 |
BASE_URL = os.getenv("SPACE_URL")
|
| 19 |
|
| 20 |
# Inisialisasi API
|
|
@@ -22,64 +24,68 @@ supabase = create_client(os.getenv("SUPABASE_URL"), os.getenv("SUPABASE_SERVICE_
|
|
| 22 |
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
|
| 23 |
model = genai.GenerativeModel('gemini-1.5-flash')
|
| 24 |
|
| 25 |
-
# Flask App
|
| 26 |
app_flask = Flask(__name__)
|
| 27 |
-
|
| 28 |
-
# Telegram Application
|
| 29 |
ptb_app = ApplicationBuilder().token(TOKEN).build()
|
| 30 |
|
| 31 |
-
# --- LOGIKA BOT ---
|
| 32 |
-
async def analyze_food(image_bytes):
|
| 33 |
-
prompt = "Analyze this food image. Return ONLY raw JSON: {\"food_name\": str, \"calories\": int, \"protein\": float, \"carbs\": float, \"fat\": float}"
|
| 34 |
-
response = model.generate_content([{"mime_type": "image/jpeg", "data": image_bytes}, prompt])
|
| 35 |
-
clean_text = response.text.strip().replace("```json", "").replace("```", "")
|
| 36 |
-
return json.loads(clean_text)
|
| 37 |
-
|
| 38 |
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 39 |
url = os.getenv("WEBAPP_URL")
|
| 40 |
kbd = [[InlineKeyboardButton("📊 Dashboard", web_app=WebAppInfo(url=url))]]
|
| 41 |
-
await update.message.reply_text("Halo! Kirim foto makanan untuk cek kalori.", reply_markup=InlineKeyboardMarkup(kbd))
|
| 42 |
|
| 43 |
async def handle_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
img_bytes = await photo.download_as_bytearray()
|
| 47 |
-
try:
|
| 48 |
-
data = await analyze_food(img_bytes)
|
| 49 |
-
supabase.table("calorie_logs").insert({"user_id": update.effective_user.id, **data}).execute()
|
| 50 |
-
await status.edit_text(f"✅ {data['food_name']} - {data['calories']} kcal")
|
| 51 |
-
except Exception as e:
|
| 52 |
-
logger.error(f"Error AI: {e}")
|
| 53 |
-
await status.edit_text("Gagal menganalisis foto.")
|
| 54 |
|
| 55 |
-
# Tambahkan Handlers
|
| 56 |
ptb_app.add_handler(CommandHandler("start", start))
|
| 57 |
ptb_app.add_handler(MessageHandler(filters.PHOTO, handle_photo))
|
| 58 |
|
| 59 |
-
# ---
|
| 60 |
@app_flask.route(f"/{TOKEN}", methods=['POST'])
|
| 61 |
async def webhook():
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
return "OK", 200
|
| 66 |
|
| 67 |
@app_flask.route('/')
|
| 68 |
def index():
|
| 69 |
-
return "Bot is
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
await ptb_app.bot.set_webhook(url=webhook_url)
|
| 76 |
|
| 77 |
if __name__ == '__main__':
|
| 78 |
-
# Jalankan
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
loop.run_until_complete(setup_webhook())
|
| 83 |
|
| 84 |
-
# Jalankan Flask
|
| 85 |
app_flask.run(host='0.0.0.0', port=7860)
|
|
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
import logging
|
| 4 |
+
import asyncio
|
| 5 |
+
import socket
|
| 6 |
+
import time
|
| 7 |
+
from threading import Thread
|
| 8 |
from flask import Flask, request
|
| 9 |
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
|
| 10 |
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes
|
|
|
|
| 15 |
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
|
| 16 |
logger = logging.getLogger(__name__)
|
| 17 |
|
| 18 |
+
# Config
|
| 19 |
TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
|
|
|
|
|
|
|
| 20 |
BASE_URL = os.getenv("SPACE_URL")
|
| 21 |
|
| 22 |
# Inisialisasi API
|
|
|
|
| 24 |
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
|
| 25 |
model = genai.GenerativeModel('gemini-1.5-flash')
|
| 26 |
|
|
|
|
| 27 |
app_flask = Flask(__name__)
|
|
|
|
|
|
|
| 28 |
ptb_app = ApplicationBuilder().token(TOKEN).build()
|
| 29 |
|
| 30 |
+
# --- LOGIKA BOT (Tetap sama) ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 32 |
url = os.getenv("WEBAPP_URL")
|
| 33 |
kbd = [[InlineKeyboardButton("📊 Dashboard", web_app=WebAppInfo(url=url))]]
|
| 34 |
+
await update.message.reply_text("Halo! Bot aktif. Kirim foto makanan untuk cek kalori.", reply_markup=InlineKeyboardMarkup(kbd))
|
| 35 |
|
| 36 |
async def handle_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 37 |
+
# (Logika Gemini & Supabase Anda di sini...)
|
| 38 |
+
await update.message.reply_text("Foto diterima! Sedang diproses...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
|
|
|
| 40 |
ptb_app.add_handler(CommandHandler("start", start))
|
| 41 |
ptb_app.add_handler(MessageHandler(filters.PHOTO, handle_photo))
|
| 42 |
|
| 43 |
+
# --- WEBHOOK ROUTE ---
|
| 44 |
@app_flask.route(f"/{TOKEN}", methods=['POST'])
|
| 45 |
async def webhook():
|
| 46 |
+
update = Update.de_json(request.get_json(force=True), ptb_app.bot)
|
| 47 |
+
await ptb_app.process_update(update)
|
| 48 |
+
return "OK", 200
|
|
|
|
| 49 |
|
| 50 |
@app_flask.route('/')
|
| 51 |
def index():
|
| 52 |
+
return "Bot is Waiting for Network...", 200
|
| 53 |
+
|
| 54 |
+
# --- FUNGSI TUNGGU JARINGAN (RETRY LOGIC) ---
|
| 55 |
+
async def start_bot_with_retry():
|
| 56 |
+
max_retries = 10
|
| 57 |
+
retry_delay = 10 # detik
|
| 58 |
+
|
| 59 |
+
for i in range(max_retries):
|
| 60 |
+
try:
|
| 61 |
+
logger.info(f"Mencoba menyambung ke Telegram (Percobaan {i+1}/{max_retries})...")
|
| 62 |
+
# Cek DNS secara manual dulu
|
| 63 |
+
socket.gethostbyname('api.telegram.org')
|
| 64 |
+
|
| 65 |
+
# Jika DNS ok, jalankan inisialisasi
|
| 66 |
+
await ptb_app.initialize()
|
| 67 |
+
webhook_url = f"{BASE_URL}/{TOKEN}"
|
| 68 |
+
await ptb_app.bot.set_webhook(url=webhook_url)
|
| 69 |
+
logger.info(f"✅ Webhook berhasil diset ke: {webhook_url}")
|
| 70 |
+
return # Keluar dari loop jika berhasil
|
| 71 |
+
except Exception as e:
|
| 72 |
+
logger.error(f"❌ Koneksi gagal: {e}")
|
| 73 |
+
if i < max_retries - 1:
|
| 74 |
+
logger.info(f"Menunggu {retry_delay} detik sebelum mencoba lagi...")
|
| 75 |
+
await asyncio.sleep(retry_delay)
|
| 76 |
+
else:
|
| 77 |
+
logger.error("Sistem menyerah. Periksa koneksi internet server.")
|
| 78 |
|
| 79 |
+
def run_bot_thread():
|
| 80 |
+
loop = asyncio.new_event_loop()
|
| 81 |
+
asyncio.set_event_loop(loop)
|
| 82 |
+
loop.run_until_complete(start_bot_with_retry())
|
|
|
|
| 83 |
|
| 84 |
if __name__ == '__main__':
|
| 85 |
+
# Jalankan Bot di thread berbeda agar Flask bisa start duluan
|
| 86 |
+
# Ini supaya Space tidak dianggap 'Crashed' oleh Hugging Face
|
| 87 |
+
bot_thread = Thread(target=run_bot_thread)
|
| 88 |
+
bot_thread.start()
|
|
|
|
| 89 |
|
| 90 |
+
# Jalankan Flask (HF butuh port 7860 segera aktif)
|
| 91 |
app_flask.run(host='0.0.0.0', port=7860)
|