AI_Chatbot / apps.py
embedingHF's picture
Upload folder using huggingface_hub
ae677bb verified
Raw
History Blame Contribute Delete
3.13 kB
import sys
import atexit
import os
from django.apps import AppConfig, apps
from django.db import connection
from django.core.exceptions import AppRegistryNotReady
class AiChatbotConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'ai_chatbot'
def ready(self):
# Prevent double execution in runserver
if 'runserver' in sys.argv and '--noreload' not in sys.argv:
if os.environ.get('RUN_MAIN') != 'true':
return
# ✅ FIX: Check if tables exist before syncing
try:
from django.db.utils import OperationalError, ProgrammingError
# Check if master_question table exists
with connection.cursor() as cursor:
cursor.execute("""
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_name = 'ai_chatbot_masterquestion'
);
""")
table_exists = cursor.fetchone()[0]
if not table_exists:
print("⚠️ Database tables not ready yet. Skipping auto-sync.")
return
except (OperationalError, ProgrammingError) as e:
print(f"⚠️ Database not ready: {e}. Skipping auto-sync.")
return
from .services import EmbeddingService
from .models import GlobalQA, MasterQuestion
from .greeting_question import SYSTEM_GREETINGS
try:
service = EmbeddingService()
print("✓ AI Model loaded for Auto-Sync")
# # 1. Sync Master Questions
# for q_data in SYSTEM_QUESTIONS:
# MasterQuestion.objects.get_or_create(
# question=q_data['question'],
# defaults={'order': q_data['order']}
# )
# 2. Sync Global Greetings
for g_data in SYSTEM_GREETINGS:
if not GlobalQA.objects.filter(question=g_data['question']).exists():
print(f"→ Generating vector for greeting: {g_data['question']}")
vector = service.generate_embedding(g_data['question'])
GlobalQA.objects.create(
question=g_data['question'],
answer=g_data['answer'],
question_embedding=vector,
language=g_data['language'],
priority=g_data['priority']
)
print("✅ System AI Knowledge Sync Complete")
# Register thread cleanup on exit
atexit.register(EmbeddingService.cleanup_thread)
except Exception as e:
print(f"✗ Auto-Sync failed: {e}")
def get_property_info(property_id):
PropertyModel = apps.get_model('Property', 'Property')
return PropertyModel.objects.get(id=property_id)