-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
415 lines (343 loc) ยท 17.4 KB
/
main.py
File metadata and controls
415 lines (343 loc) ยท 17.4 KB
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
# pip install comtypes pdf2image Pillow transformers torch pytesseract easyocr reportlab PyMuPDF streamlit
import streamlit as st
import os
import tempfile
from comtypes import client
from pdf2image import convert_from_path
from PIL import Image
from pdf2image.exceptions import PDFInfoNotInstalledError, PDFPageCountError
from transformers import AutoTokenizer, AutoModel
import torch
import easyocr
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
import fitz
def ppt_to_pdf(ppt_path, pdf_path):
"""
PPT ํ์ผ์ PDF๋ก ๋ณํํ๋ ํจ์
:param ppt_path: PPT ํ์ผ ๊ฒฝ๋ก
:param pdf_path: ์ ์ฅํ PDF ํ์ผ ๊ฒฝ๋ก
:return: ์ฑ๊ณต ์ True, ์คํจ ์ False
"""
try:
powerpoint = client.CreateObject("Powerpoint.Application")
powerpoint.Visible = 1
presentation = powerpoint.Presentations.Open(ppt_path)
presentation.SaveAs(pdf_path, 32) # 32๋ PDF ํ์์ ๋ํ๋
๋๋ค
presentation.Close()
powerpoint.Quit()
print(f"PPT ํ์ผ์ด {pdf_path}๋ก ๋ณํ๋์์ต๋๋ค.")
return True
except Exception as e:
print(f"PPT๋ฅผ PDF๋ก ๋ณํํ๋ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}")
return False
def pdf_to_images(pdf_path, output_folder):
"""
PDF ํ์ผ์ ์ด๋ฏธ์ง๋ก ๋ณํํ๋ ํจ์
:param pdf_path: PDF ํ์ผ ๊ฒฝ๋ก
:param output_folder: ์ด๋ฏธ์ง๋ฅผ ์ ์ฅํ ํด๋ ๊ฒฝ๋ก
:return: ์ ์ฅ๋ ์ด๋ฏธ์ง ํ์ผ ๊ฒฝ๋ก ๋ฆฌ์คํธ, ์คํจ ์ ๋น ๋ฆฌ์คํธ
"""
if not os.path.exists(output_folder):
os.makedirs(output_folder)
poppler_bin_path = r"D:\Library\poppler-24.07.0\Library\bin"
if not os.path.exists(poppler_bin_path):
print("Poppler ๊ฒฝ๋ก๊ฐ ์๋ชป๋์์ต๋๋ค.")
return []
try:
images = convert_from_path(pdf_path, poppler_path=poppler_bin_path)
image_paths = []
for i, image in enumerate(images):
image_path = os.path.join(output_folder, f"page_{i+1}.png")
image.save(image_path, "PNG")
image_paths.append(image_path)
print(f"{len(image_paths)}๊ฐ์ ์ด๋ฏธ์ง๊ฐ {output_folder}์ ์ ์ฅ๋์์ต๋๋ค.")
return image_paths
except Exception as e:
print(f"PDF๋ฅผ ์ด๋ฏธ์ง๋ก ๋ณํํ๋ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}")
return []
def ppt_to_pdf_files(test_folder, output_folder):
for filename in os.listdir(test_folder):
if filename.endswith(".ppt") or filename.endswith(".pptx"):
ppt_path = os.path.join(test_folder, filename)
pdf_filename = os.path.splitext(filename)[0] + ".pdf"
pdf_path = os.path.join(output_folder, pdf_filename)
ppt_to_pdf(ppt_path, pdf_path)
print(f"{filename}์(๋ฅผ) {pdf_filename}๋ก ๋ณํํ์ต๋๋ค.")
def load_ocr_model():
"""
OCR ๋ชจ๋ธ๊ณผ ํ ํฌ๋์ด์ ๋ฅผ ๋ก๋ํ๋ ํจ์
"""
tokenizer = AutoTokenizer.from_pretrained('ucaslcl/GOT-OCR2_0', trust_remote_code=True)
model = AutoModel.from_pretrained('ucaslcl/GOT-OCR2_0', trust_remote_code=True, low_cpu_mem_usage=True, device_map='cuda', use_safetensors=True, pad_token_id=tokenizer.eos_token_id)
return tokenizer, model.eval().cuda()
def ppt_to_image_ocr(ppt_path, pdf_path, output_folder):
"""
PPT๋ฅผ PDF๋ก ๋ณํํ๊ณ , ์ด๋ฏธ์ง๋ก ๋ณํํ ํ OCR์ ์ํํ๋ ํจ์
:param ppt_path: PPT ํ์ผ ๊ฒฝ๋ก
:param pdf_path: ์ ์ฅํ PDF ํ์ผ ๊ฒฝ๋ก
:param output_folder: ์ด๋ฏธ์ง์ OCR ๊ฒฐ๊ณผ๋ฅผ ์ ์ฅํ ํด๋ ๊ฒฝ๋ก
:return: OCR ๊ฒฐ๊ณผ ํ
์คํธ ๋ฆฌ์คํธ, ์คํจ ์ ๋น ๋ฆฌ์คํธ
"""
try:
# PPT๋ฅผ PDF๋ก ๋ณํ
if not ppt_to_pdf(ppt_path, pdf_path):
raise Exception("PPT๋ฅผ PDF๋ก ๋ณํํ๋๋ฐ ์คํจํ์ต๋๋ค.")
# PDF๋ฅผ ์ด๋ฏธ์ง๋ก ๋ณํ
image_paths = pdf_to_images(pdf_path, output_folder)
if not image_paths:
raise Exception("PDF๋ฅผ ์ด๋ฏธ์ง๋ก ๋ณํํ๋๋ฐ ์คํจํ์ต๋๋ค.")
# OCR ์ํ
reader = easyocr.Reader(['en', 'ko'])
ocr_results = []
for i, image_path in enumerate(image_paths):
image = Image.open(image_path)
res = reader.readtext(image, detail=0, paragraph=True)
# OCR ๊ฒฐ๊ณผ๋ฅผ ํ
์คํธ ํ์ผ๋ก ์ ์ฅ
txt_path = os.path.join(output_folder, f"ocr_result_{i+1}.txt")
with open(txt_path, 'w', encoding='utf-8') as f:
f.write('\n'.join(res))
ocr_results.append('\n'.join(res))
print(f"์ด๋ฏธ์ง {i+1}์ OCR ๊ฒฐ๊ณผ๊ฐ {txt_path}์ ์ ์ฅ๋์์ต๋๋ค.")
return ocr_results
except Exception as e:
print(f"PPT๋ฅผ ์ด๋ฏธ์ง๋ก ๋ณํํ๊ณ OCR์ ์ํํ๋ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}")
return []
def pdf_to_image_ocr(pdf_path, output_folder):
"""
PDF๋ฅผ ์ด๋ฏธ์ง๋ก ๋ณํํ๊ณ OCR์ ์ํํ๋ ํจ์
:param pdf_path: PDF ํ์ผ ๊ฒฝ๋ก
:param output_folder: ์ด๋ฏธ์ง์ OCR ๊ฒฐ๊ณผ๋ฅผ ์ ์ฅํ ํด๋ ๊ฒฝ๋ก
:return: OCR ๊ฒฐ๊ณผ ํ
์คํธ ๋ฆฌ์คํธ, ์คํจ ์ ๋น ๋ฆฌ์คํธ
"""
try:
# PDF๋ฅผ ์ด๋ฏธ์ง๋ก ๋ณํ
image_paths = pdf_to_images(pdf_path, output_folder)
if not image_paths:
raise Exception("PDF๋ฅผ ์ด๋ฏธ์ง๋ก ๋ณํํ๋๋ฐ ์คํจํ์ต๋๋ค.")
# OCR ์ํ
reader = easyocr.Reader(['en', 'ko'])
ocr_results = []
for i, image_path in enumerate(image_paths):
res = reader.readtext(image_path, detail=0, paragraph=True)
# OCR ๊ฒฐ๊ณผ๋ฅผ ํ
์คํธ ํ์ผ๋ก ์ ์ฅ
txt_path = os.path.join(output_folder, f"ocr_result_{i+1}.txt")
with open(txt_path, 'w', encoding='utf-8') as f:
f.write('\n'.join(res))
ocr_results.append('\n'.join(res))
print(f"์ด๋ฏธ์ง {i+1}์ OCR ๊ฒฐ๊ณผ๊ฐ {txt_path}์ ์ ์ฅ๋์์ต๋๋ค.")
return ocr_results
except Exception as e:
print(f"PDF๋ฅผ ์ด๋ฏธ์ง๋ก ๋ณํํ๊ณ OCR์ ์ํํ๋ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}")
return []
def txt_to_pdf_convert(txt_files_path, pdf_file_name):
"""
ํน์ ๊ฒฝ๋ก์ ๋ชจ๋ txt ํ์ผ์ ํ๋์ PDF๋ก ๋ณํํฉ๋๋ค.
๊ฐ txt ํ์ผ์ PDF์์ 1ํ์ด์ง๋ฅผ ์ฐจ์งํฉ๋๋ค.
:param txt_files_path: txt ํ์ผ๋ค์ด ์๋ ๋๋ ํ ๋ฆฌ ๊ฒฝ๋ก
:param pdf_file_name: ์์ฑํ PDF ํ์ผ์ ์ด๋ฆ
:return: ์ฑ๊ณต ์ True, ์คํจ ์ False
"""
try:
# ํ๊ธ ํฐํธ ๋ฑ๋ก
font_path = 'NanumGothic.ttf' # ํฐํธ ํ์ผ ๊ฒฝ๋ก๋ฅผ ์ ์ ํ ์์ ํด์ฃผ์ธ์
pdfmetrics.registerFont(TTFont('NanumGothic', font_path))
# PDF ์์ฑ
c = canvas.Canvas(pdf_file_name, pagesize=letter)
width, height = letter
# txt ํ์ผ ๋ชฉ๋ก ๊ฐ์ ธ์ค๊ธฐ
txt_files = sorted([f for f in os.listdir(txt_files_path) if f.endswith('.txt')])
for txt_file in txt_files:
file_path = os.path.join(txt_files_path, txt_file)
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# ํ
์คํธ๋ฅผ PDF ํ์ด์ง์ ์ถ๊ฐ
c.setFont('NanumGothic', 12)
textobject = c.beginText(40, height - 40)
for line in content.split('\n'):
textobject.textLine(line)
c.drawText(textobject)
c.showPage() # ์ ํ์ด์ง ์์
c.save() # PDF ์ ์ฅ
print(f"PDF ํ์ผ '{pdf_file_name}'์ด ์์ฑ๋์์ต๋๋ค.")
return True
except Exception as e:
print(f"TXT๋ฅผ PDF๋ก ๋ณํํ๋ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}")
return False
def pdf_to_html(pdf_path, html_path):
"""
PDF ํ์ผ์ HTML๋ก ๋ณํํ๋ ํจ์
:param pdf_path: PDF ํ์ผ ๊ฒฝ๋ก
:param html_path: ์ ์ฅํ HTML ํ์ผ ๊ฒฝ๋ก
:return: ์ฑ๊ณต ์ True, ์คํจ ์ False
"""
try:
doc = fitz.open(pdf_path)
html_content = "<html><body>"
for page_num in range(len(doc)):
page = doc.load_page(page_num)
text = page.get_text("html") # ํ์ด์ง์ ๋ด์ฉ์ HTML๋ก ์ถ์ถ
html_content += text
html_content += "</body></html>"
with open(html_path, "w", encoding="utf-8") as f:
f.write(html_content)
print(f"PDF๊ฐ ์ฑ๊ณต์ ์ผ๋ก HTML๋ก ๋ณํ๋์์ต๋๋ค: {html_path}")
return True
except Exception as e:
print(f"PDF๋ฅผ HTML๋ก ๋ณํํ๋ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}")
return False
def extract_image_from_pdf(pdf_path, output_folder):
"""
PDF ํ์ผ์์ ์ด๋ฏธ์ง๋ฅผ ์ถ์ถํ๊ณ OCR์ ์ํํ๋ ํจ์
:param pdf_path: PDF ํ์ผ ๊ฒฝ๋ก
:param output_folder: ์ด๋ฏธ์ง์ OCR ๊ฒฐ๊ณผ๋ฅผ ์ ์ฅํ ํด๋ ๊ฒฝ๋ก
:return: ์ถ์ถ๋ ์ด๋ฏธ์ง ์, ์คํจ ์ 0
"""
if not os.path.exists(output_folder):
os.makedirs(output_folder)
try:
doc = fitz.open(pdf_path)
image_count = 0
reader = easyocr.Reader(['en', 'ko'])
for page_num in range(len(doc)):
page = doc[page_num]
images = page.get_images()
for img_index, img in enumerate(images):
xref = img[0]
base_image = doc.extract_image(xref)
image_bytes = base_image["image"]
image_ext = base_image["ext"]
image_path = os.path.join(output_folder, f"image_{page_num+1}_{img_index+1}.{image_ext}")
with open(image_path, "wb") as image_file:
image_file.write(image_bytes)
# OCR ์ํ
res = reader.readtext(image_path, detail=0, paragraph=True)
# OCR ๊ฒฐ๊ณผ๋ฅผ ํ
์คํธ ํ์ผ๋ก ์ ์ฅ
text_path = os.path.join(output_folder, f"ocr_text_{page_num+1}_{img_index+1}.txt")
with open(text_path, 'w', encoding='utf-8') as f:
f.write('\n'.join(res))
image_count += 1
print(f"{image_count}๊ฐ์ ์ด๋ฏธ์ง๊ฐ ์ถ์ถ๋๊ณ OCR์ด ์ํ๋์์ต๋๋ค.")
return image_count
except Exception as e:
print(f"PDF์์ ์ด๋ฏธ์ง ์ถ์ถ ๋ฐ OCR ์ํ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}")
return 0
def main():
st.title("ํ์ผ ํ์ ์ ํ๋ฆฌ์ผ์ด์
")
menu = ["PPT to PDF", "PDF to Images", "Image Analysis", "OCR", "TXT to PDF", "PDF to HTML", "Extract Images from PDF"]
choice = st.sidebar.selectbox("๊ธฐ๋ฅ ์ ํ", menu)
if choice == "PPT to PDF":
st.subheader("PPT๋ฅผ PDF๋ก ๋ณํ")
uploaded_file = st.file_uploader("PPT ํ์ผ์ ์
๋ก๋ํ์ธ์", type=["ppt", "pptx"])
if uploaded_file:
with st.spinner("PPT๋ฅผ PDF๋ก ๋ณํ ์ค..."):
with tempfile.NamedTemporaryFile(delete=False, suffix=".pptx") as temp_file:
temp_file.write(uploaded_file.read())
temp_file_path = temp_file.name
output_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf").name
ppt_to_pdf(temp_file_path, output_pdf)
st.success(f"PDF๋ก ๋ณํ๋์์ต๋๋ค: {output_pdf}")
with open(output_pdf, "rb") as file:
st.download_button(
label="๋ณํ๋ PDF ๋ค์ด๋ก๋",
data=file,
file_name="converted.pdf",
mime="application/pdf"
)
elif choice == "PDF to Images":
st.subheader("PDF๋ฅผ ์ด๋ฏธ์ง๋ก ๋ณํ")
uploaded_file = st.file_uploader("PDF ํ์ผ์ ์
๋ก๋ํ์ธ์", type=["pdf"])
if uploaded_file:
with st.spinner("PDF๋ฅผ ์ด๋ฏธ์ง๋ก ๋ณํ ์ค..."):
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
temp_file.write(uploaded_file.read())
temp_file_path = temp_file.name
output_folder = tempfile.mkdtemp()
image_paths = pdf_to_images(temp_file_path, output_folder)
for image_path in image_paths:
st.image(Image.open(image_path), caption=os.path.basename(image_path))
elif choice == "OCR":
st.subheader("OCR ์ํ")
uploaded_file = st.file_uploader("PDF ๋๋ ์ด๋ฏธ์ง ํ์ผ์ ์
๋ก๋ํ์ธ์", type=["pdf", "png", "jpg", "jpeg"])
if uploaded_file:
# ์
๋ก๋๋ ํ์ผ ํ์
if uploaded_file.type.startswith('image'):
st.image(uploaded_file, caption="์
๋ก๋๋ ์ด๋ฏธ์ง", use_column_width=True)
elif uploaded_file.type == "application/pdf":
st.write("PDF ํ์ผ์ด ์
๋ก๋๋์์ต๋๋ค.")
st.write(f"ํ์ผ๋ช
: {uploaded_file.name}")
else:
st.write(f"์
๋ก๋๋ ํ์ผ: {uploaded_file.name}")
with st.spinner("OCR ์ํ ์ค..."):
with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(uploaded_file.name)[1]) as temp_file:
temp_file.write(uploaded_file.read())
temp_file_path = temp_file.name
output_folder = tempfile.mkdtemp()
if uploaded_file.type == "application/pdf":
pdf_to_image_ocr(temp_file_path, output_folder)
else:
reader = easyocr.Reader(['en', 'ko'])
res = reader.readtext(temp_file_path, detail=0, paragraph=True)
txt_path = os.path.join(output_folder, "ocr_result.txt")
with open(txt_path, 'w', encoding='utf-8') as f:
f.write('\n'.join(res))
for file in os.listdir(output_folder):
if file.endswith('.txt'):
with open(os.path.join(output_folder, file), 'r', encoding='utf-8') as f:
st.text_area(f"OCR ๊ฒฐ๊ณผ - {file}", f.read(), height=200)
elif choice == "TXT to PDF":
st.subheader("TXT๋ฅผ PDF๋ก ๋ณํ")
uploaded_file = st.file_uploader("TXT ํ์ผ์ ์
๋ก๋ํ์ธ์", type=["txt"])
if uploaded_file:
with st.spinner("TXT๋ฅผ PDF๋ก ๋ณํ ์ค..."):
with tempfile.NamedTemporaryFile(delete=False, suffix=".txt") as temp_file:
temp_file.write(uploaded_file.read())
temp_file_path = temp_file.name
output_pdf = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf").name
txt_to_pdf_convert(os.path.dirname(temp_file_path), output_pdf)
st.success(f"PDF๋ก ๋ณํ๋์์ต๋๋ค: {output_pdf}")
with open(output_pdf, "rb") as file:
st.download_button(
label="๋ณํ๋ PDF ๋ค์ด๋ก๋",
data=file,
file_name="converted.pdf",
mime="application/pdf"
)
elif choice == "PDF to HTML":
st.subheader("PDF๋ฅผ HTML๋ก ๋ณํ")
uploaded_file = st.file_uploader("PDF ํ์ผ์ ์
๋ก๋ํ์ธ์", type=["pdf"])
if uploaded_file:
with st.spinner("PDF๋ฅผ HTML๋ก ๋ณํ ์ค..."):
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
temp_file.write(uploaded_file.read())
temp_file_path = temp_file.name
output_html = tempfile.NamedTemporaryFile(delete=False, suffix=".html").name
pdf_to_html(temp_file_path, output_html)
st.success(f"HTML๋ก ๋ณํ๋์์ต๋๋ค: {output_html}")
with open(output_html, "r", encoding="utf-8") as file:
st.download_button(
label="๋ณํ๋ HTML ๋ค์ด๋ก๋",
data=file.read(),
file_name="converted.html",
mime="text/html"
)
elif choice == "Extract Images from PDF":
st.subheader("PDF์์ ์ด๋ฏธ์ง ์ถ์ถ")
uploaded_file = st.file_uploader("PDF ํ์ผ์ ์
๋ก๋ํ์ธ์", type=["pdf"])
if uploaded_file:
with st.spinner("PDF์์ ์ด๋ฏธ์ง ์ถ์ถ ์ค..."):
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
temp_file.write(uploaded_file.read())
temp_file_path = temp_file.name
output_folder = tempfile.mkdtemp()
extract_image_from_pdf(temp_file_path, output_folder)
for file in os.listdir(output_folder):
if file.endswith(('.png', '.jpg', '.jpeg')):
st.image(Image.open(os.path.join(output_folder, file)), caption=file)
elif file.endswith('.txt'):
with open(os.path.join(output_folder, file), 'r', encoding='utf-8') as f:
st.text_area(f"OCR ๊ฒฐ๊ณผ - {file}", f.read(), height=200)
if __name__ == "__main__":
main()