File size: 5,511 Bytes
f87ae4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55f5a8e
f87ae4b
55f5a8e
 
 
 
 
 
f87ae4b
55f5a8e
f87ae4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55f5a8e
f87ae4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# src/utils/loader.py
from pypdf import PdfReader
from docx import Document
import pandas as pd
import io
import re
import os

# ---------------------------------------------
# 🧩 1. อ่านไฟล์ PDF
# ---------------------------------------------
def extract_text_from_pdf(file_path: str) -> str:
    """
    ใช้เมื่อมี path ของไฟล์ PDF จริง (เช่นตอนรันบนเครื่อง)
    """
    reader = PdfReader(file_path)
    all_text = ""
    for i, page in enumerate(reader.pages):
        text = page.extract_text()
        if text:
            all_text += f"\n\n--- Page {i+1} ---\n{text}"
    return all_text.strip()


def extract_text_from_pdf_bytes(file_bytes: bytes) -> str:
    """
    ใช้เมื่อไฟล์มาจาก Streamlit uploader (เป็น bytes)
    """
    reader = PdfReader(io.BytesIO(file_bytes))
    texts = []
    for i, page in enumerate(reader.pages):
        text = page.extract_text()
        if text:
            texts.append(f"--- Page {i+1} ---\n{text}")
    return "\n\n".join(texts).strip()

# ---------------------------------------------
# 🧩 2. อ่านไฟล์ DOCX
# ---------------------------------------------
def extract_text_from_docx_bytes(file_bytes: bytes) -> str:
    doc = Document(io.BytesIO(file_bytes))
    paras = [p.text for p in doc.paragraphs if p.text.strip()]
    return "\n".join(paras).strip()


def extract_text_from_docx_path(file_path: str) -> str:
    doc = Document(file_path)
    paras = [p.text for p in doc.paragraphs if p.text.strip()]
    return "\n".join(paras).strip()

# ---------------------------------------------
# 🧩 3. อ่านไฟล์ TXT / CSV
# ---------------------------------------------
def extract_text_from_txt_bytes(file_bytes: bytes, encoding="utf-8") -> str:
    try:
        return file_bytes.decode(encoding, errors="ignore")
    except Exception:
        return file_bytes.decode("utf-8", errors="ignore")


def extract_text_from_txt_path(file_path: str, encoding="utf-8") -> str:
    with open(file_path, "r", encoding=encoding, errors="ignore") as f:
        return f.read()


def extract_text_from_csv_bytes(file_bytes: bytes) -> str:
    df = pd.read_csv(io.BytesIO(file_bytes))
    # รวมทุกคอลัมน์ทุกแถวให้เป็นข้อความเดียว (เพื่อสร้าง quiz ภายหลัง)
    lines = []
    for _, row in df.astype(str).iterrows():
        lines.append(" | ".join(row.values))
    return "\n".join(lines)


def extract_text_from_csv_path(file_path: str) -> str:
    df = pd.read_csv(file_path)
    lines = []
    for _, row in df.astype(str).iterrows():
        lines.append(" | ".join(row.values))
    return "\n".join(lines)

# ---------------------------------------------
# 🧩 4. Clean ข้อความ (ตัดช่องว่าง / จัดรูปแบบ)
# ---------------------------------------------
def clean_text(text: str) -> str:
    text = re.sub(r'\s+\n', '\n', text)     # เว้นวรรคก่อนขึ้นบรรทัด
    text = re.sub(r'\n{3,}', '\n\n', text)  # ตัดบรรทัดว่างเกิน 2 บรรทัด
    text = re.sub(r'[ \t]{2,}', ' ', text)  # ตัดช่องว่างยาว
    return text.strip()

# ---------------------------------------------
# 🧩 5. ฟังก์ชันรวมหลัก (Auto-detect)
# ---------------------------------------------
def load_to_text(uploaded_file) -> str:
    """
    ใช้ใน Streamlit: รับ uploaded_file แล้วคืนข้อความทั้งหมดเป็น string เดียว
    (รองรับ PDF / DOCX / CSV / TXT ทั้งบน local และ Hugging Face)
    """
    # ✅ ป้องกันกรณี .read() แล้ว buffer หาย
    if hasattr(uploaded_file, "getvalue"):
        file_bytes = uploaded_file.getvalue()
    else:
        file_bytes = uploaded_file.read()

    name = uploaded_file.name.lower()
    mime = getattr(uploaded_file, "type", "") or ""

    if name.endswith(".pdf"):
        text = extract_text_from_pdf_bytes(file_bytes)
    elif name.endswith(".docx"):
        text = extract_text_from_docx_bytes(file_bytes)
    elif name.endswith(".csv"):
        text = extract_text_from_csv_bytes(file_bytes)
    elif name.endswith(".txt") or mime.startswith("text/"):
        text = extract_text_from_txt_bytes(file_bytes)
    else:
        # fallback พยายามอ่านเป็นข้อความ
        try:
            text = extract_text_from_txt_bytes(file_bytes)
        except Exception:
            text = ""

    return clean_text(text)


def load_from_path(file_path: str) -> str:
    """
    ใช้นอก Streamlit (อ่านจาก path ปกติ)
    """
    file_path = str(file_path)
    if not os.path.exists(file_path):
        raise FileNotFoundError(file_path)

    if file_path.lower().endswith(".pdf"):
        text = extract_text_from_pdf(file_path)
    elif file_path.lower().endswith(".docx"):
        text = extract_text_from_docx_path(file_path)
    elif file_path.lower().endswith(".csv"):
        text = extract_text_from_csv_path(file_path)
    elif file_path.lower().endswith(".txt"):
        text = extract_text_from_txt_path(file_path)
    else:
        text = ""
    return clean_text(text)