Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
import os
|
3 |
+
from fastapi import FastAPI, Request
|
4 |
+
from contextlib import asynccontextmanager
|
5 |
+
from telegram import Update
|
6 |
+
from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackContext
|
7 |
+
import httpx
|
8 |
+
import asyncio
|
9 |
+
from transformers import pipeline
|
10 |
+
from langdetect import detect
|
11 |
+
from huggingface_hub import login
|
12 |
+
|
13 |
+
|
14 |
+
# Global variables
|
15 |
+
TOKEN = os.getenv("TELEGRAM_BOT_TOKEN") # Telegram Token
|
16 |
+
HF_HUB_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
17 |
+
|
18 |
+
|
19 |
+
# Verify Hugging Face token
|
20 |
+
if not HF_HUB_TOKEN:
|
21 |
+
raise ValueError("Missing Hugging Face API token. Please set HUGGINGFACEHUB_API_TOKEN in environment variables.")
|
22 |
+
login(token=HF_HUB_TOKEN)
|
23 |
+
|
24 |
+
|
25 |
+
# Load Hebrew and English text generation models
|
26 |
+
hebrew_generator = pipeline("text-generation", model="Norod78/hebrew-gpt_neo-small")
|
27 |
+
english_generator = pipeline("text-generation", model="distilgpt2")
|
28 |
+
|
29 |
+
|
30 |
+
# Function to detect language
|
31 |
+
def detect_language(user_input):
|
32 |
+
try:
|
33 |
+
lang = detect(user_input)
|
34 |
+
return "hebrew" if lang == "he" else "english" if lang == "en" else "unsupported"
|
35 |
+
except:
|
36 |
+
return "unsupported"
|
37 |
+
|
38 |
+
|
39 |
+
# Function to generate a response
|
40 |
+
def generate_response(text):
|
41 |
+
language = detect_language(text)
|
42 |
+
if language == "hebrew":
|
43 |
+
return hebrew_generator(text, max_length=100)[0]["generated_text"]
|
44 |
+
elif language == "english":
|
45 |
+
return english_generator(text, max_length=100)[0]["generated_text"]
|
46 |
+
return "Sorry, I only support Hebrew and English."
|
47 |
+
|
48 |
+
|
49 |
+
# Create Telegram Bot
|
50 |
+
telegram_app = Application.builder().token(TOKEN).build()
|
51 |
+
|
52 |
+
|
53 |
+
# Initialize Telegram
|
54 |
+
async def init_telegram():
|
55 |
+
await telegram_app.initialize()
|
56 |
+
await telegram_app.start()
|
57 |
+
|
58 |
+
|
59 |
+
# Configure logging
|
60 |
+
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
|
61 |
+
logger = logging.getLogger(__name__)
|
62 |
+
|
63 |
+
|
64 |
+
# Command and Message Handlers
|
65 |
+
async def start(update: Update, context: CallbackContext):
|
66 |
+
await update.message.reply_text("Hello! Tell me your decision-making issue in Hebrew or English, and I'll try to help you.")
|
67 |
+
|
68 |
+
|
69 |
+
async def handle_message(update: Update, context: CallbackContext):
|
70 |
+
user_text = update.message.text
|
71 |
+
response = generate_response(user_text)
|
72 |
+
await update.message.reply_text(response)
|
73 |
+
|
74 |
+
|
75 |
+
telegram_app.add_handler(CommandHandler("start", start))
|
76 |
+
telegram_app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
|
77 |
+
|
78 |
+
|
79 |
+
# FastAPI lifespan event
|
80 |
+
@asynccontextmanager
|
81 |
+
async def lifespan(app: FastAPI):
|
82 |
+
print("Starting application...")
|
83 |
+
|
84 |
+
# Check internet connection
|
85 |
+
try:
|
86 |
+
async with httpx.AsyncClient() as client:
|
87 |
+
response = await client.get("https://api.telegram.org")
|
88 |
+
print(f"Network test successful! Status Code: {response.status_code}")
|
89 |
+
except Exception as e:
|
90 |
+
print(f"Network test failed: {e}")
|
91 |
+
|
92 |
+
# Start Telegram bot
|
93 |
+
asyncio.create_task(init_telegram()) # Run in background
|
94 |
+
|
95 |
+
yield # Wait until app closes
|
96 |
+
|
97 |
+
print("Shutting down application...")
|
98 |
+
|
99 |
+
|
100 |
+
# Create FastAPI app
|
101 |
+
app = FastAPI(lifespan=lifespan)
|
102 |
+
|
103 |
+
|
104 |
+
@app.get("/")
|
105 |
+
async def root():
|
106 |
+
return {"message": "Decision Helper Bot is running!"}
|
107 |
+
|
108 |
+
|
109 |
+
@app.post("/")
|
110 |
+
async def receive_update(request: Request):
|
111 |
+
update = Update.de_json(await request.json(), telegram_app.bot)
|
112 |
+
await telegram_app.process_update(update)
|
113 |
+
return {"status": "ok"}
|
114 |
+
|
115 |
+
|
116 |
+
# Run the server
|
117 |
+
if __name__ == "__main__":
|
118 |
+
import uvicorn
|
119 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|