Oh Gyuhyeok
Fix bug fix (#4)
0a21623 unverified
import logging
import os
import warnings
import gradio as gr
import pandas as pd
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
from langchain_upstage import ChatUpstage
from rapidfuzz import process
import pymupdf
warnings.filterwarnings("ignore")
UPSTAGE_API_KEY = os.environ["UPSTAGE_API_KEY"]
TITLE = "์‰ฌ์šด ์ „๋ฌธ์šฉ์–ด ๋ฒˆ์—ญ๊ธฐ"
DESCRIPTION = """
์šฐ๋ฆฌ๊ฐ€ easyword.kr์— ๋ชจ์€ ์‰ฌ์šด ์ „๋ฌธ์šฉ์–ด๋“ค์„ ์‚ฌ์šฉํ•˜์—ฌ, ์ž๋™์œผ๋กœ ๋ฌธ์žฅ์„ ๋ฒˆ์—ญํ•ด์ค๋‹ˆ๋‹ค.
๋ฒˆ์—ญ์„ ์ž๋™์œผ๋กœ ํ•˜๊ธฐ ์œ„ํ•ด ์—…์Šคํ…Œ์ด์ง€์˜ Solar ๋Œ€ํ˜• ์–ธ์–ด ๋ชจ๋ธ (large language model, LLM)์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.
์šฐ๋ฆฌ ๋ฒˆ์—ญ๊ธฐ๋Š” ์ตœ๋Œ€ํ•œ ์‰ฌ์šด ์ „๋ฌธ์šฉ์–ด ์›์น™์„ ๋”ฐ๋ฅด๋ฉฐ, ์›๋ฌธ ์ „๋ฌธ์šฉ์–ด๋Š” ๋ฒˆ์—ญ๋œ ์‰ฌ์šด๋ง ๋‹ค์Œ ๊ด„ํ˜ธ ์•ˆ์— ๋”ฐ๋ผ๋ถ™์ž…๋‹ˆ๋‹ค.
""".strip()
LIMIT_FACTOR = 2.5
SCORE_CUTOFF = 60.0
MAX_RETRIES = 4
logging.basicConfig(
filename=f"{__file__}.log",
filemode="a",
format="%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s",
datefmt="%H:%M:%S",
level=logging.DEBUG,
)
logger = logging.getLogger(__file__)
df = pd.read_csv("./dictionary.csv")
grouped_df = df.groupby("name").agg(lambda x: ",".join(map(str, x)))
grouped_df = grouped_df.drop(columns=["Unnamed: 0"])
def find_jargons(sentence: str, limit: int | None = None) -> list[str]:
if limit is None:
limit = int(len(sentence.split()) * LIMIT_FACTOR)
extracted = process.extract(
sentence, grouped_df.index, limit=limit, score_cutoff=SCORE_CUTOFF
)
return [v[0] for v in extracted]
def recommend_prompt(jargon: str) -> str:
return f"'{jargon}'์€ '{grouped_df.loc[jargon].name_trans}'๋กœ"
llm = ChatUpstage()
llm = llm | StrOutputParser()
def chainer(messages):
return ChatPromptTemplate.from_messages(messages) | llm | StrOutputParser()
SYSTEM_PROMPT = """
๋„ˆ๋Š” ์ปดํ“จํ„ฐ ๊ณผํ•™ ๋ฐ ๊ณตํ•™ ๋ถ„์•ผ์˜ ์ „๋ฌธ ์šฉ์–ด๋ฅผ ์‰ฌ์šด ์šฐ๋ฆฌ๋ง๋กœ ๋ฒˆ์—ญํ•ด์ฃผ๋Š” ๋ฒˆ์—ญ๊ฐ€์•ผ.
์ „๋ฌธ์šฉ์–ด์˜ ์˜๋ฏธ๋ฅผ ์ •ํ™•ํžˆ ์ดํ•ดํ•˜๊ณ , ๊ทธ ์˜๋ฏธ๊ฐ€ ์ •ํ™•ํžˆ ์ „๋‹ฌ๋˜๋Š” ์‰ฌ์šด๋ง์„ ์ฐพ์•„์•ผ ํ•ด.
์ง€๋ ˆ ๊ฒ๋จน๊ฒŒํ•˜๋Š” ์šฉ์–ด(๋ถˆํ•„์š”ํ•œ ํ•œ๋ฌธํˆฌ)๋ฅผ ํ”ผํ•˜๊ณ , ๊ฐ€๋Šฅํ•˜๋ฉด ์‰ฌ์šด๋ง์„ ์ฐพ์•„์•ผ ํ•ด.
์›๋ฌธ ์ „๋ฌธ์šฉ์–ด๋Š” ํ•ด๋‹น ์šฐ๋ฆฌ๋ง ๋‹ค์Œ์— ๊ด„ํ˜ธ์•ˆ์— ํ•ญ์ƒ ๋”ฐ๋ผ๋ถ™์—ฌ์•ผ ํ•ด.
๊ธฐ์กด์˜ ๊ถŒ์œ„์— ์–ฝ๋งค์ด์ง€ ์•Š๊ณ , ๊ธฐ์กด ์šฉ์–ด์‚ฌ์ „์ด๋‚˜ ์ด๋ฏธ ๋„๋ฆฌํผ์ง„ ์šฉ์–ด์ง€๋งŒ ์‰ฝ์ง€์•Š๋‹ค๋ฉด, ๋ณด๋‹ค ์‰ฌ์šด ์ „๋ฌธ์šฉ์–ด๋ฅผ ์ฐพ์•„์•ผ ํ•ด.
์ด๋•Œ, ๊ธฐ์กด์šฉ์–ด๋Š” ์›๋ฌธ ์ „๋ฌธ์šฉ์–ด์™€ ํ•จ๊ป˜ ๊ด„ํ˜ธ์•ˆ์— ๋”ฐ๋ผ๋ถ™์—ฌ์•ผ ํ•ด.
์‰ฌ์šด๋ง์€ ์ˆœ์ˆ˜ ์šฐ๋ฆฌ๋ง์„ ๋œปํ•˜์ง€ ์•Š์•„. ์™ธ๋ž˜์–ด๋ผ๋„ ๋„๋ฆฌ ์‰ฝ๊ฒŒ ๋ฐ›์•„๋“ค์—ฌ์ง„๋‹ค๋ฉด ์‚ฌ์šฉํ•ด.
"""
SAMPLE_SENTENCE = "In functional programming, continuation-passing style (CPS) is a style of programming in which control is passed explicitly in the form of a continuation."
SAMPLE_TRANSLATION = "๊ฐ’์ค‘์‹ฌ ํ”„๋กœ๊ทธ๋ž˜๋ฐ[functional programming]์—์„œ, ๋งˆ์ €ํ• ์ผ ์ „๋‹ฌํ•˜๊ธฐ[continuation-passing style, CPS]๋Š” ์‹คํ–‰ํ๋ฆ„[control]์ด ์ง์ ‘ ๋งˆ์ €ํ• ์ผ[continutaion]์˜ ํ˜•ํƒœ๋กœ ์ „๋‹ฌ๋˜๋Š” ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์Šคํƒ€์ผ์ด๋‹ค."
def translate(sentence: str) -> str:
# remove "{", "}" in sentence.
# sentence = sentence.replace("{", "").replace("}", "")
messages = [
SystemMessage(content=SYSTEM_PROMPT),
HumanMessage(
content=f"์ „๋ฌธ ์šฉ์–ด๋ฅผ ๋ฒˆ์—ญํ•  ๋•Œ๋Š” ๋ฐ˜๋“œ์‹œ ์›์–ด๋ฅผ ๊ด„ํ˜ธ[]์— ๋„ฃ์–ด์„œ ๋”ฐ๋ผ ๋ถ™์—ฌ์•ผ ํ•ด. ์ด ๋ฌธ์žฅ์„ ๋ฒˆ์—ญํ•ด์ค˜: '{SAMPLE_SENTENCE}'"
),
AIMessage(content=SAMPLE_TRANSLATION),
HumanMessage(
content=f"์ „๋ฌธ ์šฉ์–ด๋ฅผ ๋ฒˆ์—ญํ•  ๋•Œ๋Š” ๋ฐ˜๋“œ์‹œ ์›์–ด๋ฅผ ๊ด„ํ˜ธ[]์— ๋„ฃ์–ด์„œ ๋”ฐ๋ผ ๋ถ™์—ฌ์•ผ ํ•ด. ์ด ๋ฌธ์žฅ์„ ๋ฒˆ์—ญํ•ด์ค˜: '{sentence}'"
),
]
initial_translation = llm.invoke(messages)
logger.info(initial_translation)
used_jargons = find_jargons(sentence)
messages += [
AIMessage(content=initial_translation),
HumanMessage(
content=f"๋ฐฉ๊ธˆ ๋ฒˆ์—ญํ•œ ๋ฌธ์žฅ์—์„œ '{', '.join(used_jargons)}' ์ค‘ ์‚ฌ์šฉํ•œ ์šฉ์–ด๊ฐ€ ์žˆ๋‹ค๋ฉด, ์–ด๋–ค ์šฉ์–ด๋“ค๋กœ ๋ฒˆ์—ญํ–ˆ๋Š”์ง€ ๋งํ•ด์ค˜. ์‚ฌ์šฉํ•˜์ง€ ์•Š์€ ์šฉ์–ด๋“ค์€ ๋ฌด์‹œํ•ด๋„ ๋ผ."
),
]
response = llm.invoke(messages)
logger.info(response)
recommendations = ", ".join(recommend_prompt(jargon) for jargon in used_jargons)
messages += [
AIMessage(content=response),
HumanMessage(
content=f"์ด๋ฒˆ์—๋Š” ์ฒ˜์Œ ๋ฒˆ์—ญํ–ˆ๋˜ ๋ฌธ์žฅ์„ '{sentence}'๋ฅผ ๋‹ค์‹œ ๋ฒˆ์—ญํ•ด์ฃผ๋Š”๋ฐ, ๋‹ค์Œ ๋ชฉ๋ก์— ๋‚˜์˜จ ์‰ฌ์šด ์ „๋ฌธ์šฉ์–ด ๋ฒˆ์—ญ ์˜ˆ์‹œ๋ฅผ ์ฐธ๊ณ ํ•ด์„œ ๋ฒˆ์—ญ์„ ํ•ด์ค˜: '{recommendations}' ์‚ฌ์šฉํ•˜์ง€ ์•Š์€ ์šฉ์–ด๋“ค์€ ๋ฌด์‹œํ•ด๋„ ๋ผ. ์ถ”๊ฐ€ ์„ค๋ช… ์—†์ด ๋ฌธ์žฅ๋งŒ ๋ฒˆ์—ญํ•ด. ์‚ฌ์šฉ๋œ ์›์–ด๋ฅผ ์šฉ์–ด ๋ฐ”๋กœ ๋’ค์— ๊ด„ํ˜ธ []์— ๋„ฃ์–ด์„œ ๋”ฐ๋ผ ๋ถ™์—ฌ์ค˜."
),
]
refined_translation = llm.invoke(messages)
logger.info(refined_translation)
retries = 0
while "[" not in refined_translation or "]" not in refined_translation:
retries += 1
if retries > MAX_RETRIES:
break
messages += [
AIMessage(content=refined_translation),
HumanMessage(
content=f"์ „๋ฌธ์šฉ์–ด๋ฅผ ๋ฒˆ์—ญํ–ˆ์œผ๋ฉด ๋ฐ˜๋“œ์‹œ ์›์–ด๋ฅผ ๊ด„ํ˜ธ[]์— ๋„ฃ์–ด์„œ ๋”ฐ๋ผ ๋ถ™์—ฌ์•ผ ํ•ด. '์‹คํ–‰ํ๋ฆ„[control]'์ฒ˜๋Ÿผ. ๋ฐฉ๊ธˆ ๋ฒˆ์—ญํ•œ '{refined_translation}'์—์„œ, ์›๋ž˜ ๋ฌธ์žฅ '{sentence}'์— ์‚ฌ์šฉ๋œ ์›์–ด๋ฅผ ์šฉ์–ด ๋ฐ”๋กœ ๋’ค์— ๊ด„ํ˜ธ []์— ๋„ฃ์–ด์„œ ๋”ฐ๋ผ ๋ถ™์—ฌ์ค˜."
),
]
try:
refined_translation = llm.invoke(messages)
except Exception as e:
logger.error(e)
break
logger.info(refined_translation)
refined_translation = refined_translation.replace("[", "(").replace("]", ")")
return refined_translation
class PDFFile:
def __init__(self):
self.file_list = []
def read_pdf(self, file_path: str) -> str:
# Open the PDF file
document = pymupdf.open(file_path)
text = ""
# Iterate through the pages
for page_num in range(len(document)):
# Extract text from each page
page = document.load_page(page_num)
text += page.get_text()
# Close the PDF document
document.close()
return text
def remove_line_breaks(self, text: str) -> list[str]:
# remove only single line breaks, not paragraphs
# find line breaks and it is not followed by a period
for i in range(len(text)):
if i == 0 or i == len(text) - 1:
continue
if text[i] == "\n" and text[i - 1] != "." and text[i + 1] != "\n":
text = text[:i] + " " + text[i + 1 :]
return text
def upload_file(self, file_path: str) -> list[str]:
self.file_list.append(file_path)
return self.file_list
def transalte_pdf(
self,
remove_line_breaks: bool,
save_before_translation: bool,
) -> str:
if not self.file_list:
return "No file uploaded yet."
file_out_list = []
for file in self.file_list:
directory = os.path.dirname(file)
filename = os.path.basename(file)
# remove extension
filename = ".".join(filename.split(".")[:-1])
pdf_text = self.read_pdf(file)
if remove_line_breaks:
pdf_text = self.remove_line_breaks(pdf_text)
if save_before_translation:
with open(f"{directory}/{filename}_pre.txt", "w") as f:
f.write(pdf_text)
file_out_list.append(f"{directory}/{filename}_pre.txt")
# translation = translate(pdf_text)
# Translation with divide and conquer with 50 sentences
translation = ""
# seperate the text into sentences
sentences = pdf_text.split(".")
for i in range(0, len(sentences), 50):
translation += translate(".".join(sentences[i : i + 50])) + ". "
with open(f"{directory}/{filename}_translated.txt", "w") as f:
f.write(translation)
file_out_list.append(f"{directory}/{filename}_translated.txt")
self.file_list = []
# Zip the files
# import zipfile
# with zipfile.ZipFile(f"{directory}/translated_files.zip", "w") as z:
# for file in file_out_list:
# z.write(file)
# return f"{directory}/translated_files.zip"
return file_out_list
with gr.Blocks() as demo:
with gr.Tab("TEXT"):
chatbot = gr.Interface(
fn=translate,
inputs=gr.Textbox(label="Enter your text"),
outputs=[gr.Textbox(label="Translation")],
examples=[
"In functional programming, continuation-passing style (CPS) is a style of programming in which control is passed explicitly in the form of a continuation.",
"In computer science, abstract interpretation is a theory of sound approximation of the semantics of computer programs, based on monotonic functions over ordered sets, especially lattices.",
"In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions",
"Lambda calculus (also written as ฮป-calculus) is a formal system in mathematical logic for expressing computation based on function abstraction and application using variable binding and substitution",
"Operational semantics is a category of formal programming language semantics in which certain desired properties of a program, such as correctness, safety or security, are verified by constructing proofs from logical statements about its execution and procedures, rather than by attaching mathematical meanings to its terms (denotational semantics).",
"In computing and computer programming, exception handling is the process of responding to the occurrence of exceptions โ€“ anomalous or exceptional conditions requiring special processing โ€“ during the execution of a program.",
"The term redex, short for reducible expression, refers to subterms that can be reduced by one of the reduction rules.",
],
title=TITLE,
description=DESCRIPTION,
)
with gr.Tab("PDF"):
pdf_file = PDFFile()
upload_button = gr.UploadButton(
label="Upload PDF",
file_types=[".pdf"],
)
upload_file_list_box = gr.File(label="Uploaded Files")
upload_button.upload(pdf_file.upload_file, upload_button, upload_file_list_box)
run_translator = gr.Interface(
fn=pdf_file.transalte_pdf,
inputs=[
gr.Checkbox(label="Remove line breaks"),
gr.Checkbox(label="Save before translation"),
],
outputs=[gr.File(label="Download Translated Files")],
)
def main():
demo.launch(share=True)
if __name__ == "__main__":
main()