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
+
import nest_asyncio
|
| 5 |
+
|
| 6 |
+
# Import the Hugging Face Inference Client and login function
|
| 7 |
+
from huggingface_hub import InferenceClient, login
|
| 8 |
+
import langid
|
| 9 |
+
|
| 10 |
+
# Import Telegram bot components
|
| 11 |
+
from telegram import Update, Bot
|
| 12 |
+
from telegram.ext import Application, CommandHandler, MessageHandler, filters, CallbackContext
|
| 13 |
+
|
| 14 |
+
# -------------------------
|
| 15 |
+
# Configure logging
|
| 16 |
+
# -------------------------
|
| 17 |
+
logging.basicConfig(
|
| 18 |
+
format="%(asctime)s - %(levelname)s - %(message)s", level=logging.INFO
|
| 19 |
+
)
|
| 20 |
+
logger = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
# -------------------------
|
| 23 |
+
# Environment variables and login to Hugging Face
|
| 24 |
+
# -------------------------
|
| 25 |
+
HF_HUB_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
| 26 |
+
if not HF_HUB_TOKEN:
|
| 27 |
+
raise ValueError("Missing Hugging Face API token. Please set HUGGINGFACEHUB_API_TOKEN.")
|
| 28 |
+
|
| 29 |
+
login(token=HF_HUB_TOKEN)
|
| 30 |
+
client = InferenceClient(api_key=HF_HUB_TOKEN)
|
| 31 |
+
|
| 32 |
+
# Get Telegram Bot Token
|
| 33 |
+
TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
|
| 34 |
+
if not TOKEN:
|
| 35 |
+
raise ValueError("Missing Telegram Bot Token. Please set TELEGRAM_BOT_TOKEN.")
|
| 36 |
+
|
| 37 |
+
# Get Webhook Domain (e.g., your-space.hf.space)
|
| 38 |
+
WEBHOOK_DOMAIN = os.getenv("WEBHOOK_DOMAIN")
|
| 39 |
+
if not WEBHOOK_DOMAIN:
|
| 40 |
+
raise ValueError("Missing Webhook Domain. Please set WEBHOOK_DOMAIN.")
|
| 41 |
+
|
| 42 |
+
# Construct the full webhook URL.
|
| 43 |
+
# We use the Telegram bot token as a unique path.
|
| 44 |
+
WEBHOOK_URL = f"https://{WEBHOOK_DOMAIN}/{TOKEN}"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# -------------------------
|
| 48 |
+
# Function to detect language
|
| 49 |
+
# -------------------------
|
| 50 |
+
def detect_language(user_input: str):
|
| 51 |
+
try:
|
| 52 |
+
lang, _ = langid.classify(user_input)
|
| 53 |
+
if lang == "he":
|
| 54 |
+
return "hebrew"
|
| 55 |
+
elif lang == "en":
|
| 56 |
+
return "english"
|
| 57 |
+
else:
|
| 58 |
+
return "unsupported"
|
| 59 |
+
except Exception as e:
|
| 60 |
+
logger.error(f"Language detection error: {e}")
|
| 61 |
+
return "unsupported"
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# -------------------------
|
| 65 |
+
# Function to generate response using Hugging Face Chat models
|
| 66 |
+
# -------------------------
|
| 67 |
+
def generate_response(text: str) -> str:
|
| 68 |
+
language = detect_language(text)
|
| 69 |
+
|
| 70 |
+
if language == "hebrew":
|
| 71 |
+
# For Hebrew, prompt the model accordingly.
|
| 72 |
+
content = "转注谞讛 讘拽爪专讛 讗讘诇 转砖转祝 讗转 转讛诇讬讱 拽讘诇转 讛讛讞诇讟讜转 砖诇讱, " + text
|
| 73 |
+
model = "microsoft/Phi-3.5-mini-instruct"
|
| 74 |
+
elif language == "english":
|
| 75 |
+
# For English, use a different prompt.
|
| 76 |
+
content = "keep it short but tell your decision making process, " + text
|
| 77 |
+
model = "mistralai/Mistral-Nemo-Instruct-2407"
|
| 78 |
+
else:
|
| 79 |
+
return "Sorry, I only support Hebrew and English."
|
| 80 |
+
|
| 81 |
+
messages = [{"role": "user", "content": content}]
|
| 82 |
+
|
| 83 |
+
try:
|
| 84 |
+
# Call the chat completion API
|
| 85 |
+
completion = client.chat.completions.create(
|
| 86 |
+
model=model,
|
| 87 |
+
messages=messages,
|
| 88 |
+
max_tokens=2048,
|
| 89 |
+
temperature=0.5,
|
| 90 |
+
top_p=0.7
|
| 91 |
+
)
|
| 92 |
+
return completion.choices[0].message.content
|
| 93 |
+
except Exception as e:
|
| 94 |
+
logger.error(f"Error generating response: {e}")
|
| 95 |
+
return "Error: Could not generate response."
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# -------------------------
|
| 99 |
+
# Telegram Bot Handlers
|
| 100 |
+
# -------------------------
|
| 101 |
+
async def start(update: Update, context: CallbackContext):
|
| 102 |
+
# Respond to the /start command.
|
| 103 |
+
await update.message.reply_text("Hello! Tell me your decision-making issue, and I'll try to help.")
|
| 104 |
+
logger.info("Start command received.")
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
async def handle_message(update: Update, context: CallbackContext):
|
| 108 |
+
user_text = update.message.text
|
| 109 |
+
logger.info(f"User message: {user_text}")
|
| 110 |
+
|
| 111 |
+
# Generate a response using our Hugging Face chat logic.
|
| 112 |
+
response_text = generate_response(user_text)
|
| 113 |
+
logger.info(f"Generated response: {response_text}")
|
| 114 |
+
|
| 115 |
+
await update.message.reply_text(response_text)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
# -------------------------
|
| 119 |
+
# Main function to run the Telegram Bot using Webhook mode
|
| 120 |
+
# -------------------------
|
| 121 |
+
async def main():
|
| 122 |
+
# Build the Application with the Telegram Bot Token.
|
| 123 |
+
application = Application.builder().token(TOKEN).build()
|
| 124 |
+
|
| 125 |
+
# Add command and message handlers.
|
| 126 |
+
application.add_handler(CommandHandler("start", start))
|
| 127 |
+
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
|
| 128 |
+
|
| 129 |
+
logger.info("Starting bot in webhook mode...")
|
| 130 |
+
print("Starting bot in webhook mode...")
|
| 131 |
+
|
| 132 |
+
# Run the bot in webhook mode.
|
| 133 |
+
# The bot will listen on all interfaces (0.0.0.0) at port 7860.
|
| 134 |
+
# Telegram will send updates to WEBHOOK_URL.
|
| 135 |
+
await application.run_webhook(
|
| 136 |
+
listen="0.0.0.0", # Listen on all interfaces.
|
| 137 |
+
port=7860, # Port to listen on.
|
| 138 |
+
url_path=TOKEN, # Use the bot token as the URL path.
|
| 139 |
+
webhook_url=WEBHOOK_URL # Full webhook URL.
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
# -------------------------
|
| 144 |
+
# Run the main function without closing a running event loop
|
| 145 |
+
# -------------------------
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
# Apply nest_asyncio to allow nested event loops (needed in some HF Space environments).
|
| 148 |
+
nest_asyncio.apply()
|
| 149 |
+
loop = asyncio.get_event_loop()
|
| 150 |
+
|
| 151 |
+
try:
|
| 152 |
+
loop.run_until_complete(main())
|
| 153 |
+
except Exception as e:
|
| 154 |
+
logger.error(f"Error in main loop: {e}")
|
| 155 |
+
print(f"Error in main loop: {e}")
|