File size: 7,546 Bytes
055e733
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
360c8b1
 
 
 
 
 
 
055e733
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be7c551
055e733
 
 
 
 
 
 
 
 
 
 
360c8b1
055e733
 
 
 
 
 
 
 
 
 
 
 
 
 
360c8b1
055e733
 
 
 
 
360c8b1
055e733
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
360c8b1
 
055e733
 
 
 
 
 
 
 
 
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
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_upstage import ChatUpstage
from rapidfuzz import process

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()


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:
    messages = [
        ("system", SYSTEM_PROMPT),
        (
            "human",
            f"์ „๋ฌธ ์šฉ์–ด๋ฅผ ๋ฒˆ์—ญํ•  ๋•Œ๋Š” ๋ฐ˜๋“œ์‹œ ์›์–ด๋ฅผ ๊ด„ํ˜ธ[]์— ๋„ฃ์–ด์„œ ๋”ฐ๋ผ ๋ถ™์—ฌ์•ผ ํ•ด. ์ด ๋ฌธ์žฅ์„ ๋ฒˆ์—ญํ•ด์ค˜: '{SAMPLE_SENTENCE}'",
        ),
        ("ai", SAMPLE_TRANSLATION),
        (
            "human",
            f"์ „๋ฌธ ์šฉ์–ด๋ฅผ ๋ฒˆ์—ญํ•  ๋•Œ๋Š” ๋ฐ˜๋“œ์‹œ ์›์–ด๋ฅผ ๊ด„ํ˜ธ[]์— ๋„ฃ์–ด์„œ ๋”ฐ๋ผ ๋ถ™์—ฌ์•ผ ํ•ด. ์ด ๋ฌธ์žฅ์„ ๋ฒˆ์—ญํ•ด์ค˜: '{sentence}'",
        ),
    ]

    initial_translation = chainer(messages).invoke({})
    logger.info(initial_translation)

    used_jargons = find_jargons(sentence)
    messages += [
        ("ai", initial_translation),
        (
            "human",
            f"๋ฐฉ๊ธˆ ๋ฒˆ์—ญํ•œ ๋ฌธ์žฅ์—์„œ '{', '.join(used_jargons)}' ์ค‘ ์‚ฌ์šฉํ•œ ์šฉ์–ด๊ฐ€ ์žˆ๋‹ค๋ฉด, ์–ด๋–ค ์šฉ์–ด๋“ค๋กœ ๋ฒˆ์—ญํ–ˆ๋Š”์ง€ ๋งํ•ด์ค˜. ์‚ฌ์šฉํ•˜์ง€ ์•Š์€ ์šฉ์–ด๋“ค์€ ๋ฌด์‹œํ•ด๋„ ๋ผ.",
        ),
    ]
    response = chainer(messages).invoke({})
    logger.info(response)

    recommendations = ", ".join(recommend_prompt(jargon) for jargon in used_jargons)

    messages += [
        ("ai", response),
        (
            "human",
            f"์ด๋ฒˆ์—๋Š” ์ฒ˜์Œ ๋ฒˆ์—ญํ–ˆ๋˜ ๋ฌธ์žฅ์„ '{sentence}'๋ฅผ ๋‹ค์‹œ ๋ฒˆ์—ญํ•ด์ฃผ๋Š”๋ฐ, ๋‹ค์Œ ๋ชฉ๋ก์— ๋‚˜์˜จ ์‰ฌ์šด ์ „๋ฌธ์šฉ์–ด ๋ฒˆ์—ญ ์˜ˆ์‹œ๋ฅผ ์ฐธ๊ณ ํ•ด์„œ ๋ฒˆ์—ญ์„ ํ•ด์ค˜: '{recommendations}' ์‚ฌ์šฉํ•˜์ง€ ์•Š์€ ์šฉ์–ด๋“ค์€ ๋ฌด์‹œํ•ด๋„ ๋ผ. ์ถ”๊ฐ€ ์„ค๋ช… ์—†์ด ๋ฌธ์žฅ๋งŒ ๋ฒˆ์—ญํ•ด. ์‚ฌ์šฉ๋œ ์›์–ด๋ฅผ ์šฉ์–ด ๋ฐ”๋กœ ๋’ค์— ๊ด„ํ˜ธ []์— ๋„ฃ์–ด์„œ ๋”ฐ๋ผ ๋ถ™์—ฌ์ค˜.",
        ),
    ]
    refined_translation = chainer(messages).invoke({})
    logger.info(refined_translation)

    retries = 0
    while "[" not in refined_translation or "]" not in refined_translation:
        retries += 1
        if retries > MAX_RETRIES:
            break
        messages += [
            ("ai", refined_translation),
            (
                "human",
                f"์ „๋ฌธ์šฉ์–ด๋ฅผ ๋ฒˆ์—ญํ–ˆ์œผ๋ฉด ๋ฐ˜๋“œ์‹œ ์›์–ด๋ฅผ ๊ด„ํ˜ธ[]์— ๋„ฃ์–ด์„œ ๋”ฐ๋ผ ๋ถ™์—ฌ์•ผ ํ•ด. '์‹คํ–‰ํ๋ฆ„[control]'์ฒ˜๋Ÿผ. ๋ฐฉ๊ธˆ ๋ฒˆ์—ญํ•œ '{refined_translation}'์—์„œ, ์›๋ž˜ ๋ฌธ์žฅ '{sentence}'์— ์‚ฌ์šฉ๋œ ์›์–ด๋ฅผ ์šฉ์–ด ๋ฐ”๋กœ ๋’ค์— ๊ด„ํ˜ธ []์— ๋„ฃ์–ด์„œ ๋”ฐ๋ผ ๋ถ™์—ฌ์ค˜.",
            ),
        ]
        refined_translation = chainer(messages).invoke({})
        logger.info(refined_translation)

    refined_translation = refined_translation.replace("[", "(").replace("]", ")")
    return refined_translation


with gr.Blocks() as demo:
    with gr.Tab("CHAT"):
        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,
        )


def main():
    demo.launch(share=True)


if __name__ == "__main__":
    main()