Skip to content

Commit

Permalink
Enhance
Browse files Browse the repository at this point in the history
  • Loading branch information
noes14155 committed Sep 22, 2023
1 parent a74df4d commit 79fad13
Show file tree
Hide file tree
Showing 15 changed files with 506 additions and 167 deletions.
9 changes: 7 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,24 @@ FROM python:3.10-slim

WORKDIR /app
ENV PYTHONUNBUFFERED=1

RUN apt-get update \
&& apt-get install -y --no-install-recommends git flac ffmpeg tesseract-ocr wget \
&& apt-get -y clean \
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

RUN mkdir -p /usr/share/tesseract-ocr/4.00/tessdata/script/
#RUN wget https://github.com/tesseract-ocr/tessdata_fast/raw/main/script/Devanagari.traineddata -P /usr/share/tesseract-ocr/4.00/tessdata/script/
ENV TESSDATA_PREFIX=/usr/share/tesseract-ocr/4.00/tessdata

#ENV TESSDATA_PREFIX=/usr/share/tesseract-ocr/4.00/tessdata

COPY requirements.txt .
RUN pip install --upgrade pip \
&& pip install -r requirements.txt \
&& rm requirements.txt \
&& pip cache purge \
&& rm -rf ~/.cache/pip/*
COPY . .

COPY . .
#VOLUME /app/personas
CMD ["python3", "./main.py"]
27 changes: 19 additions & 8 deletions bot/chat_gpt.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,14 @@
from typing import List, Dict, Any, Generator

class ChatGPT:
def __init__(self,api_key,api_base):
def __init__(self, api_key: str, api_base: str):
"""
Initializes the ChatGPT instance with the provided API key and base URL.
Args:
api_key (str): The OpenAI API key.
api_base (str): The base URL for the OpenAI API.
"""
openai.api_key = api_key
openai.api_base = api_base

Expand All @@ -15,13 +22,17 @@ def __init__(self,api_key,api_base):
'Content-Type': 'application/json'
}


def fetch_chat_models(self) -> List[str]:
"""
Fetches available chat models from the OpenAI API and stores them in the models field.
def fetch_chat_models(self):
Returns:
List[str]: The available chat models.
"""
response = requests.get(self.fetch_models_url, headers=self.headers)
if response.status_code == 200:
ModelsData = response.json()
for model in ModelsData.get('data'):
models_data = response.json()
for model in models_data.get('data'):
if "chat" in model['endpoints'][0]:
self.models.append(model['id'])
else:
Expand All @@ -35,25 +46,25 @@ def generate_response(
) -> Generator[str, None, None]:
"""
Generates a response using the selected model and input parameters.
Args:
instruction (str): The instruction for generating the response.
plugin_result (str): The plugin result.
history (List[Dict[str, str]]): The chat history.
prompt (str): The user prompt.
function (List[Dict[str, Any]]): The functions to be used.
model (str): The selected model.
Yields:
str: Each message in the response stream.
"""
retries = 0
while True:
while True:
text = ''
if not model.startswith('gpt'):
plugin_result = ''
function = []
print('Unsupported model. Plugins not used')
messages = [

{"role": "system", "content": instruction},
{"role": "system", "content": plugin_result},
*history
Expand Down
91 changes: 89 additions & 2 deletions bot/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,41 @@


class Database:
"""
A class that provides methods for interacting with a SQLite database.
Attributes:
conn: The SQLite database connection object.
Methods:
__init__(self, db_file): Initializes a new instance of the Database class and connects to the specified SQLite database file.
create_tables(self): Creates the settings and history tables in the database if they do not already exist.
close_connection(self): Closes the database connection.
insert_settings(self, user_id, lang='en', persona='Julie_friend', model='gpt-3.5-turbo'): Inserts settings data for a user into the settings table.
update_settings(self, user_id, lang='en', persona='Julie_friend', model='gpt-3.5-turbo'): Updates the settings data for a user in the settings table.
insert_history(self, user_id, role, content): Inserts history data for a user into the history table.
get_settings(self, user_id): Retrieves the settings data for a user from the settings table.
get_history(self, user_id): Retrieves the history data for a user from the history table.
delete_user_history(self, user_id): Deletes all history data for a user from the history table.
delete_last_2_user_history(self, user_id): Deletes the last 2 history entries for a user from the history table.
"""

def __init__(self, db_file):
"""
Initializes a new instance of the Database class and connects to the specified SQLite database file.
Args:
db_file (str): The path to the SQLite database file.
"""
if not os.path.exists(db_file):
open(db_file, "a").close()
self.conn = sqlite3.connect(db_file)
self.create_tables()

def create_tables(self):
"""
Creates the settings and history tables in the database if they do not already exist.
"""
settings_query = """CREATE TABLE IF NOT EXISTS settings
(user_id INTEGER PRIMARY KEY, lang TEXT DEFAULT 'en',
persona TEXT DEFAULT 'Julie_friend',
Expand All @@ -22,27 +50,65 @@ def create_tables(self):
self.conn.commit()

def close_connection(self):
"""
Closes the database connection.
"""
if self.conn:
self.conn.close()

def insert_settings(self, user_id, lang='en', persona='Julie_friend',model='gpt-3.5-turbo'):
def insert_settings(self, user_id, lang='en', persona='Julie_friend', model='gpt-3.5-turbo'):
"""
Inserts settings data for a user into the settings table.
Args:
user_id (int): The ID of the user.
lang (str, optional): The language setting. Defaults to 'en'.
persona (str, optional): The persona setting. Defaults to 'Julie_friend'.
model (str, optional): The model setting. Defaults to 'gpt-3.5-turbo'.
"""
query = """INSERT OR IGNORE INTO settings (user_id, lang, persona, model)
VALUES (?, ?, ?, ?)"""
self.conn.execute(query, (user_id, lang, persona,model))
self.conn.commit()

def update_settings(self, user_id, lang='en', persona='Julie_friend',model='gpt-3.5-turbo'):
def update_settings(self, user_id, lang='en', persona='Julie_friend', model='gpt-3.5-turbo'):
"""
Updates the settings data for a user in the settings table.
Args:
user_id (int): The ID of the user.
lang (str, optional): The language setting. Defaults to 'en'.
persona (str, optional): The persona setting. Defaults to 'Julie_friend'.
model (str, optional): The model setting. Defaults to 'gpt-3.5-turbo'.
"""
query = """UPDATE settings SET lang=?, persona=?, model=? WHERE user_id=?"""
self.conn.execute(query, (lang, persona, model, user_id))
self.conn.commit()

def insert_history(self, user_id, role, content):
"""
Inserts history data for a user into the history table.
Args:
user_id (int): The ID of the user.
role (str): The role of the user.
content (str): The content of the history entry.
"""
query = """INSERT INTO history (user_id, role, content)
VALUES (?, ?, ?)"""
self.conn.execute(query, (user_id, role, content))
self.conn.commit()

def get_settings(self, user_id):
"""
Retrieves the settings data for a user from the settings table.
Args:
user_id (int): The ID of the user.
Returns:
tuple: A tuple containing the language, persona, and model settings for the user.
"""
query = """SELECT lang, persona, model FROM settings WHERE user_id=?"""
row = self.conn.execute(query, (user_id,)).fetchone()
if row:
Expand All @@ -52,16 +118,37 @@ def get_settings(self, user_id):
return None, None, None

def get_history(self, user_id):
"""
Retrieves the history data for a user from the history table.
Args:
user_id (int): The ID of the user.
Returns:
list: A list of tuples containing the role and content of each history entry.
"""
query = """SELECT role, content FROM history WHERE user_id=?"""
rows = self.conn.execute(query, (user_id,)).fetchall()
return rows

def delete_user_history(self, user_id):
"""
Deletes all history data for a user from the history table.
Args:
user_id (int): The ID of the user.
"""
query = """DELETE FROM history WHERE user_id=?"""
self.conn.execute(query, (user_id,))
self.conn.commit()

def delete_last_2_user_history(self, user_id):
"""
Deletes the last 2 history entries for a user from the history table.
Args:
user_id (int): The ID of the user.
"""
query = """
DELETE FROM history
WHERE rowid IN (
Expand Down
Loading

0 comments on commit 79fad13

Please sign in to comment.