Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -9,6 +9,13 @@ import asyncio
|
|
9 |
from PIL import Image
|
10 |
import base64
|
11 |
from io import BytesIO
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
def load_system_prompt():
|
14 |
with open('prompt.txt', 'r') as file:
|
@@ -36,62 +43,53 @@ def encode_local_image(image):
|
|
36 |
|
37 |
client = TelegramClient('bot', api_id, api_hash).start(bot_token=bot_token)
|
38 |
|
39 |
-
class
|
40 |
-
def __init__(self, size
|
|
|
41 |
self.size = size
|
42 |
-
self.buffer = [None] * size
|
43 |
-
self.start = 0
|
44 |
-
self.end = 0
|
45 |
|
46 |
def add(self, role: str, content: str):
|
47 |
-
|
48 |
-
|
49 |
-
if
|
50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
|
52 |
def get_history(self):
|
53 |
-
history
|
54 |
-
|
55 |
-
|
56 |
-
history
|
57 |
-
|
58 |
-
return history
|
59 |
|
60 |
def reset(self):
|
61 |
-
|
62 |
-
self.
|
63 |
-
self.end = 0
|
64 |
|
65 |
# Only store history for 3 users
|
66 |
user_histories = {}
|
67 |
|
68 |
def get_user_history(user_id):
|
69 |
if user_id not in user_histories:
|
70 |
-
|
71 |
-
if len(user_histories) >= 3:
|
72 |
-
oldest_user_id = list(user_histories.keys())[0]
|
73 |
-
del user_histories[oldest_user_id]
|
74 |
-
user_histories[user_id] = CircularBuffer(99)
|
75 |
return user_histories[user_id]
|
76 |
|
77 |
-
async def fetch_telegram_history(user_id):
|
78 |
-
# Collect messages into a list
|
79 |
-
messages = []
|
80 |
-
async for message in client.iter_messages(user_id, limit=50): # Use async for loop
|
81 |
-
messages.append(message)
|
82 |
-
|
83 |
-
user_history = get_user_history(user_id)
|
84 |
-
for message in messages:
|
85 |
-
role = 'user' if message.sender_id == user_id else 'assistant'
|
86 |
-
user_history.add(role, message.text)
|
87 |
-
|
88 |
async def get_completion(prompt: str, user_id, image_base64=None) -> str:
|
89 |
user_history = get_user_history(user_id)
|
90 |
|
91 |
-
#
|
92 |
-
if not user_history.get_history():
|
93 |
-
await fetch_telegram_history(user_id)
|
94 |
-
|
95 |
# Prepare message content
|
96 |
if image_base64:
|
97 |
user_message = [
|
@@ -103,7 +101,7 @@ async def get_completion(prompt: str, user_id, image_base64=None) -> str:
|
|
103 |
|
104 |
messages = [
|
105 |
{"role": "system", "content": system_prompt},
|
106 |
-
*user_history.get_history(),
|
107 |
{"role": "user", "content": user_message},
|
108 |
]
|
109 |
|
@@ -133,11 +131,11 @@ async def get_completion(prompt: str, user_id, image_base64=None) -> str:
|
|
133 |
|
134 |
@client.on(events.NewMessage(pattern='/start'))
|
135 |
async def start(event):
|
136 |
-
await event.respond("Hello!
|
137 |
|
138 |
@client.on(events.NewMessage(pattern='/help'))
|
139 |
async def help(event):
|
140 |
-
await event.respond("Here is how I can help you:\n/start - Start
|
141 |
|
142 |
@client.on(events.NewMessage(pattern='/reset'))
|
143 |
async def reset(event):
|
@@ -188,7 +186,6 @@ def keep_alive():
|
|
188 |
while True:
|
189 |
try:
|
190 |
requests.get("https://rbn2008k-Scarlett.hf.space")
|
191 |
-
print("Ping success")
|
192 |
except Exception as e:
|
193 |
print(f"Keep-alive request failed: {e}")
|
194 |
time.sleep(180)
|
|
|
9 |
from PIL import Image
|
10 |
import base64
|
11 |
from io import BytesIO
|
12 |
+
from pymongo import MongoClient
|
13 |
+
|
14 |
+
# MongoDB connection setup
|
15 |
+
mongo_uri = os.getenv('MONGODB_URI')
|
16 |
+
mongo_client = MongoClient(mongo_uri)
|
17 |
+
db = mongo_client['Scarlett'] # Create or connect to 'telegram_bot_db'
|
18 |
+
user_histories_collection = db['chats'] # Collection for storing user chat histories
|
19 |
|
20 |
def load_system_prompt():
|
21 |
with open('prompt.txt', 'r') as file:
|
|
|
43 |
|
44 |
client = TelegramClient('bot', api_id, api_hash).start(bot_token=bot_token)
|
45 |
|
46 |
+
class MongoDBHistory:
|
47 |
+
def __init__(self, user_id, size=99):
|
48 |
+
self.user_id = str(user_id)
|
49 |
self.size = size
|
|
|
|
|
|
|
50 |
|
51 |
def add(self, role: str, content: str):
|
52 |
+
# Add the message to the user's history in MongoDB
|
53 |
+
user_history = user_histories_collection.find_one({'user_id': self.user_id})
|
54 |
+
if user_history:
|
55 |
+
messages = user_history['history']
|
56 |
+
else:
|
57 |
+
messages = []
|
58 |
+
|
59 |
+
# Add new message and truncate if exceeds size
|
60 |
+
messages.append({'role': role, 'content': content})
|
61 |
+
if len(messages) > self.size:
|
62 |
+
messages = messages[-self.size:]
|
63 |
+
|
64 |
+
user_histories_collection.update_one(
|
65 |
+
{'user_id': self.user_id},
|
66 |
+
{'$set': {'history': messages}},
|
67 |
+
upsert=True
|
68 |
+
)
|
69 |
|
70 |
def get_history(self):
|
71 |
+
# Retrieve the user's history from MongoDB
|
72 |
+
user_history = user_histories_collection.find_one({'user_id': self.user_id})
|
73 |
+
if user_history:
|
74 |
+
return user_history['history']
|
75 |
+
return []
|
|
|
76 |
|
77 |
def reset(self):
|
78 |
+
# Remove the user's history from MongoDB
|
79 |
+
user_histories_collection.delete_one({'user_id': self.user_id})
|
|
|
80 |
|
81 |
# Only store history for 3 users
|
82 |
user_histories = {}
|
83 |
|
84 |
def get_user_history(user_id):
|
85 |
if user_id not in user_histories:
|
86 |
+
user_histories[user_id] = MongoDBHistory(user_id)
|
|
|
|
|
|
|
|
|
87 |
return user_histories[user_id]
|
88 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
async def get_completion(prompt: str, user_id, image_base64=None) -> str:
|
90 |
user_history = get_user_history(user_id)
|
91 |
|
92 |
+
# No history is fetched from Telegram. If no history exists in MongoDB, proceed with a clean slate.
|
|
|
|
|
|
|
93 |
# Prepare message content
|
94 |
if image_base64:
|
95 |
user_message = [
|
|
|
101 |
|
102 |
messages = [
|
103 |
{"role": "system", "content": system_prompt},
|
104 |
+
*user_history.get_history(), # Only use history from MongoDB
|
105 |
{"role": "user", "content": user_message},
|
106 |
]
|
107 |
|
|
|
131 |
|
132 |
@client.on(events.NewMessage(pattern='/start'))
|
133 |
async def start(event):
|
134 |
+
await event.respond("Hello!")
|
135 |
|
136 |
@client.on(events.NewMessage(pattern='/help'))
|
137 |
async def help(event):
|
138 |
+
await event.respond("Here is how I can help you:\n/start - Start\n/help - Show this message\n/reset - Reset chat history")
|
139 |
|
140 |
@client.on(events.NewMessage(pattern='/reset'))
|
141 |
async def reset(event):
|
|
|
186 |
while True:
|
187 |
try:
|
188 |
requests.get("https://rbn2008k-Scarlett.hf.space")
|
|
|
189 |
except Exception as e:
|
190 |
print(f"Keep-alive request failed: {e}")
|
191 |
time.sleep(180)
|