File size: 12,720 Bytes
a63380b
5d7cdd2
 
 
a63380b
 
 
 
 
 
77f8aea
a63380b
 
 
e45b86d
a63380b
 
 
 
 
 
 
 
 
e45b86d
a63380b
6ab90a8
 
 
a63380b
 
 
 
6ab90a8
5d7cdd2
6ab90a8
 
 
5d7cdd2
6ab90a8
 
a63380b
5d7cdd2
a63380b
 
6ab90a8
a63380b
6ab90a8
 
5d7cdd2
6ab90a8
 
a63380b
6ab90a8
a63380b
6ab90a8
5d7cdd2
 
6ab90a8
 
 
a63380b
6ab90a8
 
a63380b
6ab90a8
 
 
 
 
5d7cdd2
a63380b
 
 
5d7cdd2
a63380b
 
 
e45b86d
 
 
a63380b
 
 
5d7cdd2
 
 
 
 
a63380b
 
 
 
6ab90a8
 
 
 
a63380b
77f8aea
a63380b
 
 
 
5d7cdd2
 
 
 
a63380b
6ab90a8
a63380b
5d7cdd2
 
 
a63380b
6ab90a8
 
 
 
 
 
 
 
 
 
 
 
5d7cdd2
6ab90a8
a63380b
 
 
 
 
 
 
e45b86d
6ab90a8
e45b86d
 
5d7cdd2
6ab90a8
e45b86d
a63380b
 
6ab90a8
5d7cdd2
6ab90a8
 
 
a63380b
5d7cdd2
a63380b
 
 
 
 
 
 
 
 
6ab90a8
 
a63380b
 
 
 
 
 
5d7cdd2
 
 
a63380b
e45b86d
a63380b
 
 
 
 
 
 
 
5d7cdd2
 
 
 
a63380b
 
 
 
 
 
6ab90a8
5d7cdd2
 
6ab90a8
a63380b
 
 
6ab90a8
a63380b
 
5d7cdd2
a63380b
ec5a291
a63380b
 
 
 
 
ec5a291
a63380b
 
 
 
 
e45b86d
a63380b
 
 
 
 
 
 
e45b86d
5d7cdd2
a63380b
 
 
5d7cdd2
a63380b
 
6ab90a8
5d7cdd2
6ab90a8
 
e45b86d
a63380b
 
 
 
 
e45b86d
 
a63380b
 
 
 
e45b86d
 
 
 
5d7cdd2
a63380b
 
 
5d7cdd2
a63380b
 
5d7cdd2
a63380b
 
 
 
 
 
 
e45b86d
a63380b
 
 
 
 
e45b86d
a63380b
 
5d7cdd2
a63380b
e45b86d
 
 
77f8aea
a63380b
77f8aea
e45b86d
a63380b
5d7cdd2
 
 
 
 
 
 
 
 
 
 
 
a63380b
 
77f8aea
e45b86d
 
77f8aea
 
a63380b
5d7cdd2
a63380b
77f8aea
5d7cdd2
a63380b
5d7cdd2
ec5a291
5d7cdd2
a63380b
5d7cdd2
a63380b
5d7cdd2
e45b86d
a63380b
77f8aea
a63380b
 
5d7cdd2
a63380b
 
 
5d7cdd2
a63380b
 
e45b86d
a63380b
 
5d7cdd2
e45b86d
5d7cdd2
e45b86d
5d7cdd2
 
a63380b
 
 
6ab90a8
 
5d7cdd2
6ab90a8
e45b86d
6ab90a8
 
 
 
a63380b
5d7cdd2
a63380b
 
 
5d7cdd2
a63380b
 
 
5d7cdd2
a63380b
 
6ab90a8
 
 
5d7cdd2
6ab90a8
a63380b
 
5d7cdd2
e45b86d
5d7cdd2
e45b86d
5d7cdd2
 
a63380b
5d7cdd2
 
a63380b
5d7cdd2
ec5a291
5d7cdd2
 
 
 
 
 
 
 
 
 
a63380b
5d7cdd2
 
a63380b
 
 
 
 
 
 
5d7cdd2
ec5a291
5d7cdd2
a63380b
 
 
 
77f8aea
 
e45b86d
a63380b
 
 
 
6ab90a8
 
e45b86d
 
6ab90a8
 
5d7cdd2
 
6ab90a8
a63380b
e45b86d
a63380b
 
5d7cdd2
a63380b
ec5a291
6ab90a8
5d7cdd2
a63380b
5d7cdd2
a63380b
 
e45b86d
a63380b
5d7cdd2
a63380b
 
 
e45b86d
a63380b
 
 
 
5d7cdd2
a63380b
 
6ab90a8
a63380b
5d7cdd2
e45b86d
6ab90a8
5d7cdd2
 
6ab90a8
 
a63380b
5d7cdd2
ec5a291
a63380b
 
5d7cdd2
 
6ab90a8
 
e45b86d
 
5d7cdd2
e45b86d
5d7cdd2
e45b86d
 
6ab90a8
5d7cdd2
e45b86d
 
 
 
5d7cdd2
e45b86d
 
 
5d7cdd2
e45b86d
 
 
a63380b
 
 
 
5d7cdd2
a63380b
 
e45b86d
5d7cdd2
a63380b
 
 
5d7cdd2
a63380b
 
 
e45b86d
5d7cdd2
a63380b
 
 
 
e45b86d
6ab90a8
e45b86d
 
 
 
5d7cdd2
e45b86d
 
 
a63380b
5d7cdd2
a63380b
 
6ab90a8
a63380b
 
5d7cdd2
a63380b
 
 
 
 
 
ec5a291
5d7cdd2
ec5a291
 
a63380b
ec5a291
a63380b
 
e45b86d
ec5a291
5d7cdd2
ec5a291
 
a63380b
e45b86d
 
 
5d7cdd2
6ab90a8
5d7cdd2
 
ec5a291
5d7cdd2
a63380b
 
 
e45b86d
 
5d7cdd2
e45b86d
 
 
 
5d7cdd2
 
 
e45b86d
 
 
 
 
5d7cdd2
e45b86d
 
6ab90a8
5d7cdd2
 
 
 
 
 
a63380b
 
e45b86d
ec5a291
5d7cdd2
ec5a291
 
6ab90a8
e45b86d
6ab90a8
e45b86d
6ab90a8
e45b86d
5d7cdd2
 
 
 
 
 
 
e45b86d
5d7cdd2
e45b86d
5d7cdd2
e45b86d
5d7cdd2
e45b86d
5d7cdd2
e45b86d
5d7cdd2
e45b86d
5d7cdd2
e45b86d
ec5a291
e45b86d
5d7cdd2
e45b86d
5d7cdd2
e45b86d
6ab90a8
e45b86d
a63380b
 
e45b86d
ec5a291
5d7cdd2
ec5a291
 
a63380b
 
 
e45b86d
5d7cdd2
 
e45b86d
6ab90a8
 
a63380b
 
 
 
5d7cdd2
a63380b
77f8aea
6ab90a8
5d7cdd2
6ab90a8
e45b86d
 
77f8aea
a63380b
 
 
ec5a291
 
 
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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
# ================================================================
# Wine Quality Research Assistant
# Simple RAG Chatbot for Hugging Face Spaces
# Gradio 6.x Compatible
# ================================================================

import os
import re
import numpy as np
import torch
import gradio as gr

from pypdf import PdfReader
from sentence_transformers import SentenceTransformer
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM


# ================================================================
# 1. CONFIGURATION
# ================================================================

APP_TITLE = "🍷 Wine Quality Research Assistant"

EMBEDDING_MODEL_ID = "sentence-transformers/all-MiniLM-L6-v2"
LLM_MODEL_ID = "google/flan-t5-small"

TOP_K = 3
CHUNK_SIZE = 700
CHUNK_OVERLAP = 100

DEVICE = "cuda" if torch.cuda.is_available() else "cpu"


print("=" * 70)
print("Starting Wine Quality Research Assistant")
print("=" * 70)

print(f"Device: {DEVICE}")
print(f"Gradio: {gr.__version__}")


# ================================================================
# 2. FIND PDF
# ================================================================

def find_pdf():

    pdf_files = [
        file
        for file in os.listdir(".")
        if file.lower().endswith(".pdf")
    ]

    if not pdf_files:

        raise FileNotFoundError(
            "No PDF found. Upload the capstone PDF "
            "to the root folder of the Space."
        )

    print("\nPDF files detected:")

    for pdf in pdf_files:
        print(" -", pdf)

    return pdf_files[0]


PDF_FILE = find_pdf()

print(f"\nUsing PDF: {PDF_FILE}")


# ================================================================
# 3. CLEAN PDF TEXT
# ================================================================

def clean_text(text):

    if not text:
        return ""

    text = text.replace("\x00", " ")

    text = re.sub(
        r"\s+",
        " ",
        text
    )

    return text.strip()


# ================================================================
# 4. READ PDF
# ================================================================

def read_pdf(pdf_path):

    reader = PdfReader(pdf_path)

    pages = []

    for page_number, page in enumerate(
        reader.pages,
        start=1
    ):

        try:

            text = clean_text(
                page.extract_text()
            )

            if text:

                pages.append(
                    {
                        "page": page_number,
                        "text": text
                    }
                )

        except Exception as error:

            print(
                f"Could not read page "
                f"{page_number}: {error}"
            )

    return pages


pages = read_pdf(PDF_FILE)


if not pages:

    raise ValueError(
        "PDF found, but no readable text "
        "could be extracted."
    )


print(
    f"Loaded {len(pages)} PDF pages."
)


# ================================================================
# 5. CREATE CHUNKS
# ================================================================

def create_chunks(pages):

    chunks = []

    for page_data in pages:

        text = page_data["text"]
        page_number = page_data["page"]

        start = 0

        while start < len(text):

            end = start + CHUNK_SIZE

            chunk_text = text[
                start:end
            ].strip()

            if len(chunk_text) > 50:

                chunks.append(
                    {
                        "page": page_number,
                        "text": chunk_text
                    }
                )

            start += (
                CHUNK_SIZE -
                CHUNK_OVERLAP
            )

    return chunks


chunks = create_chunks(pages)

print(
    f"Created {len(chunks)} "
    f"knowledge chunks."
)


# ================================================================
# 6. LOAD EMBEDDING MODEL
# ================================================================

print("Loading embedding model...")


embedding_model = SentenceTransformer(
    EMBEDDING_MODEL_ID,
    device=DEVICE
)


document_texts = [
    chunk["text"]
    for chunk in chunks
]


document_embeddings = embedding_model.encode(
    document_texts,
    convert_to_numpy=True,
    normalize_embeddings=True,
    show_progress_bar=False
)


print("Embedding model ready.")


# ================================================================
# 7. LOAD LANGUAGE MODEL
# ================================================================

print(
    f"Loading language model: "
    f"{LLM_MODEL_ID}"
)


tokenizer = AutoTokenizer.from_pretrained(
    LLM_MODEL_ID
)


llm_model = AutoModelForSeq2SeqLM.from_pretrained(
    LLM_MODEL_ID
)


llm_model.to(DEVICE)
llm_model.eval()


print("Language model ready.")


# ================================================================
# 8. RETRIEVE RELEVANT PDF CONTENT
# ================================================================

def retrieve_context(question):

    question_embedding = embedding_model.encode(
        [question],
        convert_to_numpy=True,
        normalize_embeddings=True
    )[0]


    similarity_scores = np.dot(
        document_embeddings,
        question_embedding
    )


    top_indices = np.argsort(
        similarity_scores
    )[-TOP_K:][::-1]


    results = []


    for index in top_indices:

        results.append(
            {
                "page":
                    chunks[index]["page"],

                "text":
                    chunks[index]["text"],

                "score":
                    float(
                        similarity_scores[
                            index
                        ]
                    )
            }
        )


    return results


# ================================================================
# 9. BUILD CONTEXT
# ================================================================

def build_context(results):

    sections = []

    for item in results:

        sections.append(
            f"""
PAGE {item['page']}:

{item['text']}
"""
        )

    return "\n".join(sections)


# ================================================================
# 10. FORMAT CHAT HISTORY
# ================================================================

def format_history(history):

    if not history:
        return ""

    conversation = []

    # Only retain recent conversation
    for item in history[-4:]:

        if isinstance(item, dict):

            role = item.get(
                "role",
                ""
            )

            content = item.get(
                "content",
                ""
            )

            conversation.append(
                f"{role}: {content}"
            )

    return "\n".join(conversation)


# ================================================================
# 11. GENERATE ANSWER
# ================================================================

def generate_answer(
    question,
    context,
    history
):

    prompt = f"""
You are a helpful academic research assistant.

You answer questions about the research project:

"Machine Learning-Based Prediction of Wine Quality
Using Physicochemical Properties."

Answer the user's question using ONLY the information
provided in the DOCUMENT CONTEXT.

RULES:

1. Answer the question directly.
2. Use clear and simple language.
3. Be academically accurate.
4. Do not invent information.
5. Do not invent research results.
6. Clearly distinguish proposed methodology from
   completed findings.
7. Use bullet points when helpful.
8. Keep the answer focused on the user's question.
9. If the document does not contain the answer, say:

"This information is not specified in the current
capstone synopsis."

DOCUMENT CONTEXT:

{context}

RECENT CONVERSATION:

{history}

QUESTION:

{question}

ANSWER:
"""


    inputs = tokenizer(
        prompt,
        return_tensors="pt",
        truncation=True,
        max_length=1800
    )


    inputs = {
        key: value.to(DEVICE)
        for key, value
        in inputs.items()
    }


    with torch.no_grad():

        output = llm_model.generate(
            **inputs,
            max_new_tokens=220,
            num_beams=2,
            do_sample=False,
            repetition_penalty=1.15,
            no_repeat_ngram_size=3
        )


    answer = tokenizer.decode(
        output[0],
        skip_special_tokens=True
    )


    return answer.strip()


# ================================================================
# 12. CHAT FUNCTION
# ================================================================

def chat(message, history):

    if not message.strip():

        return (
            "Please enter a question "
            "about the document."
        )


    print("\n" + "=" * 60)
    print(f"QUESTION: {message}")


    # Retrieve relevant content
    results = retrieve_context(
        message
    )


    print("Retrieved:")

    for item in results:

        print(
            f"Page {item['page']} | "
            f"Score: {item['score']:.3f}"
        )


    context = build_context(
        results
    )


    history_text = format_history(
        history
    )


    answer = generate_answer(
        message,
        context,
        history_text
    )


    # Unique page numbers
    source_pages = sorted(
        set(
            item["page"]
            for item in results
        )
    )


    page_text = ", ".join(
        str(page)
        for page in source_pages
    )


    return f"""
{answer}

---

πŸ“š **Source page(s): {page_text}**
"""


# ================================================================
# 13. CSS
# ================================================================

css = """

.gradio-container {
    max-width: 1000px !important;
    margin: auto !important;
}

"""


# ================================================================
# 14. USER INTERFACE
# ================================================================

with gr.Blocks(
    title=APP_TITLE
) as demo:


    # ------------------------------------------------------------
    # SIMPLE HEADER
    # ------------------------------------------------------------

    gr.Markdown(
        """
# 🍷 Wine Quality Research Assistant

### Ask questions about the QM640 Wine Quality Capstone

This chatbot searches the uploaded capstone document and
answers your questions using the relevant information from it.

**Type your question below to begin.**
"""
    )


    # ------------------------------------------------------------
    # SMALL STATUS LINE
    # ------------------------------------------------------------

    gr.Markdown(
        f"""
πŸ“„ **Document loaded:** `{PDF_FILE}`  
πŸ“‘ **Pages:** {len(pages)} &nbsp;&nbsp; | &nbsp;&nbsp;
🧩 **Knowledge chunks:** {len(chunks)}
"""
    )


    # ------------------------------------------------------------
    # CHATBOT
    # ------------------------------------------------------------

    chatbot_component = gr.Chatbot(
        height=480,
        show_label=False,
        placeholder=(
            "🍷 Ask me anything about "
            "the Wine Quality Capstone."
        )
    )


    # ------------------------------------------------------------
    # CHAT INTERFACE
    # ------------------------------------------------------------

    chat_interface = gr.ChatInterface(

        fn=chat,

        chatbot=chatbot_component,

        textbox=gr.Textbox(
            placeholder=(
                "Ask a question about "
                "the document..."
            ),
            show_label=False
        ),

        submit_btn="Ask",

        stop_btn=False,

        examples=[

            "What is the main objective of the study?",

            "What dataset is used in this project?",

            "What are the research questions?",

            "Which machine learning models will be compared?",

            "How will model performance be evaluated?",

            "What is the business value of this research?"

        ]

    )


    # ------------------------------------------------------------
    # FOOTER
    # ------------------------------------------------------------

    gr.Markdown(
        """
---

πŸ”Ž **RAG-powered:** Your question β†’ Relevant PDF sections β†’
AI-generated answer

*QM640 Data Analytics Capstone*
"""
    )


# ================================================================
# 15. LAUNCH
# ================================================================

print("\n" + "=" * 70)
print("Wine Quality Research Assistant is ready.")
print("=" * 70)


if __name__ == "__main__":

    demo.queue()

    demo.launch(
        css=css
    )