File size: 17,932 Bytes
a81b34f f72ee60 1f7c2d4 f72ee60 1f7c2d4 f72ee60 cb215c9 1f7c2d4 f72ee60 4d94f97 1f7c2d4 f72ee60 bb60938 f72ee60 bb60938 f72ee60 bb60938 f72ee60 bb60938 f72ee60 bb60938 f72ee60 bb60938 f72ee60 bb60938 f72ee60 bb60938 f72ee60 bb60938 f72ee60 bb60938 f72ee60 bb60938 f72ee60 4b70df2 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 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 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 |
import gradio as gr
import os
import time
import re
import json
from concurrent.futures import ThreadPoolExecutor, as_completed
from openai import OpenAI
import random
from concurrent.futures import TimeoutError as FuturesTimeoutError
from openai import APIStatusError, APITimeoutError, APIConnectionError
import traceback
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 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) # 60์ด ํ๋ ํ์์์
import re
import re
import re
def postprocess_pronoun(text: str) -> str:
"""
'์ด์ฌ๋ช
๋ํ'๊ฐ ํฌํจ๋ ๋ชจ๋ ๋จ์ด๋ฅผ '์ด์ฌ๋ช
๋ํต๋ น'์ผ๋ก ๊ต์ฒดํ๋ฉฐ,
๋ค๋ฐ๋ฅด๋ ์กฐ์ฌ๊ฐ ์์ ๊ฒฝ์ฐ ํจ๊ป ์์ ํฉ๋๋ค.
"""
# ํํ๊ฐ '๋ฐ๋์ด์ผ ํ๋' ์กฐ์ฌ/์ด๋ฏธ๋ง ์ ์
correction_map = {
'๋': '์', '๊ฐ': '์ด', '๋ฅผ': '์', '์': '๊ณผ', '๋ก': '์ผ๋ก',
'์ฌ': '์ด์ฌ', '๋ผ': '์ด๋ผ', '๋': '์ด๋',
'๋ค': '์ด๋ค', '์๋ค': '์ด์๋ค', '๋ผ๋ฉด': '์ด๋ผ๋ฉด', '๋ผ์': '์ด๋ผ์'
}
# ์ ๊ท์์ด ์ฐพ์์ผ ํ ๋ชจ๋ ์กฐ์ฌ/์ด๋ฏธ ๋ชฉ๋ก
all_target_particles = list(correction_map.keys()) + ['๋ก๋ถํฐ', '๋ง', '๋', '๊ป์']
particle_pattern = "|".join(re.escape(p) for p in all_target_particles)
# ์ต์ข
์ ๊ท์: ์์ ์ฅ์น(?!...)๋ฅผ ์ ๊ฑฐํ์ฌ ๋ชจ๋ ๊ฒฝ์ฐ๋ฅผ ์ฐพ์๋
๋๋ค.
regex = re.compile(f"(์ด์ฌ๋ช
\s*๋ํ)({particle_pattern})?")
def replace_func(match):
particle = match.group(2)
new_phrase = "์ด์ฌ๋ช
๋ํต๋ น"
if particle:
new_phrase += correction_map.get(particle, particle)
return new_phrase
return regex.sub(replace_func, text)
def extract_json_from_text(text):
"""
ํ
์คํธ์์ JSON ๋ถ๋ถ์ ์ถ์ถํฉ๋๋ค.
์ฌ๋ฌ ํจํด์ ์๋ํ์ฌ JSON์ ์ฐพ์ต๋๋ค.
Args:
text: JSON์ด ํฌํจ๋ ํ
์คํธ
Returns:
dict: ํ์ฑ๋ JSON ๊ฐ์ฒด ๋๋ None
"""
if not text or not text.strip():
return None
# ํ
์คํธ ์ ๋ฆฌ (์๋ค ๊ณต๋ฐฑ ์ ๊ฑฐ)
text = text.strip()
# ํจํด 1: ```json ... ``` ํํ
json_code_block_pattern = r'```json\s*(.*?)\s*```'
match = re.search(json_code_block_pattern, text, re.DOTALL)
if match:
try:
extracted = match.group(1).strip()
if extracted:
return json.loads(extracted)
except json.JSONDecodeError:
pass
# ํจํด 2: ``` ... ``` ํํ (json ํ๊ทธ ์์ด)
code_block_pattern = r'```\s*(.*?)\s*```'
match = re.search(code_block_pattern, text, re.DOTALL)
if match:
try:
extracted = match.group(1).strip()
if extracted:
return json.loads(extracted)
except json.JSONDecodeError:
pass
# ํจํด 3: {๋ก ์์ํ๊ณ }๋ก ๋๋๋ JSON ๊ฐ์ฒด
json_object_pattern = r'\{.*\}'
match = re.search(json_object_pattern, text, re.DOTALL)
if match:
try:
extracted = match.group(0).strip()
if extracted:
return json.loads(extracted)
except json.JSONDecodeError:
pass
# ํจํด 4: [๋ก ์์ํ๊ณ ]๋ก ๋๋๋ JSON ๋ฐฐ์ด
json_array_pattern = r'\[.*\]'
match = re.search(json_array_pattern, text, re.DOTALL)
if match:
try:
extracted = match.group(0).strip()
if extracted:
return json.loads(extracted)
except json.JSONDecodeError:
pass
# ํจํด 5: ์ ์ฒด ํ
์คํธ๊ฐ JSON์ธ ๊ฒฝ์ฐ
try:
if text.startswith('{') or text.startswith('['):
return json.loads(text)
except json.JSONDecodeError:
pass
return None
# 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, article_info=""):
"""
ํ๋์ ๋ฒํฌ๋ฅผ ํ์ดํ๋ผ์ธ์ผ๋ก ์ฒ๋ฆฌํฉ๋๋ค.
API ์๋ฌ ๋ฐ์ ์, ๋ง์ง๋ง์ผ๋ก ์ฑ๊ณตํ ๋จ๊ณ์ ๊ฒฐ๊ณผ๋ฌผ์ ๋ฐํํฉ๋๋ค.
"""
global processed_count
thread_id = threading.get_ident()
start = time.time()
# ๊ฐ ๋จ๊ณ์ ๊ฒฐ๊ณผ๋ฅผ ์ ์ฅํ ๋ณ์
step0, proofread_result, step1, step1_explanation, step2, step2_explanation, step3, step4, step5 = (None,) * 9
# ์๋ฌ ๋ฐ์ ์ ๋ฐํํ ๋ง์ง๋ง ์ฑ๊ณต ๊ฒฐ๊ณผ๋ฌผ (์ด๊ธฐ๊ฐ์ ์๋ณธ ํ
์คํธ)
last_successful_output = bulk_text
for attempt in range(max_retries):
try:
# Step 0: ๋จ์ด์ฅ ๊ธฐ๋ฐ ๊ต์
step0 = apply_vocabulary_correction(bulk_text)
last_successful_output = step0
print(f"{article_info}[Thread-{thread_id}] Bulk {bulk_index+1} Attempt {attempt+1} - Calling proofread...")
proofread_result = call_proofread(step0)
# Step 1: Solar API ํธ์ถ 1
system_step1 = WRAPPER_PROMPT.format(system_prompt=CALL_1_SYSTEM_PROMPT)
user_step1 = USER_PROMPT.format(original=step0, proofread=proofread_result)
print(f"{article_info}[Thread-{thread_id}] Bulk {bulk_index+1} Attempt {attempt+1} - Calling step1...")
step1_json = call_solar_pro2(system_step1, user_step1)
try:
parsed_json = json.loads(step1_json)
step1 = parsed_json.get('output', step0) # ํ์ฑ ์ฑ๊ณต ์ output ํ๋ ์ฌ์ฉ, ์์ผ๋ฉด ์ด์ ๋จ๊ณ ๊ฒฐ๊ณผ
step1_explanation = parsed_json.get('explanation', '')
last_successful_output = step1
except json.JSONDecodeError:
print(f"{article_info}[Thread-{thread_id}] Bulk {bulk_index+1} Attempt {attempt+1} - Step1 JSON ํ์ฑ ์คํจ. ์ถ์ถ ์๋...")
extracted_json = extract_json_from_text(step1_json)
if extracted_json and 'output' in extracted_json:
step1 = extracted_json['output']
step1_explanation = extracted_json.get('explanation', '')
last_successful_output = step1
print(f"{article_info}[Thread-{thread_id}] Bulk {bulk_index+1} Attempt {attempt+1} - JSON ์ถ์ถ ์ฑ๊ณต")
else:
step1 = step0 # ์ถ์ถ๋ ์คํจํ๋ฉด ์ด์ ๋จ๊ณ ๊ฒฐ๊ณผ ์ฌ์ฉ
step1_explanation = ""
print(f"{article_info}[Thread-{thread_id}] Bulk {bulk_index+1} Attempt {attempt+1} - JSON ์ถ์ถ ์คํจ")
# Step 2: Solar API ํธ์ถ 2
print(f"{article_info}[Thread-{thread_id}] Bulk {bulk_index+1} Attempt {attempt+1} - Calling step2...")
step2_json = call_solar_pro2(CALL_2_SYSTEM_PROMPT, step1)
try:
parsed_json = json.loads(step2_json)
step2 = parsed_json.get('output', step1)
step2_explanation = parsed_json.get('explanation', '')
last_successful_output = step2
except json.JSONDecodeError:
print(f"{article_info}[Thread-{thread_id}] Bulk {bulk_index+1} Attempt {attempt+1} - Step2 JSON ํ์ฑ ์คํจ. ์ถ์ถ ์๋...")
extracted_json = extract_json_from_text(step2_json)
if extracted_json and 'output' in extracted_json:
step2 = extracted_json['output']
step2_explanation = extracted_json.get('explanation', '')
last_successful_output = step2
print(f"{article_info}[Thread-{thread_id}] Bulk {bulk_index+1} Attempt {attempt+1} - JSON ์ถ์ถ ์ฑ๊ณต")
else:
step2 = step1
step2_explanation = ""
print(f"{article_info}[Thread-{thread_id}] Bulk {bulk_index+1} Attempt {attempt+1} - JSON ์ถ์ถ ์คํจ")
# Step 3: Solar API ํธ์ถ 3
print(f"{article_info}[Thread-{thread_id}] Bulk {bulk_index+1} Attempt {attempt+1} - Calling step3...")
step3_json = call_solar_pro2(CALL_3_SYSTEM_PROMPT, step2)
try:
parsed_json = json.loads(step3_json)
step3 = parsed_json.get('output', step2)
last_successful_output = step3
except json.JSONDecodeError:
print(f"{article_info}[Thread-{thread_id}] Bulk {bulk_index+1} Attempt {attempt+1} - Step3 JSON ํ์ฑ ์คํจ. ์ถ์ถ ์๋...")
extracted_json = extract_json_from_text(step3_json)
if extracted_json and 'output' in extracted_json:
step3 = extracted_json['output']
last_successful_output = step3
print(f"{article_info}[Thread-{thread_id}] Bulk {bulk_index+1} Attempt {attempt+1} - JSON ์ถ์ถ ์ฑ๊ณต")
else:
step3 = step2
print(f"{article_info}[Thread-{thread_id}] Bulk {bulk_index+1} Attempt {attempt+1} - JSON ์ถ์ถ ์คํจ")
# Step 4: ๋จ์ด์ฅ ๊ธฐ๋ฐ ๊ต์
step4 = apply_vocabulary_correction(step3)
# Step 5: ๋๋ช
์ฌ ํ์ฒ๋ฆฌ
step5 = postprocess_pronoun(step4)
last_successful_output = step5
elapsed = time.time() - start
with counter_lock:
processed_count += 1
# ๋ชจ๋ ๋จ๊ณ๊ฐ ์ฑ๊ณต์ ์ผ๋ก ์๋ฃ๋๋ฉด ๋ฃจํ ํ์ถ ๋ฐ ๊ฒฐ๊ณผ ๋ฐํ
return {
"bulk_index": bulk_index,
"original": bulk_text,
"final": last_successful_output,
"processing_time": elapsed,
"character_count": len(bulk_text),
"attempts": attempt + 1,
}
except Exception as e:
if attempt < max_retries - 1:
print(
f"{article_info}[Thread-{thread_id}] ๋ฒํฌ {bulk_index+1} ์๋ {attempt+1} ์คํจ, ์ฌ์๋: {type(e).__name__}"
)
time.sleep(1 * (attempt + 1)) # ์ฌ์๋ ์ ์ ์ ๋๊ธฐ
continue
else:
# ์ต์ข
์คํจ ์, ๋ง์ง๋ง์ผ๋ก ์ฑ๊ณตํ๋ ๊ฒฐ๊ณผ๋ฌผ์ final์ ๋ด์ ๋ฐํ
print(f"๐ฅ๐ฅ๐ฅ {article_info}[Thread-{thread_id}] ๋ฒํฌ {bulk_index+1} ์ต์ข
์คํจ! ๋ง์ง๋ง ์ฑ๊ณต ๊ฒฐ๊ณผ๋ฌผ์ ์ฌ์ฉํฉ๋๋ค. ๐ฅ๐ฅ๐ฅ")
traceback.print_exc() # ์์ธ ์๋ฌ ๋ก๊ทธ ์ถ๋ ฅ
return {
"bulk_index": bulk_index,
"original": bulk_text,
"final": last_successful_output, # โจ ํต์ฌ: ์๋ณธ ๋์ ๋ง์ง๋ง ์ฑ๊ณต ๊ฒฐ๊ณผ๋ฌผ์ ์ฌ์ฉ
"processing_time": time.time() - start,
"character_count": len(bulk_text),
"error": traceback.format_exc(),
"attempts": max_retries,
}
# ๋ฃจํ๊ฐ ์๊ธฐ์น ์๊ฒ ์ข
๋ฃ๋ ๊ฒฝ์ฐ๋ฅผ ๋๋นํ ๋ฐํ
return {"bulk_index": bulk_index, "final": bulk_text, "error": "unknown_flow_error"}
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-dev",
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 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()
|