Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,18 +1,21 @@
|
|
1 |
-
import
|
|
|
2 |
import logging
|
3 |
-
import
|
4 |
-
import
|
5 |
-
|
|
|
|
|
6 |
|
7 |
# Configuration
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
|
12 |
-
#
|
13 |
-
|
14 |
|
15 |
-
#
|
16 |
logging.basicConfig(
|
17 |
level=logging.DEBUG,
|
18 |
format='%(asctime)s - %(levelname)s - %(message)s',
|
@@ -23,89 +26,57 @@ logging.basicConfig(
|
|
23 |
)
|
24 |
logger = logging.getLogger(__name__)
|
25 |
|
26 |
-
|
27 |
-
|
28 |
-
async def bot_send_message(chat_id, text):
|
29 |
-
"""Send a message to the specified chat ID using the proxy configuration."""
|
30 |
-
async with httpx.AsyncClient(proxies=PROXY_URL) as client:
|
31 |
-
response = await client.post(
|
32 |
-
f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage",
|
33 |
-
data={"chat_id": chat_id, "text": text, "parse_mode": "Markdown"}
|
34 |
-
)
|
35 |
-
if response.status_code == 200:
|
36 |
-
logger.info(f"Message sent successfully to chat_id {chat_id}")
|
37 |
-
else:
|
38 |
-
logger.error(f"Failed to send message: {response.text}")
|
39 |
-
|
40 |
-
@app.route(f'/webhooks/{WEBHOOK_SECRET}', methods=['POST'])
|
41 |
-
def handle_update():
|
42 |
-
"""Handles incoming updates from Telegram."""
|
43 |
-
payload = request.json
|
44 |
-
logger.debug(f"Received payload: {payload}")
|
45 |
-
|
46 |
-
if payload.get('message'):
|
47 |
-
message_text = payload['message'].get('text')
|
48 |
-
chat_id = payload['message']['chat']['id']
|
49 |
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
json={'text': message_text}
|
58 |
-
)
|
59 |
-
if response.status_code == 200:
|
60 |
-
response_text = response.json().get('data', 'Error processing request.')
|
61 |
-
else:
|
62 |
-
response_text = 'Error occurred while processing your request.'
|
63 |
-
await bot_send_message(chat_id, response_text)
|
64 |
|
65 |
-
|
66 |
-
|
|
|
|
|
|
|
67 |
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
|
74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
75 |
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
retry_attempts = 5
|
80 |
-
retry_delay = 1 # seconds
|
81 |
-
|
82 |
-
for attempt in range(retry_attempts):
|
83 |
-
try:
|
84 |
-
async with httpx.AsyncClient(proxies=PROXY_URL) as client:
|
85 |
-
response = await client.post(
|
86 |
-
f"https://api.telegram.org/bot{BOT_TOKEN}/setWebhook",
|
87 |
-
data={"url": webhook_url},
|
88 |
-
)
|
89 |
-
result = response.json()
|
90 |
-
if result.get('ok'):
|
91 |
-
logger.info("Webhook set successfully.")
|
92 |
-
return
|
93 |
-
elif result.get('error_code') == 429:
|
94 |
-
retry_after = result['parameters'].get('retry_after', retry_delay)
|
95 |
-
logger.warning(f"Rate limit exceeded. Retrying after {retry_after} seconds.")
|
96 |
-
await asyncio.sleep(retry_after)
|
97 |
-
else:
|
98 |
-
logger.error(f"Failed to set webhook: {result}")
|
99 |
-
return
|
100 |
-
except httpx.RequestError as e:
|
101 |
-
logger.error(f"Request exception: {e}")
|
102 |
-
return
|
103 |
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
|
|
109 |
|
110 |
if __name__ == "__main__":
|
111 |
-
|
|
|
1 |
+
import telebot
|
2 |
+
import google.generativeai as genai
|
3 |
import logging
|
4 |
+
import requests
|
5 |
+
import gradio as gr
|
6 |
+
|
7 |
+
# Suppress experimental warnings
|
8 |
+
os.environ['HF_HUB_DISABLE_EXPERIMENTAL_WARNING'] = '1'
|
9 |
|
10 |
# Configuration
|
11 |
+
GOOGLE_API_KEY = 'AIzaSyAYXUMnwmR4nUGDCs97FJJsafcQAPAAuzE'
|
12 |
+
BOT_TOKEN = '7484321656:AAFaswxTqaSHu_s4jd_pk2Q2OJJWYcWHwAM'
|
13 |
+
WEBHOOK_URL = f"https://measmonysuon-flyingbird.hf.space/webhooks/handle_update"
|
14 |
|
15 |
+
# Initialize the Telegram bot
|
16 |
+
bot = telebot.TeleBot(BOT_TOKEN)
|
17 |
|
18 |
+
# Configure logging
|
19 |
logging.basicConfig(
|
20 |
level=logging.DEBUG,
|
21 |
format='%(asctime)s - %(levelname)s - %(message)s',
|
|
|
26 |
)
|
27 |
logger = logging.getLogger(__name__)
|
28 |
|
29 |
+
# Set up Google Generative AI
|
30 |
+
genai.configure(api_key=GOOGLE_API_KEY)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
|
32 |
+
generation_config = {
|
33 |
+
"temperature": 1,
|
34 |
+
"top_p": 0.95,
|
35 |
+
"top_k": 64,
|
36 |
+
"max_output_tokens": 8192,
|
37 |
+
"response_mime_type": "text/plain",
|
38 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
|
40 |
+
model = genai.GenerativeModel(
|
41 |
+
model_name="gemini-1.5-pro",
|
42 |
+
generation_config=generation_config,
|
43 |
+
system_instruction="Please respond to user input"
|
44 |
+
)
|
45 |
|
46 |
+
chat_session = model.start_chat(
|
47 |
+
history=[
|
48 |
+
{"role": "user", "parts": ["hi\n"]},
|
49 |
+
{"role": "model", "parts": ["Hello! 👋 How can I help you today? 😊 \n"]},
|
50 |
+
{"role": "user", "parts": ["I am looking for photo booth service?"]},
|
51 |
+
{"role": "model", "parts": ["That's great! 🎉 I can definitely help you with information about Aforative Media's photo booth services. \n\nTo give you the most relevant information, could you tell me a little more about what you're looking for? ..."]},
|
52 |
+
{"role": "user", "parts": ["How much for photo booth services?"]},
|
53 |
+
{"role": "model", "parts": ["You're smart to ask about pricing upfront! 😉 \n\nAforative Media's Mr. & Ms. Booth photo booth services start at **USD 390 for a minimum of 2 hours**. ..."]},
|
54 |
+
{"role": "user", "parts": ["How about videography service?"]},
|
55 |
+
{"role": "model", "parts": ["You're thinking about capturing the memories on film too? Excellent choice! Videography adds a whole other dimension to remembering special events. \n\nAforative Media offers excellent videography services, and just like their photo booths, their videography packages are competitively priced and flexible. ..."]},
|
56 |
+
]
|
57 |
+
)
|
58 |
|
59 |
+
def generate_response(user_input):
|
60 |
+
"""Generate a response using Google Generative AI."""
|
61 |
+
try:
|
62 |
+
prompt = f"Respond to the user: {user_input}"
|
63 |
+
response = chat_session.send_message(prompt) # Generate response using text and prompt
|
64 |
+
response_text = response.text
|
65 |
+
return response_text
|
66 |
+
except Exception as e:
|
67 |
+
logger.error(f"Error during GenAI processing: {e}")
|
68 |
+
return "Sorry, I can't answer this query right now but I will improve from time to time."
|
69 |
|
70 |
+
# Define Gradio interface
|
71 |
+
def gradio_handle_update(user_input):
|
72 |
+
return generate_response(user_input)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
|
74 |
+
iface = gr.Interface(
|
75 |
+
fn=gradio_handle_update,
|
76 |
+
inputs=gr.Textbox(label="User Input"),
|
77 |
+
outputs=gr.Textbox(label="Bot Response"),
|
78 |
+
live=True
|
79 |
+
)
|
80 |
|
81 |
if __name__ == "__main__":
|
82 |
+
iface.launch() # Launch the Gradio app
|