DeMaking commited on
Commit
7b18e43
verified
1 Parent(s): a2c6413

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -18
app.py CHANGED
@@ -5,37 +5,127 @@ from telegram import Update
5
  from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
6
  import os
7
 
8
- app = FastAPI()
 
 
 
 
 
 
 
9
 
10
  # Replace this with your Hugging Face Space URL
11
- HUGGING_FACE_SPACE_URL = "https://demaking-decision-helper-bot.hf.space"
12
 
13
  # Get Telegram bot token from environment variables
14
  TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
15
  if not TOKEN:
16
  raise ValueError("Missing Telegram Bot Token. Please set TELEGRAM_BOT_TOKEN environment variable.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
 
 
 
19
  async def call_hugging_face_space(input_data: str):
 
 
 
20
  async with httpx.AsyncClient(timeout=45.0) as client:
21
  try:
22
  response = await client.post(HUGGING_FACE_SPACE_URL, json={"input": input_data})
23
- response.raise_for_status() # Raise an error for bad responses
24
  return response.json()
25
  except httpx.HTTPStatusError as e:
26
- print(f"HTTP error occurred: {e}")
27
- return {"error": str(e)}
 
 
 
28
  except httpx.ConnectError as e:
29
- print(f"Connection error: {e}")
30
  return {"error": "Could not connect to the Hugging Face Space"}
31
  except Exception as e:
32
- print(f"An error occurred: {e}")
33
- return {"error": str(e)}
34
 
35
 
36
  @app.post("/webhook/{token}")
37
  async def webhook(token: str, request: Request):
38
  if token != TOKEN:
 
39
  return JSONResponse(status_code=403, content={"message": "Forbidden"})
40
 
41
  update = Update.de_json(await request.json(), None)
@@ -52,22 +142,22 @@ def start_telegram_bot():
52
  # Set up a command handler
53
  async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
54
  await update.message.reply_text("Hello! Tell me your decision-making issue, and I'll try to help.")
55
- print("Start command received.")
56
 
57
 
58
- # async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
59
- # user_text = update.message.text
60
- # print(f"User message: {user_text}")
61
 
62
- # # Send the user text to the FastAPI server and get the response.
63
- # result = await call_hugging_face_space(user_text)
64
- # response_text = result.get("response", "Error generating response.")
65
 
66
- # print(f"API Response: {response_text}")
67
- # await update.message.reply_text(response_text)
68
 
69
  application.add_handler(CommandHandler("start", start))
70
- # application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
71
 
72
  # Start the bot
73
  application.run_polling()
 
5
  from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
6
  import os
7
 
8
+ import logging
9
+ # from transformers import pipeline
10
+ from huggingface_hub import InferenceClient, login
11
+ import langid
12
+
13
+ # Configure logging
14
+ logging.basicConfig(format="%(asctime)s - %(levelname)s - %(message)s", level=logging.INFO)
15
+ logger = logging.getLogger(__name__)
16
 
17
  # Replace this with your Hugging Face Space URL
18
+ HUGGING_FACE_SPACE_URL = "https://demaking-decision-helper-bot.hf.space/generate_response"
19
 
20
  # Get Telegram bot token from environment variables
21
  TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
22
  if not TOKEN:
23
  raise ValueError("Missing Telegram Bot Token. Please set TELEGRAM_BOT_TOKEN environment variable.")
24
+
25
+
26
+ # Get Hugging Face API token from environment variable
27
+ HF_HUB_TOKEN = os.getenv("HUGGINGFACEHUB_API_TOKEN")
28
+ if not HF_HUB_TOKEN:
29
+ raise ValueError("Missing Hugging Face API token. Please set HUGGINGFACEHUB_API_TOKEN."
30
+
31
+ # Login and initialize the client
32
+ login(token=HF_HUB_TOKEN)
33
+ client = InferenceClient(api_key=HF_HUB_TOKEN)
34
+
35
+
36
+ app = FastAPI()
37
+
38
+ # Function to detect language
39
+ def detect_language(user_input):
40
+ try:
41
+ lang, _ = langid.classify(user_input)
42
+ return "hebrew" if lang == "he" else "english" if lang == "en" else "unsupported"
43
+ except Exception as e:
44
+ logging.error(f"Language detection error: {e}")
45
+ return "unsupported"
46
+
47
+
48
+ # Function to generate response
49
+ def generate_response(text):
50
+ language = detect_language(text)
51
+
52
+ if language == "hebrew":
53
+ content = "转注谞讛 讘拽爪专讛 讗讘诇 转砖转祝 讗转 转讛诇讬讱 拽讘诇转 讛讛讞诇讟讜转 砖诇讱, " + text
54
+ model = "microsoft/Phi-3.5-mini-instruct"
55
+ elif language == "english":
56
+ content = "keep it short but tell your decision making process, " + text
57
+ model = "mistralai/Mistral-Nemo-Instruct-2407"
58
+ else:
59
+ return "Sorry, I only support Hebrew and English."
60
+
61
+ messages = [{"role": "user", "content": content}]
62
 
63
+ completion = client.chat.completions.create(
64
+ model=model,
65
+ messages=messages,
66
+ max_tokens=2048,
67
+ temperature=0.5,
68
+ top_p=0.7
69
+ )
70
+ return completion.choices[0].message.content
71
+
72
+
73
+ @app.post("/generate_response")
74
+ async def generate_text(request: Request):
75
+ """
76
+ Endpoint to generate a response from the chat model.
77
+ Expects a JSON with a "text" field.
78
+ """
79
+ try:
80
+ data = await request.json()
81
+ text = data.get("text", "").strip()
82
+ if not text:
83
+ return {"error": "No text provided"}
84
+ response = generate_response(text)
85
+ return {"response": response}
86
+ except Exception as e:
87
+ logging.error(f"Error processing request: {e}")
88
+ return {"error": "An unexpected error occurred."}
89
+
90
+
91
+ @app.get("/")
92
+ async def root():
93
+ """
94
+ Root endpoint to check that the API is running.
95
+ """
96
+ return {"message": "Decision Helper API is running!"}
97
+
98
 
99
+ # -------------------------
100
+ # Function to fetch response from FastAPI
101
+ # -------------------------
102
  async def call_hugging_face_space(input_data: str):
103
+ """
104
+ Sends a POST request to the FastAPI API with the user's imput and returns the JSON response.
105
+ """
106
  async with httpx.AsyncClient(timeout=45.0) as client:
107
  try:
108
  response = await client.post(HUGGING_FACE_SPACE_URL, json={"input": input_data})
109
+ response.raise_for_status() # Raise exception for HTTP 4XX/5XX errors
110
  return response.json()
111
  except httpx.HTTPStatusError as e:
112
+ logger.error(f"HTTP Error: {e.response.status_code} - {e.response.text}")
113
+ return {"response": "Error: API returned an error."}
114
+ except httpx.RequestError as e:
115
+ logger.error(f"Request Error: {e}")
116
+ return {"response": "Error: Request Error. Could not reach API."}
117
  except httpx.ConnectError as e:
118
+ logger.error(f"Connection error: {e}")
119
  return {"error": "Could not connect to the Hugging Face Space"}
120
  except Exception as e:
121
+ logger.error(f"Unexpected Error: {e}")
122
+ return {"response": "Error: Unexpected error occurred."}
123
 
124
 
125
  @app.post("/webhook/{token}")
126
  async def webhook(token: str, request: Request):
127
  if token != TOKEN:
128
+ logger.error(f"Tokens doesn't match. {e}")
129
  return JSONResponse(status_code=403, content={"message": "Forbidden"})
130
 
131
  update = Update.de_json(await request.json(), None)
 
142
  # Set up a command handler
143
  async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
144
  await update.message.reply_text("Hello! Tell me your decision-making issue, and I'll try to help.")
145
+ logger.info("Start command received.")
146
 
147
 
148
+ async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
149
+ user_text = update.message.text
150
+ logger.info(f"User message: {user_text}")
151
 
152
+ # Send the user text to the FastAPI server and get the response.
153
+ result = await call_hugging_face_space(user_text)
154
+ response_text = result.get("response", "Error generating response.")
155
 
156
+ logger.info(f"API Response: {response_text}")
157
+ await update.message.reply_text(response_text)
158
 
159
  application.add_handler(CommandHandler("start", start))
160
+ application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
161
 
162
  # Start the bot
163
  application.run_polling()