File size: 7,755 Bytes
935bcf0
 
5e7ad7c
 
 
 
d654245
 
 
 
 
 
935bcf0
c2dfbd3
 
d654245
 
 
 
 
c2dfbd3
d654245
c2dfbd3
d654245
 
c2dfbd3
d654245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2dfbd3
d654245
c2dfbd3
935bcf0
d654245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
935bcf0
5e7ad7c
d654245
935bcf0
d654245
5e7ad7c
935bcf0
 
d654245
 
 
935bcf0
d654245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
935bcf0
d654245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
935bcf0
d654245
935bcf0
 
 
 
d654245
 
 
 
 
 
935bcf0
d654245
 
 
 
 
 
 
935bcf0
d654245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
935bcf0
 
d654245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
935bcf0
 
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import pandas as pd
from datasets import load_dataset
from sentence_transformers import SentenceTransformer, util
from huggingface_hub import InferenceClient
import gradio as gr
import os
import torch

# ==========================
# LOAD DATASET
# ==========================
print("1. Ingesting Data...")

try:
    raw_data = load_dataset("Kaludi/Customer-Support-Responses")
    df = pd.DataFrame(raw_data["train"])

    df = df[["query", "response"]]
    df.columns = ["customer_query", "historical_resolution"]

    print("Cloud dataset loaded successfully.")

except Exception as e:
    print(f"Cloud dataset unavailable ({e}). Using backup dataset...")

    backup_data = [
        {
            "customer_query": "How do I reset my password?",
            "historical_resolution":
            "To reset your password, navigate to login and click Forgot Password. A reset email will be sent."
        },
        {
            "customer_query": "Where is my invoice?",
            "historical_resolution":
            "Invoices are available in Billing & Payments under your account dashboard."
        },
        {
            "customer_query": "How do I cancel subscription?",
            "historical_resolution":
            "Navigate to Settings > Subscription > Cancel Plan."
        },
        {
            "customer_query": "Can I upgrade my account?",
            "historical_resolution":
            "Yes, go to Account Settings > Upgrade Plan."
        },
        {
            "customer_query": "App crashes on startup",
            "historical_resolution":
            "Please update the app and clear cache. If issue persists, contact support."
        }
    ]

    df = pd.DataFrame(backup_data)

# ==========================
# LOAD EMBEDDING MODEL
# ==========================
print("2. Loading Embedding Model...")

embedding_model = SentenceTransformer(
    "paraphrase-multilingual-MiniLM-L12-v2"
)

sample_resolutions = df["historical_resolution"].head(100).tolist()

resolution_embeddings = embedding_model.encode(
    sample_resolutions,
    convert_to_tensor=True
)

# ==========================
# CONNECT TO LLM
# ==========================
print("3. Connecting to Qwen 2.5...")

hf_token = os.environ.get("HF_TOKEN")

client = InferenceClient(
    model="Qwen/Qwen2.5-7B-Instruct",
    token=hf_token
)

# ==========================
# MAIN FUNCTION
# ==========================
def resolve_ticket(customer_query):

    if not customer_query.strip():
        return (
            "⚠️ Please enter a support ticket.",
            "",
            "0%"
        )

    query_embedding = embedding_model.encode(
        customer_query,
        convert_to_tensor=True
    )

    hits = util.semantic_search(
        query_embedding,
        resolution_embeddings,
        top_k=1
    )

    best_match = hits[0][0]
    best_match_index = best_match["corpus_id"]
    similarity_score = float(best_match["score"])

    confidence = round(similarity_score * 100, 2)

    retrieved_context = (
        df["historical_resolution"]
        .iloc[best_match_index]
    )

    messages = [
        {
            "role": "system",
            "content":
            """
            You are a professional multilingual
            customer support assistant.

            Rules:
            - Respond ONLY using the provided internal document
            - Use professional tone
            - Reply in the EXACT SAME LANGUAGE
              as the user's query
            - Be concise but helpful
            """
        },
        {
            "role": "user",
            "content":
            f"""
            Customer Query:
            {customer_query}

            Internal Document:
            {retrieved_context}
            """
        }
    ]

    try:
        response = client.chat.completions.create(
            messages=messages,
            max_tokens=250,
            temperature=0.3
        )

        final_response = (
            response.choices[0]
            .message.content.strip()
        )

        return (
            final_response,
            retrieved_context,
            f"{confidence}%"
        )

    except Exception as e:
        return (
            f"❌ Error: {str(e)}",
            retrieved_context,
            f"{confidence}%"
        )


# ==========================
# CUSTOM CSS
# ==========================
custom_css = """
body {
    background: linear-gradient(
        135deg,
        #050816,
        #0f172a
    );
}

.gradio-container {
    background:
    linear-gradient(
        135deg,
        #050816,
        #0f172a
    ) !important;

    font-family:
    'Segoe UI',
    sans-serif !important;
}

.glass-card {
    background:
    rgba(255,255,255,0.08);

    border:
    1px solid rgba(255,255,255,0.15);

    backdrop-filter:
    blur(18px);

    border-radius: 20px;
    padding: 20px;

    box-shadow:
    0 0 25px rgba(0,255,255,0.18);
}

h1 {
    text-align: center;
    color: #00f5ff;
    text-shadow:
    0px 0px 20px #00f5ff;
}

textarea {
    border-radius: 15px !important;
    border: 1px solid #00f5ff !important;

    box-shadow:
    0px 0px 15px rgba(
        0,
        245,
        255,
        0.4
    ) !important;
}

button {
    background:
    linear-gradient(
        90deg,
        #7c3aed,
        #00f5ff
    ) !important;

    color: white !important;

    border: none !important;
    border-radius: 14px !important;

    font-size: 18px !important;
    font-weight: bold !important;

    height: 55px !important;

    box-shadow:
    0 0 20px rgba(
        0,
        245,
        255,
        0.7
    ) !important;
}

button:hover {
    transform: scale(1.03);
    transition: 0.2s ease;
}

footer {
    visibility: hidden;
}
"""

# ==========================
# UI
# ==========================
with gr.Blocks(
    theme=gr.themes.Glass(),
    css=custom_css,
    title="Multilingual AI Support"
) as demo:

    gr.Markdown("""
    # 🌌 Multilingual AI Support Triage

    ### ⚡ Enterprise AI Ticket Resolution System

    🟢 **Status:** Online  
    🌍 **Languages:** 100+  
    🧠 **AI Model:** Qwen 2.5 7B  
    🔍 **Pipeline:** Retrieval-Augmented Generation (RAG)

    ---
    """)

    with gr.Row():

        with gr.Column(scale=1):

            gr.Markdown("## 📨 Customer Ticket")

            input_query = gr.Textbox(
                label="Enter support query",
                placeholder=
                "Try Spanish, Hindi, German...",
                lines=7
            )

            submit_btn = gr.Button(
                "🚀 Resolve Ticket"
            )

            gr.Markdown("### 🌍 Example Queries")

            gr.Examples(
                examples=[
                    ["¿Cómo restablezco mi contraseña?"],
                    ["Mein Konto wurde doppelt belastet"],
                    ["मेरा पासवर्ड रीसेट नहीं हो रहा"],
                    ["Comment annuler mon abonnement ?"]
                ],
                inputs=input_query
            )

        with gr.Column(scale=1):

            gr.Markdown("## 🤖 AI Resolution")

            output_reply = gr.Textbox(
                label="Generated Response",
                lines=8
            )

            retrieved_doc = gr.Textbox(
                label=
                "Retrieved Internal Document",
                lines=5
            )

            confidence_box = gr.Textbox(
                label="🎯 Match Confidence"
            )

    submit_btn.click(
        fn=resolve_ticket,
        inputs=input_query,
        outputs=[
            output_reply,
            retrieved_doc,
            confidence_box
        ],
        show_progress=True
    )

demo.launch()