File size: 6,090 Bytes
7cc0170
 
 
 
 
 
 
 
 
 
 
 
 
af4689d
 
 
 
 
 
 
 
 
 
7cc0170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
152
153
154
155
156
157
158
159
160
161
162
163
import psycopg2
from dotenv import load_dotenv
import os
from functools import lru_cache
from transformers import pipeline
load_dotenv()

class Database:
    def __init__(self):
        try:
            self.conn = psycopg2.connect(os.getenv("POSTGRES_URL"))
            self.cursor = self.conn.cursor()
            # Verify tables exist on startup
            self.cursor.execute("""
            CREATE TABLE IF NOT EXISTS messages (
                id SERIAL PRIMARY KEY,
                sender VARCHAR(50),
                body TEXT,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
            """)
            self.conn.commit()

            self.cursor.execute("""
                SELECT EXISTS (
                    SELECT FROM information_schema.tables 
                    WHERE table_name = 'users'
                )
            """)
            if not self.cursor.fetchone()[0]:
                raise RuntimeError("Database tables not initialized")
        except Exception as e:
            print(f"Database connection error: {str(e)}")
            raise

    def find_technician(self, service_type: str, longitude: float, latitude: float):
        query = """
            SELECT id, name, contact, rating
            FROM technicians
            WHERE %s = ANY(qualifications)
            AND availability = 'available'
            ORDER BY location <-> ST_SetSRID(ST_MakePoint(%s, %s), 4326)
            LIMIT 1
        """
        self.cursor.execute(query, (service_type, longitude, latitude))
        result = self.cursor.fetchone()
        if result:
            return {
                "id": result[0],
                "name": result[1],
                "contact": result[2],
                "rating": result[3]
            }
        return None

    def get_user_state(self, user_number: str):
        query = "SELECT state, last_message FROM users WHERE number = %s"
        self.cursor.execute(query, (user_number,))
        result = self.cursor.fetchone()
        return {"state": result[0], "last_message": result[1]} if result else None

    def update_user_state(self, user_number: str, state: str, last_message: str):
        query = """
            INSERT INTO users (number, state, last_message)
            VALUES (%s, %s, %s)
            ON CONFLICT (number) DO UPDATE
            SET state = %s, last_message = %s, updated_at = CURRENT_TIMESTAMP
        """
        self.cursor.execute(query, (user_number, state, last_message, state, last_message))
        self.conn.commit()

    def save_request(self, user_number: str, technician_id: int, service_type: str):
        query = """
            INSERT INTO requests (user_number, technician_id, service_type, status)
            VALUES (%s, %s, %s, %s)
            RETURNING id
        """
        self.cursor.execute(query, (user_number, technician_id, service_type, "pending"))
        self.conn.commit()
        return self.cursor.fetchone()[0]

    def close(self):
        self.cursor.close()
        self.conn.close()


class NLPProcessor:
    def __init__(self):
        # Initialize all required attributes
        self.api_url = "https://api-inference.huggingface.co/models/Christy123/service-classifier"
        self.api_token = os.getenv("HF_API_TOKEN")  # Make sure this is in your .env
        self.ner_url = "https://api-inference.huggingface.co/models/dbmdz/bert-large-cased-finetuned-conll03-english"
        self.service_mappings = {
            "ac": "hvac",
            "air conditioner": "hvac",
            "plumb": "plumbing",
            "pipe": "plumbing",
            "electr": "electrical",
            "wiring": "electrical"
        }

    def extract_service(self, text: str) -> str:
        """Enhanced service classification with fallback"""
        try:
            # Try Hugging Face API first
            headers = {"Authorization": f"Bearer {os.getenv('HF_API_TOKEN')}"}
            response = requests.post(
                "https://api-inference.huggingface.co/models/Christy123/service-classifier",
                headers=headers,
                json={"inputs": text},
                timeout=5
            )
                
            if response.status_code == 200:
                result = response.json()[0]
                if result["score"] > 0.7:  # Only accept confident predictions
                    return result["label"]
                
                # Fallback to keyword matching
            text_lower = text.lower()
            for keyword, service in self.service_mappings.items():
                if keyword in text_lower:
                    return service
                        
            return "unknown"
                
        except Exception:
            return "unknown"

    def extract_location(self, text: str) -> str:
        """Enhanced location detection with fallback methods"""
        headers = {"Authorization": f"Bearer {self.api_token}"}
        
        # Try Hugging Face NER first
        try:
            response = requests.post(
                "https://api-inference.huggingface.co/models/dbmdz/bert-large-cased-finetuned-conll03-english",
                headers=headers,
                json={"inputs": text},
                timeout=5
            )
            if response.status_code == 200:
                entities = response.json()
                locations = [e["word"] for e in entities if e["entity_group"] == "LOC"]
                if locations:
                    return locations[0]
        except Exception:
            pass
        
        # Fallback 1: Simple keyword matching
        kenyan_towns = ["Nairobi", "Mombasa", "Kisumu", "Nakuru", "Eldoret", 
                    "Westlands", "Karen", "Runda", "Thika", "Naivasha"]
        for town in kenyan_towns:
            if town.lower() in text.lower():
                return town
        
        # Fallback 2: Look for "in <location>" pattern
        import re
        match = re.search(r"\bin\s+([A-Za-z]+)", text, re.IGNORECASE)
        if match:
            return match.group(1)
        
        return None