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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b8e7c1
 
 
 
 
 
 
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
import os
import time
import logging
import sys

import gradio as gr
from pinecone import Pinecone, ServerlessSpec

from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, StorageContext, Settings
from llama_index.vector_stores.pinecone import PineconeVectorStore
from llama_index.readers.file import PDFReader
from llama_index.llms.openai import OpenAI
from llama_index.embeddings.openai import OpenAIEmbedding


# -----------------------------
# Logging
# -----------------------------
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logger = logging.getLogger(__name__)


# -----------------------------
# Environment Variables
# Add these in Hugging Face Spaces Secrets
# -----------------------------
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
PINECONE_API_KEY = os.getenv("PINECONE_API_KEY")

PINECONE_INDEX_NAME = os.getenv("PINECONE_INDEX_NAME", "dds-hr-chatbot")
PINECONE_CLOUD = os.getenv("PINECONE_CLOUD", "aws")
PINECONE_REGION = os.getenv("PINECONE_REGION", "us-east-1")

REINDEX_ON_STARTUP = os.getenv("REINDEX_ON_STARTUP", "false").lower() == "true"

DATA_DIR = "data"

if not OPENAI_API_KEY:
    raise ValueError("OPENAI_API_KEY is missing. Please add it in Hugging Face Spaces secrets.")

if not PINECONE_API_KEY:
    raise ValueError("PINECONE_API_KEY is missing. Please add it in Hugging Face Spaces secrets.")


# -----------------------------
# LlamaIndex Settings
# -----------------------------
Settings.llm = OpenAI(
    model="gpt-4o-mini",
    temperature=0.2,
    api_key=OPENAI_API_KEY
)

Settings.embed_model = OpenAIEmbedding(
    model="text-embedding-ada-002",
    api_key=OPENAI_API_KEY
)

Settings.chunk_size = 600
Settings.chunk_overlap = 200


# -----------------------------
# System Prompt
# -----------------------------
system_prompt = """
You are Ayesha, the Decoding Data Science (DDS) Enterprise HR Chatbot.

Your role is to answer questions using only the uploaded DDS HR Handbook.

Core rules:
- Answer only DDS HR policy questions that are supported by the handbook.
- Do not answer questions outside HR policy scope.
- Do not answer confidential questions, salary questions, legal questions, or old-policy questions.
- If the answer is not available in the handbook, politely say that the information is not available and direct the user to connect@decodingdatascience.com.
- Do not reveal internal reasoning.
- Keep answers concise, professional, and helpful.
- Never invent information.

For forbidden, confidential, unsupported, or out-of-scope topics, respond with:
“I’m sorry, I can only answer questions about the latest DDS HR policies. For confidential or other queries, please email connect@decodingdatascience.com.”

Remember: You are Ayesha, the DDS Enterprise HR Chatbot. You must only answer from the authorized HR handbook content.
"""


# -----------------------------
# Pinecone Setup
# -----------------------------
def get_existing_index_names(pc):
    """
    Handles different Pinecone SDK return styles safely.
    """
    try:
        return pc.list_indexes().names()
    except Exception:
        indexes = pc.list_indexes()
        names = []

        for index_info in indexes:
            if isinstance(index_info, dict):
                names.append(index_info.get("name"))
            else:
                names.append(getattr(index_info, "name", None))

        return [name for name in names if name]


def setup_pinecone_index():
    pc = Pinecone(api_key=PINECONE_API_KEY)

    existing_indexes = get_existing_index_names(pc)

    if PINECONE_INDEX_NAME not in existing_indexes:
        logger.info(f"Creating Pinecone index: {PINECONE_INDEX_NAME}")

        pc.create_index(
            name=PINECONE_INDEX_NAME,
            dimension=1536,
            metric="cosine",
            spec=ServerlessSpec(
                cloud=PINECONE_CLOUD,
                region=PINECONE_REGION
            )
        )

        while True:
            description = pc.describe_index(PINECONE_INDEX_NAME)

            try:
                is_ready = description.status["ready"]
            except Exception:
                is_ready = getattr(description.status, "ready", False)

            if is_ready:
                break

            logger.info("Waiting for Pinecone index to be ready...")
            time.sleep(2)

    else:
        logger.info(f"Using existing Pinecone index: {PINECONE_INDEX_NAME}")

    return pc.Index(PINECONE_INDEX_NAME)


# -----------------------------
# Load or Create LlamaIndex Query Engine
# -----------------------------
def build_query_engine():
    pinecone_index = setup_pinecone_index()

    vector_store = PineconeVectorStore(
        pinecone_index=pinecone_index
    )

    storage_context = StorageContext.from_defaults(
        vector_store=vector_store
    )

    index_stats = pinecone_index.describe_index_stats()
    total_vectors = index_stats.get("total_vector_count", 0)

    if total_vectors == 0 or REINDEX_ON_STARTUP:
        logger.info("Loading documents and creating vector index...")

        if not os.path.exists(DATA_DIR):
            raise ValueError(
                "The 'data' folder is missing. Please create a data folder and upload your PDF file inside it."
            )

        documents = SimpleDirectoryReader(
            input_dir=DATA_DIR,
            required_exts=[".pdf"],
            file_extractor={".pdf": PDFReader()}
        ).load_data()

        if not documents:
            raise ValueError("No PDF documents were loaded from the 'data' folder.")

        index = VectorStoreIndex.from_documents(
            documents,
            storage_context=storage_context
        )

        logger.info("Documents indexed successfully.")

    else:
        logger.info("Existing Pinecone vectors found. Loading index from vector store.")

        index = VectorStoreIndex.from_vector_store(
            vector_store=vector_store
        )

    query_engine = index.as_query_engine(
        similarity_top_k=5,
        system_prompt=system_prompt
    )

    return query_engine


query_engine = build_query_engine()


# -----------------------------
# Query Function
# -----------------------------
def query_doc(prompt):
    try:
        response = query_engine.query(prompt)
        return str(response)

    except Exception as e:
        logger.error(f"Error while answering query: {e}")
        return "Sorry, something went wrong while processing your question. Please try again."


# -----------------------------
# Example Questions
# -----------------------------
example_questions = [
    "What is the leave policy?",
    "What is the work from home policy?",
    "What is the probation policy?",
    "What are the employee code of conduct rules?",
    "Who should I contact for confidential HR questions?"
]


# -----------------------------
# Chat Functions
# -----------------------------
initial_chat = [
    {
        "role": "assistant",
        "content": "Hello, I am Ayesha, the DDS Enterprise HR Chatbot. Ask me a question about DDS HR policies."
    }
]


def respond(message, chat_history):
    if chat_history is None:
        chat_history = initial_chat.copy()

    if not message or not message.strip():
        chat_history.append(
            {
                "role": "assistant",
                "content": "Please enter a question about the DDS HR handbook."
            }
        )
        return "", chat_history

    answer = query_doc(message)

    chat_history.append(
        {
            "role": "user",
            "content": message
        }
    )

    chat_history.append(
        {
            "role": "assistant",
            "content": answer
        }
    )

    return "", chat_history


def clear_chat():
    return initial_chat.copy()


def set_example_question(question):
    return question


# -----------------------------
# Professional Gradio UI
# -----------------------------
DDS_LOGO_URL = "https://raw.githubusercontent.com/Decoding-Data-Science/airesidency/main/dds-logo-removebg-preview.png"

custom_css = """
body {
    background: linear-gradient(135deg, #f8fafc 0%, #eef2ff 45%, #f8fafc 100%);
}

.gradio-container {
    font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}

.main-container {
    max-width: 1250px;
    margin: auto;
}

.header-card {
    background: rgba(255, 255, 255, 0.95);
    border-radius: 24px;
    padding: 26px;
    box-shadow: 0 16px 40px rgba(15, 23, 42, 0.08);
    border: 1px solid #e5e7eb;
    margin-bottom: 20px;
}

.sidebar-card {
    background: rgba(255, 255, 255, 0.96);
    border-radius: 24px;
    padding: 24px;
    box-shadow: 0 16px 40px rgba(15, 23, 42, 0.08);
    border: 1px solid #e5e7eb;
    height: 100%;
}

.chat-card {
    background: rgba(255, 255, 255, 0.96);
    border-radius: 24px;
    padding: 22px;
    box-shadow: 0 16px 40px rgba(15, 23, 42, 0.08);
    border: 1px solid #e5e7eb;
}

.logo-img {
    max-width: 175px;
    margin-bottom: 8px;
}

.title-text {
    font-size: 32px;
    font-weight: 850;
    color: #111827;
    margin-bottom: 8px;
    letter-spacing: -0.03em;
}

.subtitle-text {
    font-size: 16px;
    color: #4b5563;
    line-height: 1.65;
    max-width: 850px;
}

.badge {
    display: inline-block;
    background: #eef2ff;
    color: #3730a3;
    padding: 7px 13px;
    border-radius: 999px;
    font-size: 13px;
    font-weight: 650;
    margin-right: 7px;
    margin-bottom: 8px;
}

.status-box {
    background: #f8fafc;
    border: 1px solid #e5e7eb;
    padding: 14px;
    border-radius: 16px;
    font-size: 14px;
    color: #374151;
    line-height: 1.6;
}

.small-note {
    font-size: 13px;
    color: #6b7280;
    line-height: 1.55;
}

.footer-note {
    font-size: 13px;
    color: #6b7280;
    text-align: center;
    margin-top: 18px;
}

#chatbot {
    min-height: 540px;
    border-radius: 18px;
    border: 1px solid #e5e7eb;
}

#question_box textarea {
    border-radius: 16px !important;
}

.example-button {
    margin-bottom: 8px !important;
    border-radius: 14px !important;
    white-space: normal !important;
    text-align: left !important;
}

.primary-action {
    border-radius: 14px !important;
}

.clear-action {
    border-radius: 14px !important;
}
"""


with gr.Blocks(title="DDS Enterprise HR Chatbot") as demo:

    with gr.Column(elem_classes=["main-container"]):

        # -----------------------------
        # Header
        # -----------------------------
        with gr.Row(elem_classes=["header-card"]):
            with gr.Column(scale=1, min_width=190):
                gr.HTML(
                    f"""
                    <img src="{DDS_LOGO_URL}" class="logo-img" alt="DDS Logo">
                    """
                )

            with gr.Column(scale=5):
                gr.HTML(
                    """
                    <div class="title-text">DDS Enterprise HR Chatbot</div>
                    <div class="subtitle-text">
                        A professional HR policy assistant built for Decoding Data Science.
                        Ask questions from the uploaded DDS HR Handbook and get clear, concise answers
                        based on the available document content.
                    </div>
                    <br>
                    <span class="badge">HR Handbook Q&A</span>
                    <span class="badge">LlamaIndex</span>
                    <span class="badge">Pinecone</span>
                    <span class="badge">OpenAI</span>
                    <span class="badge">Gradio</span>
                    """
                )

        # -----------------------------
        # Two Column Layout
        # -----------------------------
        with gr.Row():

            # Left Sidebar
            with gr.Column(scale=1, min_width=300, elem_classes=["sidebar-card"]):

                gr.Markdown(
                    """
                    ### What this assistant can help with

                    This chatbot answers questions only from the uploaded DDS HR Handbook.

                    **You can ask about:**

                    - Leave policies  
                    - Work from home rules  
                    - Probation guidelines  
                    - Code of conduct  
                    - Employee handbook policies  
                    - HR contact process  
                    """
                )

                gr.HTML(
                    """
                    <div class="status-box">
                        <strong>Scope:</strong> DDS HR policies only<br>
                        <strong>Data source:</strong> Uploaded HR handbook<br>
                        <strong>Confidential questions:</strong> Redirected to HR email
                    </div>
                    """
                )

                gr.Markdown("### Quick questions")

                example_buttons = []

                for question in example_questions:
                    btn = gr.Button(
                        question,
                        variant="secondary",
                        size="sm",
                        elem_classes=["example-button"]
                    )
                    example_buttons.append(btn)

                gr.HTML(
                    """
                    <hr>
                    <div class="small-note">
                    <strong>Important:</strong><br>
                    This chatbot does not answer salary, confidential, legal, or non-HR questions.
                    For confidential queries, contact
                    <strong>connect@decodingdatascience.com</strong>.
                    </div>
                    """
                )

            # Right Chat Area
            with gr.Column(scale=3, elem_classes=["chat-card"]):

                chatbot = gr.Chatbot(
                    label="DDS HR Assistant",
                    elem_id="chatbot",
                    value=initial_chat.copy(),
                    height=540
                )

                user_input = gr.Textbox(
                    label="Ask your HR policy question",
                    placeholder="Example: What is the leave policy?",
                    lines=2,
                    elem_id="question_box"
                )

                with gr.Row():
                    submit_btn = gr.Button(
                        "Ask Question",
                        variant="primary",
                        elem_classes=["primary-action"]
                    )

                    clear_btn = gr.Button(
                        "Clear Chat",
                        variant="secondary",
                        elem_classes=["clear-action"]
                    )

                gr.Markdown(
                    """
                    **Tip:** Ask specific questions for better answers.  
                    Example: “What does the handbook say about probation?” instead of “Tell me everything.”
                    """
                )

        # -----------------------------
        # Button Actions
        # -----------------------------
        submit_btn.click(
            fn=respond,
            inputs=[user_input, chatbot],
            outputs=[user_input, chatbot]
        )

        user_input.submit(
            fn=respond,
            inputs=[user_input, chatbot],
            outputs=[user_input, chatbot]
        )

        clear_btn.click(
            fn=clear_chat,
            inputs=None,
            outputs=chatbot
        )

        for btn, question in zip(example_buttons, example_questions):
            btn.click(
                fn=set_example_question,
                inputs=gr.State(question),
                outputs=user_input
            )

        # -----------------------------
        # Footer
        # -----------------------------
        gr.HTML(
            """
            <div class="footer-note">
                Built by Decoding Data Science | Enterprise HR Chatbot Demo
            </div>
            """
        )


if __name__ == "__main__":
    demo.launch(
        theme=gr.themes.Soft(
            primary_hue="indigo",
            neutral_hue="slate"
        ),
        css=custom_css
    )