Wewoo commited on
Commit
a77c81d
·
verified ·
1 Parent(s): ed2fe46

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +92 -0
  2. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+ import PyPDF2
4
+
5
+ # Model tốt nhất cho tiếng Anh + chạy được trên HF Free
6
+ summarizer = pipeline(
7
+ "summarization",
8
+ model="google/pegasus-xsum"
9
+ )
10
+
11
+ def read_pdf(file_obj):
12
+ """Đọc PDF từ Gradio file object."""
13
+ try:
14
+ with open(file_obj.name, "rb") as f:
15
+ reader = PyPDF2.PdfReader(f)
16
+ text = ""
17
+ for page in reader.pages:
18
+ t = page.extract_text()
19
+ if t:
20
+ text += t + "\n"
21
+ return text
22
+ except Exception as e:
23
+ return None
24
+
25
+
26
+ def chunk_text(text, max_chars=512):
27
+ """
28
+ Chia text thành đoạn nhỏ an toàn cho Pegasus.
29
+ Pegasus chịu tối đa ~512 tokens → nên dùng 512 chars để chắc chắn không crash.
30
+ """
31
+ chunks = []
32
+ text = text.strip()
33
+
34
+ while len(text) > max_chars:
35
+ # tìm dấu chấm gần nhất để chia tự nhiên
36
+ cut = text.rfind('.', 0, max_chars)
37
+ if cut == -1:
38
+ # không có dấu chấm → cắt cứng
39
+ cut = max_chars
40
+ chunk = text[:cut].strip()
41
+ if len(chunk) > 0:
42
+ chunks.append(chunk)
43
+ text = text[cut:].strip()
44
+
45
+ if len(text) > 0:
46
+ chunks.append(text)
47
+
48
+ return chunks
49
+
50
+
51
+ def summarize_pdf(pdf_file):
52
+ if pdf_file is None:
53
+ return "Hãy upload một file PDF."
54
+
55
+ text = read_pdf(pdf_file)
56
+ if text is None:
57
+ return "Lỗi đọc PDF — có thể file bị mã hóa hoặc không phải PDF chuẩn."
58
+
59
+ text = text.strip()
60
+ if len(text) < 50:
61
+ return "PDF quá ngắn hoặc không có nội dung văn bản."
62
+
63
+ # chia nhỏ text → tránh lỗi CPU + tránh timeout HF
64
+ chunks = chunk_text(text)
65
+ summaries = []
66
+
67
+ for i, chunk in enumerate(chunks):
68
+ try:
69
+ result = summarizer(
70
+ chunk,
71
+ max_length=120, # phù hợp Pegasus
72
+ min_length=20,
73
+ do_sample=False
74
+ )
75
+ summaries.append(result[0]["summary_text"])
76
+ except Exception as e:
77
+ summaries.append(f"[Lỗi khi tóm tắt đoạn {i+1}]: {e}")
78
+
79
+ # nối summaries lại
80
+ return "\n\n".join(summaries)
81
+
82
+
83
+ with gr.Blocks() as demo:
84
+ gr.Markdown("## 📝 Tóm tắt PDF bằng AI (Pegasus + Gradio)")
85
+
86
+ pdf = gr.File(label="Upload PDF", file_types=[".pdf"])
87
+ output = gr.Textbox(lines=12, label="Kết quả tóm tắt")
88
+
89
+ btn = gr.Button("Tóm tắt PDF")
90
+ btn.click(fn=summarize_pdf, inputs=pdf, outputs=output)
91
+
92
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ transformers
2
+ torch
3
+ gradio
4
+ PyPDF2
5
+ sentencepiece
6
+ accelerate