File size: 3,134 Bytes
ae677bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)