File size: 7,002 Bytes
48f6f3a
 
 
 
829153b
d1f0261
 
25cdf71
48f6f3a
829153b
48f6f3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcde59f
48f6f3a
788f9ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48f6f3a
788f9ea
 
48f6f3a
788f9ea
 
 
 
 
48f6f3a
 
 
 
 
788f9ea
48f6f3a
 
788f9ea
48f6f3a
788f9ea
48f6f3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
829153b
25cdf71
829153b
25cdf71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcde59f
 
48f6f3a
 
 
25cdf71
 
d1f0261
 
 
829153b
25cdf71
d1f0261
 
829153b
 
48f6f3a
 
 
 
 
 
 
 
 
 
25cdf71
48f6f3a
 
 
 
 
 
 
 
 
 
 
 
25cdf71
48f6f3a
fcde59f
48f6f3a
 
 
 
 
 
 
 
 
 
 
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
import re
import requests
from bs4 import BeautifulSoup
import gradio as gr
from paddleocr import PaddleOCR
from PIL import Image
import numpy as np
import cv2

# Summarizer
try:
    from summa.summarizer import summarize as textrank_summarize
    HAS_SUMMA = True
except Exception:
    HAS_SUMMA = False

DEFAULT_HEADERS = {"User-Agent": "Mozilla/5.0"}

# -----------------------------
# Fetch
# -----------------------------
def fetch_html(url: str, timeout: int = 12) -> str:
    r = requests.get(url, headers=DEFAULT_HEADERS, timeout=timeout)
    r.raise_for_status()
    return r.text

# -----------------------------
# HTML -> Text (preserve code blocks)
# -----------------------------
def _strip_noise_tags(soup: BeautifulSoup):
    for t in soup(["script", "style", "noscript", "svg", "iframe"]):
        t.decompose()
    for t in soup.find_all(["header", "footer", "nav", "aside"]):
        t.decompose()

def _pick_content_root(soup: BeautifulSoup):
    for selector in ["main", "article", "[role='main']"]:
        node = soup.select_one(selector)
        if node:
            return node
    candidates = soup.find_all("div")
    if not candidates:
        return soup.body or soup
    best = max(candidates, key=lambda d: len(d.get_text(strip=True) or ""))
    return best if best else (soup.body or soup)

def html_to_text_preserve_code(html: str) -> str:
    soup = BeautifulSoup(html, "html.parser")
    if not soup:
        return "๋ณธ๋ฌธ์„ ์ถ”์ถœํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."
    _strip_noise_tags(soup)
    root = _pick_content_root(soup)
    if not root:
        root = soup
    for pre in root.find_all("pre"):
        code_tag = pre.find("code")
        code_text = code_tag.get_text() if code_tag else pre.get_text()
        code_text = code_text.replace("\r\n", "\n")
        code_text = re.sub(r"\n{3,}", "\n\n", code_text).strip("\n")
        pre.replace_with(f"\n```\n{code_text}\n```\n")
    for c in root.find_all("code"):
        c_text = c.get_text().replace("`", "\\`")
        c.replace_with(f"`{c_text}`")
    text_output = root.get_text("\n")
    text_output = re.sub(r"\n{3,}", "\n\n", text_output).strip()
    return text_output or "๋ณธ๋ฌธ์„ ์ถ”์ถœํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."

# -----------------------------
# Sentence splitting
# -----------------------------
_SENT_SPLIT_REGEX = re.compile(r"(?<=[\.!\?ใ€‚๏ผ๏ผŸ])\s+|\n+")

def split_sentences(text: str):
    parts = _SENT_SPLIT_REGEX.split(text)
    return [s.strip() for s in parts if s.strip()]

# -----------------------------
# Summarize
# -----------------------------
def summarize_text(text: str, max_sentences: int = 3) -> str:
    text = (text or "").strip()
    if not text:
        return ""
    if HAS_SUMMA:
        try:
            candidate = textrank_summarize(text, split=True)
            if candidate:
                return "\n".join(candidate[:max_sentences]).strip()
        except Exception:
            pass
    sents = split_sentences(text)
    if not sents:
        return text[:800]
    return "\n".join(sents[:max_sentences]).strip()

# -----------------------------
# Handlers
# -----------------------------
def handle_html(url: str) -> str:
    url = (url or "").strip()
    if not url:
        return "โŒ URL์„ ์ž…๋ ฅํ•˜์„ธ์š”."
    try:
        return fetch_html(url)
    except Exception as e:
        return f"์—๋Ÿฌ: {e}"

def handle_text(url: str) -> str:
    url = (url or "").strip()
    if not url:
        return "โŒ URL์„ ์ž…๋ ฅํ•˜์„ธ์š”."
    try:
        html = fetch_html(url)
        return html_to_text_preserve_code(html)
    except Exception as e:
        return f"์—๋Ÿฌ: {e}"

def handle_summary(url: str, sent_n: int) -> str:
    url = (url or "").strip()
    if not url:
        return "โŒ URL์„ ์ž…๋ ฅํ•˜์„ธ์š”."
    try:
        html = fetch_html(url)
        text = html_to_text_preserve_code(html)
        if not text or text.startswith("๋ณธ๋ฌธ์„ ์ถ”์ถœํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."):
            return text
        summary = summarize_text(text, max_sentences=int(sent_n))
        if not summary:
            return "์š”์•ฝ์„ ์ƒ์„ฑํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."
        return f"๐Ÿ“ ์ž๋™์š”์•ฝ ({sent_n}๋ฌธ์žฅ)\n\n{summary}"
    except Exception as e:
        return f"์—๋Ÿฌ: {e}"

# -----------------------------
# ์ด๋ฏธ์ง€ ์ „์ฒ˜๋ฆฌ + PaddleOCR
# -----------------------------
def preprocess_image(img):
    if isinstance(img, np.ndarray):
        arr = img
    else:
        arr = np.array(img)

    gray = cv2.cvtColor(arr, cv2.COLOR_RGB2GRAY)
    # ๋Œ€๋น„ ๊ฐ•ํ™” (์ด์ง„ํ™”)
    _, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    # ํฌ๊ธฐ ํ‚ค์šฐ๊ธฐ
    h, w = thresh.shape
    if h < 600:
        scale = 600 / h
        thresh = cv2.resize(thresh, None, fx=scale, fy=scale, interpolation=cv2.INTER_LINEAR)
    return thresh

ocr = PaddleOCR(use_angle_cls=True, lang='korean')  # ํ•œ๊ตญ์–ด+์˜์–ด ์ง€์›

def handle_image(img) -> str:
    if img is None:
        return "โŒ ์ด๋ฏธ์ง€๋ฅผ ์—…๋กœ๋“œํ•˜์„ธ์š”."
    try:
        proc_img = preprocess_image(img)
        results = ocr.ocr(proc_img)
        if not results or not results[0]:
            return "ํ…์ŠคํŠธ๋ฅผ ์ถ”์ถœํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."

        lines = []
        for res in results[0]:
            if len(res) == 2 and isinstance(res[1], tuple):
                txt, conf = res[1]
                lines.append(f"{txt} (conf:{conf:.2f})")
        return "\n".join(lines) if lines else "ํ…์ŠคํŠธ๋ฅผ ์ถ”์ถœํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."
    except Exception as e:
        return f"์—๋Ÿฌ: {e}"

# -----------------------------
# UI
# -----------------------------
with gr.Blocks(css="""
  #container { max-width: 920px; margin: 0 auto; }
  .small { color:#666; font-size:14px; }
""") as demo:
    gr.Markdown("## URL โ†’ HTML/ํ…์ŠคํŠธ/์š”์•ฝ + ์ด๋ฏธ์ง€ OCR (PaddleOCR + ์ „์ฒ˜๋ฆฌ)", elem_id="container")

    with gr.Row():
        url_input = gr.Textbox(label="URL", placeholder="https://example.com", scale=4)
    gr.Markdown('<div class="small">URL์„ ์ž…๋ ฅํ•˜๊ณ  ์›ํ•˜๋Š” ๋™์ž‘ ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด์„ธ์š”.</div>')

    with gr.Row():
        btn_html = gr.Button("์›๋ณธ HTML ๋ณด๊ธฐ", scale=1)
        btn_text = gr.Button("ํ…์ŠคํŠธ ๋ณด๊ธฐ (์ฝ”๋“œ๋ธ”๋Ÿญ ๋ณด์กด)", scale=1)
    with gr.Row():
        sent_n = gr.Slider(1, 8, value=3, step=1, label="์š”์•ฝ ๋ฌธ์žฅ ์ˆ˜")
        btn_sum = gr.Button("์ž๋™์š”์•ฝ ๋ณด๊ธฐ", scale=1)

    gr.Markdown("### ์ด๋ฏธ์ง€ ์—…๋กœ๋“œ โ†’ OCR (PaddleOCR + ์ „์ฒ˜๋ฆฌ)")
    with gr.Row():
        img_input = gr.Image(type="numpy", label="์ด๋ฏธ์ง€ ์—…๋กœ๋“œ")
        btn_img = gr.Button("์ด๋ฏธ์ง€ OCR ์‹คํ–‰", scale=1)

    output = gr.Textbox(label="๊ฒฐ๊ณผ", lines=26, show_copy_button=True)

    btn_html.click(fn=handle_html, inputs=url_input, outputs=output)
    btn_text.click(fn=handle_text, inputs=url_input, outputs=output)
    btn_sum.click(fn=handle_summary, inputs=[url_input, sent_n], outputs=output)
    btn_img.click(fn=handle_image, inputs=img_input, outputs=output)

if __name__ == "__main__":
    demo.launch()