Spaces:
Sleeping
Sleeping
fix errors
Browse files- Dockerfile +14 -2
- app.py +29 -45
Dockerfile
CHANGED
|
@@ -1,6 +1,18 @@
|
|
| 1 |
-
FROM python:3.
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
COPY requirements.txt .
|
| 4 |
RUN pip install --no-cache-dir -r requirements.txt
|
|
|
|
| 5 |
COPY . .
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
CMD ["python", "app.py"]
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
# Install dependencies yang dibutuhkan sistem
|
| 4 |
+
RUN apt-get update && apt-get install -y \
|
| 5 |
+
build-essential \
|
| 6 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 7 |
+
|
| 8 |
+
WORKDIR /app
|
| 9 |
+
|
| 10 |
COPY requirements.txt .
|
| 11 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 12 |
+
|
| 13 |
COPY . .
|
| 14 |
+
|
| 15 |
+
# Port standar Hugging Face
|
| 16 |
+
EXPOSE 7860
|
| 17 |
+
|
| 18 |
CMD ["python", "app.py"]
|
app.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
import logging
|
|
|
|
| 4 |
from threading import Thread
|
| 5 |
from flask import Flask
|
| 6 |
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
|
|
@@ -8,7 +9,9 @@ from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, fil
|
|
| 8 |
import google.generativeai as genai
|
| 9 |
from supabase import create_client, Client
|
| 10 |
|
| 11 |
-
#
|
|
|
|
|
|
|
| 12 |
server = Flask(__name__)
|
| 13 |
|
| 14 |
@server.route('/')
|
|
@@ -16,72 +19,53 @@ def health_check():
|
|
| 16 |
return "Bot status: ACTIVE", 200
|
| 17 |
|
| 18 |
def run_web_server():
|
| 19 |
-
# Hugging Face secara default membaca port 7860
|
| 20 |
server.run(host='0.0.0.0', port=7860)
|
| 21 |
|
| 22 |
-
#
|
| 23 |
-
|
| 24 |
-
supabase: Client = create_client(
|
| 25 |
-
os.getenv("SUPABASE_URL"),
|
| 26 |
-
os.getenv("SUPABASE_SERVICE_ROLE_KEY")
|
| 27 |
-
)
|
| 28 |
-
|
| 29 |
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
|
| 30 |
model = genai.GenerativeModel('gemini-1.5-flash')
|
| 31 |
|
| 32 |
async def analyze_food(image_bytes):
|
| 33 |
-
prompt = "
|
| 34 |
-
{"food_name": "name", "calories": 100, "protein": 5.0, "carbs": 10.0, "fat": 2.0}
|
| 35 |
-
Do not include markdown tags like ```json."""
|
| 36 |
-
|
| 37 |
response = model.generate_content([{"mime_type": "image/jpeg", "data": image_bytes}, prompt])
|
| 38 |
clean_text = response.text.strip().replace("```json", "").replace("```", "")
|
| 39 |
return json.loads(clean_text)
|
| 40 |
|
| 41 |
-
# --- HANDLERS BOT ---
|
| 42 |
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 43 |
-
# WEBAPP_URL diambil dari Secrets (URL Netlify Anda)
|
| 44 |
url = os.getenv("WEBAPP_URL")
|
| 45 |
-
kbd = [[InlineKeyboardButton("📊 Buka Dashboard
|
| 46 |
-
await update.message.reply_text(
|
| 47 |
-
f"Halo {update.effective_user.first_name}! 🍎\nKirim foto makanan untuk cek kalori.",
|
| 48 |
-
reply_markup=InlineKeyboardMarkup(kbd)
|
| 49 |
-
)
|
| 50 |
|
| 51 |
async def handle_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 52 |
-
status = await update.message.reply_text("
|
| 53 |
photo = await update.message.photo[-1].get_file()
|
| 54 |
img_bytes = await photo.download_as_bytearray()
|
| 55 |
-
|
| 56 |
try:
|
| 57 |
data = await analyze_food(img_bytes)
|
| 58 |
-
supabase.table("calorie_logs").insert({
|
| 59 |
-
|
| 60 |
-
**data
|
| 61 |
-
}).execute()
|
| 62 |
-
|
| 63 |
-
res = (f"✅ *{data['food_name']}*\n🔥 {data['calories']} kcal\n"
|
| 64 |
-
f"P: {data['protein']}g | C: {data['carbs']}g | L: {data['fat']}g")
|
| 65 |
-
await status.edit_text(res, parse_mode="Markdown")
|
| 66 |
except Exception as e:
|
| 67 |
-
|
|
|
|
| 68 |
|
| 69 |
-
# --- RUNNER ---
|
| 70 |
if __name__ == '__main__':
|
| 71 |
-
#
|
| 72 |
Thread(target=run_web_server).start()
|
| 73 |
|
| 74 |
-
# 2. Ambil token
|
| 75 |
token = os.getenv("TELEGRAM_BOT_TOKEN")
|
| 76 |
-
|
| 77 |
if not token:
|
| 78 |
-
print("
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
import logging
|
| 4 |
+
import asyncio
|
| 5 |
from threading import Thread
|
| 6 |
from flask import Flask
|
| 7 |
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, WebAppInfo
|
|
|
|
| 9 |
import google.generativeai as genai
|
| 10 |
from supabase import create_client, Client
|
| 11 |
|
| 12 |
+
# Set logging untuk melihat detail error
|
| 13 |
+
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
|
| 14 |
+
|
| 15 |
server = Flask(__name__)
|
| 16 |
|
| 17 |
@server.route('/')
|
|
|
|
| 19 |
return "Bot status: ACTIVE", 200
|
| 20 |
|
| 21 |
def run_web_server():
|
|
|
|
| 22 |
server.run(host='0.0.0.0', port=7860)
|
| 23 |
|
| 24 |
+
# Inisialisasi API
|
| 25 |
+
supabase: Client = create_client(os.getenv("SUPABASE_URL"), os.getenv("SUPABASE_SERVICE_ROLE_KEY"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
|
| 27 |
model = genai.GenerativeModel('gemini-1.5-flash')
|
| 28 |
|
| 29 |
async def analyze_food(image_bytes):
|
| 30 |
+
prompt = "Analyze this food image. Return ONLY raw JSON: {\"food_name\": str, \"calories\": int, \"protein\": float, \"carbs\": float, \"fat\": float}"
|
|
|
|
|
|
|
|
|
|
| 31 |
response = model.generate_content([{"mime_type": "image/jpeg", "data": image_bytes}, prompt])
|
| 32 |
clean_text = response.text.strip().replace("```json", "").replace("```", "")
|
| 33 |
return json.loads(clean_text)
|
| 34 |
|
|
|
|
| 35 |
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
|
|
|
| 36 |
url = os.getenv("WEBAPP_URL")
|
| 37 |
+
kbd = [[InlineKeyboardButton("📊 Buka Dashboard", web_app=WebAppInfo(url=url))]]
|
| 38 |
+
await update.message.reply_text(f"Halo {update.effective_user.first_name}! Kirim foto makananmu.", reply_markup=InlineKeyboardMarkup(kbd))
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
async def handle_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 41 |
+
status = await update.message.reply_text("Menganalisis... ⏳")
|
| 42 |
photo = await update.message.photo[-1].get_file()
|
| 43 |
img_bytes = await photo.download_as_bytearray()
|
|
|
|
| 44 |
try:
|
| 45 |
data = await analyze_food(img_bytes)
|
| 46 |
+
supabase.table("calorie_logs").insert({"user_id": update.effective_user.id, **data}).execute()
|
| 47 |
+
await status.edit_text(f"✅ {data['food_name']} - {data['calories']} kcal")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
except Exception as e:
|
| 49 |
+
logging.error(f"Error AI: {e}")
|
| 50 |
+
await status.edit_text("Gagal menganalisis foto.")
|
| 51 |
|
|
|
|
| 52 |
if __name__ == '__main__':
|
| 53 |
+
# Jalankan Flask
|
| 54 |
Thread(target=run_web_server).start()
|
| 55 |
|
|
|
|
| 56 |
token = os.getenv("TELEGRAM_BOT_TOKEN")
|
|
|
|
| 57 |
if not token:
|
| 58 |
+
print("Kritis: Token tidak ditemukan!")
|
| 59 |
+
exit(1)
|
| 60 |
+
|
| 61 |
+
# Membangun aplikasi dengan timeout dan retry
|
| 62 |
+
app = ApplicationBuilder().token(token).connect_timeout(60).read_timeout(60).build()
|
| 63 |
+
app.add_handler(CommandHandler("start", start))
|
| 64 |
+
app.add_handler(MessageHandler(filters.PHOTO, handle_photo))
|
| 65 |
+
|
| 66 |
+
print("Mencoba menyambungkan ke Telegram...")
|
| 67 |
+
# Gunakan polling dengan penanganan error koneksi
|
| 68 |
+
try:
|
| 69 |
+
app.run_polling(drop_pending_updates=True)
|
| 70 |
+
except Exception as e:
|
| 71 |
+
print(f"Gagal menjalankan bot: {e}")
|