File size: 9,956 Bytes
f72ee60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import os
import time
from openai import OpenAI
from dotenv import load_dotenv
from prompts import (
    USER_PROMPT,
    WRAPPER_PROMPT,
    CALL_1_SYSTEM_PROMPT,
    CALL_2_SYSTEM_PROMPT,
    CALL_3_SYSTEM_PROMPT,
)
import difflib
import csv
from concurrent.futures import ThreadPoolExecutor, as_completed
from threading import Lock
import threading

load_dotenv()

BASE_URL = "https://api.upstage.ai/v1"
API_KEY = os.getenv("OPENAI_API_KEY")

client = OpenAI(api_key=API_KEY, base_url=BASE_URL)


# Load vocabulary for rule-based correction
def load_vocabulary():
    vocabulary = {}
    with open("Vocabulary.csv", "r", encoding="utf-8-sig") as f:
        reader = csv.DictReader(f)
        for row in reader:
            # Debug: print first row to check column names
            if len(vocabulary) == 0:
                print("CSV columns:", list(row.keys()))
            vocabulary[row["original"]] = row["corrected"]
    return vocabulary


VOCABULARY = load_vocabulary()

# ์Šค๋ ˆ๋“œ ์•ˆ์ „ํ•œ ์นด์šดํ„ฐ
counter_lock = Lock()
processed_count = 0
total_bulks = 0


def apply_vocabulary_correction(text):
    for original, corrected in VOCABULARY.items():
        text = text.replace(original, corrected)
    return text


def create_bulk_paragraphs(text, max_chars=500):
    """
    ํ…์ŠคํŠธ๋ฅผ 500์ž ๊ธฐ์ค€์œผ๋กœ ๋ฒŒํฌ ๋‹จ์œ„๋กœ ๋ถ„ํ• ํ•ฉ๋‹ˆ๋‹ค.

    Args:
        text: ์ž…๋ ฅ ํ…์ŠคํŠธ
        max_chars: ์ตœ๋Œ€ ๋ฌธ์ž ์ˆ˜ (๊ธฐ๋ณธ๊ฐ’: 500)

    Returns:
        List[str]: ๋ฒŒํฌ ๋‹จ์œ„๋กœ ๋ถ„ํ• ๋œ ํ…์ŠคํŠธ ๋ฆฌ์ŠคํŠธ
    """
    paragraphs = [p.strip() for p in text.split("\n") if p.strip()]

    if not paragraphs:
        return []

    bulks = []
    current_bulk = []
    current_length = 0

    for para in paragraphs:
        para_length = len(para)

        # ํ˜„์žฌ ๋ฌธ๋‹จ์ด 500์ž๋ฅผ ์ดˆ๊ณผํ•˜๋Š” ๊ฒฝ์šฐ
        if para_length > max_chars:
            # ํ˜„์žฌ ๋ฒŒํฌ๊ฐ€ ์žˆ๋‹ค๋ฉด ์ถ”๊ฐ€
            if current_bulk:
                bulks.append("\n".join(current_bulk))
                current_bulk = []
                current_length = 0

            # ๊ธด ๋ฌธ๋‹จ์€ ๋‹จ๋…์œผ๋กœ ์ฒ˜๋ฆฌ
            bulks.append(para)
        else:
            # ํ˜„์žฌ ๋ฒŒํฌ์— ์ถ”๊ฐ€ํ–ˆ์„ ๋•Œ 500์ž๋ฅผ ์ดˆ๊ณผํ•˜๋Š” ๊ฒฝ์šฐ
            if (
                current_length + para_length + len(current_bulk) > max_chars
                and current_bulk
            ):
                # ํ˜„์žฌ ๋ฒŒํฌ๋ฅผ ์™„์„ฑํ•˜๊ณ  ์ƒˆ ๋ฒŒํฌ ์‹œ์ž‘
                bulks.append("\n".join(current_bulk))
                current_bulk = [para]
                current_length = para_length
            else:
                # ํ˜„์žฌ ๋ฒŒํฌ์— ์ถ”๊ฐ€
                current_bulk.append(para)
                current_length += para_length

    # ๋งˆ์ง€๋ง‰ ๋ฒŒํฌ ์ถ”๊ฐ€
    if current_bulk:
        bulks.append("\n".join(current_bulk))

    return bulks


def process_bulk(bulk_text, bulk_index, max_retries=3):
    """ํ•˜๋‚˜์˜ ๋ฒŒํฌ๋ฅผ ํŒŒ์ดํ”„๋ผ์ธ์œผ๋กœ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค. API ์—๋Ÿฌ์‹œ ์žฌํ˜ธ์ถœํ•ฉ๋‹ˆ๋‹ค."""
    global processed_count

    thread_id = threading.get_ident()
    start = time.time()

    for attempt in range(max_retries):
        try:
            # Step 0: Apply vocabulary correction to input
            step0 = apply_vocabulary_correction(bulk_text)
            proofread_result = call_proofread(step0)
            system_step1 = WRAPPER_PROMPT.format(system_prompt=CALL_1_SYSTEM_PROMPT)
            user_step1 = USER_PROMPT.format(original=step0, proofread=proofread_result)
            step1 = call_solar_pro2(system_step1, user_step1)
            step2 = call_solar_pro2(CALL_2_SYSTEM_PROMPT, step1)
            step3 = call_solar_pro2(CALL_3_SYSTEM_PROMPT, step2)
            # Step 4: Apply vocabulary correction to final output
            step4 = apply_vocabulary_correction(step3)

            elapsed = time.time() - start

            with counter_lock:
                processed_count += 1

            return {
                "bulk_index": bulk_index,
                "original": bulk_text,
                "final": step4,
                "processing_time": elapsed,
                "character_count": len(bulk_text),
                "attempts": attempt + 1,
            }

        except Exception as e:
            if attempt < max_retries - 1:
                print(
                    f"[Thread-{thread_id}] ๋ฒŒํฌ {bulk_index+1} ์‹œ๋„ {attempt+1} ์‹คํŒจ, ์žฌ์‹œ๋„: {e}"
                )
                time.sleep(1 * (attempt + 1))  # ์ ์ง„์  ๋Œ€๊ธฐ
                continue
            else:
                print(f"[Thread-{thread_id}] ๋ฒŒํฌ {bulk_index+1} ์ตœ์ข… ์‹คํŒจ: {e}")
                return {
                    "bulk_index": bulk_index,
                    "original": bulk_text,
                    "final": bulk_text,  # ์˜ค๋ฅ˜ ์‹œ ์›๋ณธ ๋ฐ˜ํ™˜
                    "processing_time": 0,
                    "character_count": len(bulk_text),
                    "error": str(e),
                    "attempts": max_retries,
                }


def call_solar_pro2(system, user, temperature=0.0, model_name="solar-pro2"):
    response = client.chat.completions.create(
        model=model_name,
        messages=[
            {"role": "system", "content": system},
            {"role": "user", "content": user},
        ],
        stream=False,
        temperature=temperature,
    )
    return response.choices[0].message.content


def call_proofread(paragraph):
    prompt = "์ž…๋ ฅ๋œ ๋ฌธ์„œ์— ๋Œ€ํ•œ ๊ต์—ด ๊ฒฐ๊ณผ๋ฅผ ์ƒ์„ฑํ•ด ์ฃผ์„ธ์š”."
    response = client.chat.completions.create(
        model="ft:solar-news-correction",
        messages=[
            {"role": "system", "content": prompt},
            {"role": "user", "content": paragraph},
        ],
        stream=False,
        temperature=0.0,
    )
    return response.choices[0].message.content


def highlight_diff(original, corrected):
    matcher = difflib.SequenceMatcher(None, original, corrected)
    result_html = []
    for tag, i1, i2, j1, j2 in matcher.get_opcodes():
        if tag == "equal":
            result_html.append(f"<span>{original[i1:i2]}</span>")
        elif tag == "replace":
            result_html.append(
                f'<span style="background:#ffecec;text-decoration:line-through;">{original[i1:i2]}</span>'
            )
            result_html.append(
                f'<span style="background:#e6ffec;">{corrected[j1:j2]}</span>'
            )
        elif tag == "delete":
            result_html.append(
                f'<span style="background:#ffecec;text-decoration:line-through;">{original[i1:i2]}</span>'
            )
        elif tag == "insert":
            result_html.append(
                f'<span style="background:#e6ffec;">{corrected[j1:j2]}</span>'
            )
    return "".join(result_html)


def process_text_parallel(input_text, max_workers=10):
    """ํ…์ŠคํŠธ๋ฅผ ๋ฒŒํฌ ๋‹จ์œ„๋กœ ๋ณ‘๋ ฌ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค."""
    global processed_count, total_bulks

    # ๋ฒŒํฌ ์ƒ์„ฑ
    bulks = create_bulk_paragraphs(input_text)
    total_bulks = len(bulks)
    processed_count = 0

    if not bulks:
        return []

    results = []

    # ๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        # ๋ชจ๋“  ๋ฒŒํฌ๋ฅผ ๋ณ‘๋ ฌ๋กœ ์ œ์ถœ
        future_to_bulk = {
            executor.submit(process_bulk, bulk, i): i for i, bulk in enumerate(bulks)
        }

        # ์™„๋ฃŒ๋œ ์ˆœ์„œ๋Œ€๋กœ ๊ฒฐ๊ณผ ์ˆ˜์ง‘
        for future in as_completed(future_to_bulk):
            try:
                result = future.result()
                results.append(result)
            except Exception as e:
                bulk_index = future_to_bulk[future]
                print(f"๋ฒŒํฌ {bulk_index+1} ์ฒ˜๋ฆฌ ์ค‘ ์˜ˆ์™ธ ๋ฐœ์ƒ: {e}")
                results.append(
                    {
                        "bulk_index": bulk_index,
                        "original": bulks[bulk_index],
                        "final": bulks[bulk_index],
                        "processing_time": 0,
                        "character_count": len(bulks[bulk_index]),
                        "error": str(e),
                    }
                )

    # ๋ฒŒํฌ ์ธ๋ฑ์Šค ์ˆœ์„œ๋Œ€๋กœ ์ •๋ ฌ
    results.sort(key=lambda x: x["bulk_index"])

    return results


def process(paragraph):
    start = time.time()
    # Step 0: Apply vocabulary correction to input
    step0 = apply_vocabulary_correction(paragraph)
    proofread_result = call_proofread(step0)
    system_step1 = WRAPPER_PROMPT.format(system_prompt=CALL_1_SYSTEM_PROMPT)
    user_step1 = USER_PROMPT.format(original=step0, proofread=proofread_result)
    step1 = call_solar_pro2(system_step1, user_step1)
    step2 = call_solar_pro2(CALL_2_SYSTEM_PROMPT, step1)
    step3 = call_solar_pro2(CALL_3_SYSTEM_PROMPT, step2)
    # Step 4: Apply vocabulary correction to final output
    step4 = apply_vocabulary_correction(step3)
    elapsed = time.time() - start
    return step4, highlight_diff(paragraph, step4)


def demo_fn(input_text):
    # ๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ๋กœ ๋ฒŒํฌ ๋‹จ์œ„๋กœ ์ฒ˜๋ฆฌ
    bulk_results = process_text_parallel(input_text, max_workers=10)

    if not bulk_results:
        return input_text, input_text

    # ๊ฒฐ๊ณผ ํ•ฉ์น˜๊ธฐ
    final_texts = [r["final"] for r in bulk_results]
    final_result = "\n".join(final_texts)

    # ํ•˜์ด๋ผ์ดํŠธ ์ƒ์„ฑ
    highlighted = highlight_diff(input_text, final_result)

    return final_result, highlighted


with gr.Blocks() as demo:
    gr.Markdown("# ๊ต์—ด ๋ชจ๋ธ ๋ฐ๋ชจ")
    input_text = gr.Textbox(
        label="์›๋ฌธ ์ž…๋ ฅ", lines=10, placeholder="๋ฌธ๋‹จ ๋‹จ์œ„๋กœ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”."
    )
    btn = gr.Button("๊ต์—ดํ•˜๊ธฐ")
    output_corrected = gr.Textbox(label="๊ต์—ด ๊ฒฐ๊ณผ", lines=10)
    output_highlight = gr.HTML(label="์ˆ˜์ •๋œ ๋ถ€๋ถ„ ๊ฐ•์กฐ")

    btn.click(
        fn=demo_fn, inputs=input_text, outputs=[output_corrected, output_highlight]
    )

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