Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import uvicorn
|
2 |
+
import logging
|
3 |
+
import os
|
4 |
+
from fastapi import FastAPI, Request
|
5 |
+
import httpx
|
6 |
+
from transformers import pipeline
|
7 |
+
from langdetect import detect
|
8 |
+
from huggingface_hub import login
|
9 |
+
|
10 |
+
|
11 |
+
app = FastAPI()
|
12 |
+
|
13 |
+
# Global variables
|
14 |
+
TOKEN = os.getenv("TELEGRAM_BOT_TOKEN") # Telegram Token
|
15 |
+
HF_HUB_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")
|
16 |
+
|
17 |
+
|
18 |
+
# Verify Hugging Face token
|
19 |
+
if not HF_HUB_TOKEN:
|
20 |
+
raise ValueError("Missing Hugging Face API token. Please set HUGGINGFACEHUB_API_TOKEN in environment variables.")
|
21 |
+
login(token=HF_HUB_TOKEN)
|
22 |
+
|
23 |
+
|
24 |
+
# Verify Telegram token
|
25 |
+
if not TOKEN:
|
26 |
+
raise ValueError("Missing Telegram token. Please set TELEGRAM_BOT_TOKEN in environment variables.")
|
27 |
+
|
28 |
+
|
29 |
+
try:
|
30 |
+
response = httpx.get(f"https://api.telegram.org/bot{TOKEN}/getMe")
|
31 |
+
print(f"Using TELEGRAM_TOKEN: {TOKEN[:5]}***") # Part of the token
|
32 |
+
print(response.json())
|
33 |
+
except httpx.RequestError as e:
|
34 |
+
print(f"aaRequest failed: {e}")
|
35 |
+
|
36 |
+
|
37 |
+
# Configure logging
|
38 |
+
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
|
39 |
+
logger = logging.getLogger(__name__)
|
40 |
+
|
41 |
+
|
42 |
+
# Load Hebrew and English text generation models
|
43 |
+
hebrew_generator = pipeline("text-generation", model="Norod78/hebrew-gpt_neo-small")
|
44 |
+
english_generator = pipeline("text-generation", model="distilgpt2")
|
45 |
+
|
46 |
+
|
47 |
+
# Function to detect language
|
48 |
+
def detect_language(user_input):
|
49 |
+
try:
|
50 |
+
lang = detect(user_input)
|
51 |
+
return "hebrew" if lang == "he" else "english" if lang == "en" else "unsupported"
|
52 |
+
except:
|
53 |
+
return "unsupported"
|
54 |
+
|
55 |
+
|
56 |
+
# Function to generate a response
|
57 |
+
def generate_response(text):
|
58 |
+
language = detect_language(text)
|
59 |
+
if language == "hebrew":
|
60 |
+
return hebrew_generator(text, max_length=100)[0]["generated_text"]
|
61 |
+
elif language == "english":
|
62 |
+
return english_generator(text, max_length=100)[0]["generated_text"]
|
63 |
+
return "Sorry, I only support Hebrew and English."
|
64 |
+
|
65 |
+
|
66 |
+
@app.get("/")
|
67 |
+
async def root():
|
68 |
+
return {"message": "Server is running on HF Spaces"}
|
69 |
+
|
70 |
+
|
71 |
+
if __name__ == "__main__":
|
72 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|