Charan5775 commited on
Commit
e547122
·
verified ·
1 Parent(s): 35ce19f

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +90 -38
main.py CHANGED
@@ -7,6 +7,8 @@ import json
7
  from datetime import datetime
8
  import edge_tts
9
  import io
 
 
10
 
11
  # Add these constants at the top
12
  API_URL = "https://api-inference.huggingface.co/models/openai/whisper-large-v3-turbo"
@@ -16,6 +18,27 @@ AI_HEADERS = {
16
  "Accept": "application/json"
17
  }
18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  # TTS settings
20
  DEFAULT_VOICE = "en-IN-NeerjaNeural"
21
  DEFAULT_RATE = "+25%"
@@ -55,6 +78,12 @@ def save_message_to_history(user_id, username, message_type, content, bot_respon
55
  message_history.append(message_data)
56
  print("Message History Update:", json.dumps(message_data, indent=2))
57
 
 
 
 
 
 
 
58
  # Add command to print history
59
  @myaibot.on_message(filters.command("history"))
60
  async def history_command(client, message):
@@ -63,18 +92,36 @@ async def history_command(client, message):
63
  return
64
 
65
  try:
66
- # Create a formatted message
67
- history_text = "📜 Message History:\n\n"
68
- for idx, msg in enumerate(message_history[-10:], 1): # Show last 10 messages
69
- history_text += f"{idx}. Message: {msg['content']}\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  if msg['response']:
71
- history_text += f" Response: {msg['response']}\n"
72
  history_text += "\n"
73
 
74
  await message.reply_text(history_text)
75
 
76
  except Exception as e:
77
- await message.reply_text(f"Error retrieving history: {str(e)}")
 
 
 
 
 
78
 
79
  # Command handler for /start
80
  @myaibot.on_message(filters.command("start"))
@@ -175,42 +222,41 @@ async def transcribe_audio(file_path):
175
  # Add this new function after transcribe_audio function
176
  async def get_ai_response(text):
177
  try:
178
- # Create condensed history from all messages
179
  context = ""
180
  if message_history:
181
- # If we have more than 10 messages, summarize older ones
182
- if len(message_history) > 10:
183
- older_messages = message_history[:-10]
184
- recent_messages = message_history[-10:]
185
-
186
- # Summarize older messages in pairs to save space
187
- context = "Earlier conversation summary:\n"
188
- for i in range(0, len(older_messages), 2):
189
- pair = older_messages[i:i+2]
190
- combined_content = " | ".join(msg['content'] for msg in pair)
191
- if len(combined_content) > 100:
192
- combined_content = combined_content[:100] + "..."
193
- context += f"Chat: {combined_content}\n"
194
-
195
- # Add a separator
196
- context += "\nRecent conversation:\n"
197
-
198
- # Add recent messages in full detail
199
- for msg in recent_messages:
200
- if msg['content'] and msg['response']:
201
- context += f"Human: {msg['content']}\nAssistant: {msg['response']}\n"
202
- else:
203
- # If less than 10 messages, include all in detail
204
- context = "Conversation history:\n"
205
- for msg in message_history:
206
- if msg['content'] and msg['response']:
207
- context += f"Human: {msg['content']}\nAssistant: {msg['response']}\n"
208
 
209
  # Combine context with current query
210
- full_query = f"{context}Human: {text}"
211
 
212
  payload = {
213
- "query": full_query,
214
  "stream": False
215
  }
216
 
@@ -226,7 +272,7 @@ async def get_ai_response(text):
226
 
227
  # The API returns the response directly
228
  if isinstance(response_data, dict) and 'response' in response_data:
229
- return response_data['response']
230
  else:
231
  return str(response_data)
232
 
@@ -297,4 +343,10 @@ async def handle_voice(client, message):
297
  # Run the bot
298
  if __name__ == "__main__":
299
  print("Bot is running...")
300
- myaibot.run()
 
 
 
 
 
 
 
7
  from datetime import datetime
8
  import edge_tts
9
  import io
10
+ from telegraph.aio import Telegraph
11
+ import aiohttp
12
 
13
  # Add these constants at the top
14
  API_URL = "https://api-inference.huggingface.co/models/openai/whisper-large-v3-turbo"
 
18
  "Accept": "application/json"
19
  }
20
 
21
+ # Initialize Telegraph and aiohttp session
22
+ telegraph = None
23
+ session = None
24
+
25
+ async def init_telegraph():
26
+ global telegraph, session
27
+ try:
28
+ if telegraph is None:
29
+ session = aiohttp.ClientSession()
30
+ telegraph = Telegraph(session=session)
31
+ await telegraph.create_account(short_name='TelegramAIBot')
32
+ return True
33
+ except Exception as e:
34
+ print(f"Telegraph initialization error: {e}")
35
+ return False
36
+
37
+ async def cleanup():
38
+ global session
39
+ if session:
40
+ await session.close()
41
+
42
  # TTS settings
43
  DEFAULT_VOICE = "en-IN-NeerjaNeural"
44
  DEFAULT_RATE = "+25%"
 
78
  message_history.append(message_data)
79
  print("Message History Update:", json.dumps(message_data, indent=2))
80
 
81
+ def condense_text(text, max_length=100):
82
+ """Condense text to a maximum length while keeping it readable"""
83
+ if len(text) <= max_length:
84
+ return text
85
+ return text[:max_length-3] + "..."
86
+
87
  # Add command to print history
88
  @myaibot.on_message(filters.command("history"))
89
  async def history_command(client, message):
 
92
  return
93
 
94
  try:
95
+ total_messages = len(message_history)
96
+ history_text = f"📜 Chat History (Total: {total_messages} messages)\n\n"
97
+
98
+ # If we have many messages, summarize older ones
99
+ if total_messages > 10:
100
+ history_text += "Earlier messages:\n"
101
+ for msg in message_history[:-10]:
102
+ history_text += f"• {condense_text(msg['content'], 50)}\n"
103
+
104
+ history_text += "\nRecent messages:\n"
105
+ recent_messages = message_history[-10:]
106
+ else:
107
+ recent_messages = message_history
108
+
109
+ # Add recent messages with more detail
110
+ for idx, msg in enumerate(recent_messages, 1):
111
+ history_text += f"{idx}. Q: {condense_text(msg['content'], 150)}\n"
112
  if msg['response']:
113
+ history_text += f" A: {condense_text(msg['response'], 150)}\n"
114
  history_text += "\n"
115
 
116
  await message.reply_text(history_text)
117
 
118
  except Exception as e:
119
+ print(f"Error in history command: {str(e)}")
120
+ # Fallback to super condensed version
121
+ short_history = "📜 Last 5 Messages:\n\n"
122
+ for msg in message_history[-5:]:
123
+ short_history += f"• {condense_text(msg['content'], 30)}\n"
124
+ await message.reply_text(short_history)
125
 
126
  # Command handler for /start
127
  @myaibot.on_message(filters.command("start"))
 
222
  # Add this new function after transcribe_audio function
223
  async def get_ai_response(text):
224
  try:
225
+ # Create context from history
226
  context = ""
227
  if message_history:
228
+ # Get last 5 relevant messages for context
229
+ recent_history = message_history[-5:]
230
+ context = (
231
+ "You are a helpful AI assistant. Below is the conversation history. "
232
+ "Use this context to provide a relevant response to the user's latest message. "
233
+ "If the current message is related to previous ones, make sure to reference and build upon that information.\n\n"
234
+ "Previous conversation:\n"
235
+ )
236
+
237
+ # Add conversation history with clear markers
238
+ for i, msg in enumerate(recent_history, 1):
239
+ context += f"Message {i}:\n"
240
+ context += f"User: {msg['content']}\n"
241
+ if msg['response']:
242
+ context += f"Assistant: {msg['response']}\n"
243
+ context += "\n"
244
+
245
+ # Add specific instructions for the response
246
+ context += (
247
+ "Instructions:\n"
248
+ "1. Consider the conversation history above\n"
249
+ "2. If the new message relates to previous ones, reference that information\n"
250
+ "3. Maintain consistency with previous responses\n"
251
+ "4. Provide a direct and relevant answer\n\n"
252
+ "New message to respond to:\n"
253
+ )
 
254
 
255
  # Combine context with current query
256
+ full_prompt = f"{context}User: {text}\nAssistant: Let me provide a relevant response based on our conversation..."
257
 
258
  payload = {
259
+ "query": full_prompt,
260
  "stream": False
261
  }
262
 
 
272
 
273
  # The API returns the response directly
274
  if isinstance(response_data, dict) and 'response' in response_data:
275
+ return response_data['response'].replace("Assistant: Let me provide a relevant response based on our conversation...", "").strip()
276
  else:
277
  return str(response_data)
278
 
 
343
  # Run the bot
344
  if __name__ == "__main__":
345
  print("Bot is running...")
346
+ try:
347
+ myaibot.run()
348
+ finally:
349
+ # Cleanup
350
+ if session:
351
+ loop = asyncio.get_event_loop()
352
+ loop.run_until_complete(cleanup())