Spaces:
Sleeping
Sleeping
File size: 5,278 Bytes
61c774d 71736e8 61c774d 5d557f1 61c774d 5d557f1 61c774d 5d557f1 61c774d 5d557f1 61c774d 5d557f1 61c774d 5d557f1 61c774d 5d557f1 61c774d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 |
# database.py
import os
from sqlalchemy import create_engine, Column, Integer, String, Text, Boolean, DateTime, func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from utils.utils import get_secret
import random
from better_profanity import profanity
import logging
# Database connection
DB_USER = get_secret("DB_USER")
DB_PASSWORD = get_secret("DB_PASSWORD")
DB_HOST = get_secret("DB_HOST")
DB_NAME = get_secret("DB_NAME")
DB_PORT = get_secret("DB_PORT", "3306")
DATABASE_URL = f"mysql+pymysql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
try:
logger.info("Connecting to database at %s", DB_HOST)
engine = create_engine(DATABASE_URL, connect_args={"connect_timeout": 10})
# Test the connection
with engine.connect() as connection:
logger.info("Successfully connected to the database")
except Exception as e:
logger.error(f"Error connecting to the database: {str(e)}")
raise e
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class Chatbot(Base):
__tablename__ = "chatbots"
id = Column(Integer, primary_key=True, index=True)
chatbot_id = Column(String(50), unique=True, index=True, nullable=False)
name = Column(String(100), nullable=False)
custom_instruction = Column(Text, nullable=False)
is_active = Column(Boolean, default=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
# Create tables
Base.metadata.create_all(bind=engine)
# Load German profanity words
german_profanity = set()
with open('german_profanity.txt', 'r', encoding='utf-8') as f:
german_profanity = set(word.strip().lower() for word in f)
profanity.add_censor_words(german_profanity)
def filter_profanity(text):
return profanity.censor(text)
def generate_chatbot_id():
adjectives = [
'happy', 'clever', 'bright', 'shiny', 'fluffy', 'gentle', 'brave', 'calm',
'kind', 'joyful', 'radiant', 'sparkling', 'cheerful', 'gracious', 'elegant',
'vivacious', 'serene', 'vibrant', 'splendid', 'charismatic', 'delightful',
'blissful', 'generous', 'charming', 'dazzling', 'glowing', 'harmonious',
'jovial', 'luminous', 'majestic', 'mellow', 'noble', 'optimistic',
'passionate', 'playful', 'resilient', 'spirited', 'tranquil', 'upbeat',
'valiant', 'whimsical', 'witty', 'zealous', 'admirable', 'affectionate',
'brilliant', 'courteous', 'devoted', 'ecstatic', 'faithful', 'gleeful'
]
nouns = [
'elephant', 'penguin', 'lion', 'dolphin', 'koala', 'panda', 'tiger', 'whale',
'butterfly', 'eagle', 'peacock', 'unicorn', 'phoenix', 'otter', 'swan',
'chameleon', 'ladybug', 'flamingo', 'puppy', 'kitten', 'fawn', 'hummingbird',
'koala', 'firefly', 'bunny', 'goldfish', 'puffin', 'orca', 'red_panda', 'turtle',
'parrot', 'owl', 'seahorse', 'hedgehog', 'sloth', 'duckling', 'starfish',
'gazelle', 'panther', 'robin', 'seal', 'lynx', 'jellyfish', 'gecko',
'kangaroo', 'lemur', 'meerkat', 'platypus', 'quokka', 'squirrel', 'toucan'
]
return f"{random.choice(adjectives)}-{random.choice(nouns)}-{random.randint(100, 999)}"
def create_chatbot(name, custom_instruction):
db = SessionLocal()
try:
chatbot_id = generate_chatbot_id()
new_chatbot = Chatbot(chatbot_id=chatbot_id, name=name, custom_instruction=custom_instruction)
db.add(new_chatbot)
db.commit()
db.refresh(new_chatbot)
return new_chatbot
except SQLAlchemyError as e:
db.rollback()
raise e
finally:
db.close()
def get_chatbot(chatbot_id):
db = SessionLocal()
try:
return db.query(Chatbot).filter(Chatbot.chatbot_id == chatbot_id, Chatbot.is_active == True).first()
except SQLAlchemyError as e:
raise e
finally:
db.close()
def update_chatbot(chatbot_id, name=None, custom_instruction=None, is_active=None):
db = SessionLocal()
try:
chatbot = db.query(Chatbot).filter(Chatbot.chatbot_id == chatbot_id).first()
if chatbot:
if name:
chatbot.name = name
if custom_instruction:
chatbot.custom_instruction = custom_instruction
if is_active is not None:
chatbot.is_active = is_active
db.commit()
db.refresh(chatbot)
return chatbot
except SQLAlchemyError as e:
db.rollback()
raise e
finally:
db.close()
def delete_chatbot(chatbot_id):
db = SessionLocal()
try:
chatbot = db.query(Chatbot).filter(Chatbot.chatbot_id == chatbot_id).first()
if chatbot:
db.delete(chatbot)
db.commit()
return True
return False
except SQLAlchemyError as e:
db.rollback()
raise e
finally:
db.close()
def get_all_chatbots():
db = SessionLocal()
try:
return db.query(Chatbot).all()
except SQLAlchemyError as e:
raise e
finally:
db.close() |