[파이썬] Ch.13 (2) gemma/llama 챗봇 + 기사 번역 웹

2026. 7. 16. 10:31·짧은 호흡/Python

< 여러가지 LLM 사용해서 비교답변 얻기 >

(1)에서 이어서…

  • 구글의 gemma4(26년 4월 출시) 모델과, 메타의 llama3.1(24년 7월 출시)을 동시에 사용하여,
  • 사용자가 한번 메시지를 입력하면 두 LLM 으로 받은 답변을 비교할 수 있는 웹앱으로 바꿔보자.
  •  

이런 모양으로

import streamlit as st

# 모듈 불러오기
from step_2_1 import (
    chat_message_llm,
    chat_message_user,
    init_session_state,
)

if __name__ == "__main__" :
    st.set_page_config( layout = "wide" )
    st.title("이지우의 챗봇(Gemma4 + Llama3.1)")

    init_session_state( dict ( gemma = [], llama = [] ) )

    gemma : list = st.session_state[ "gemma" ]
    llama : list = st.session_state[ "llama" ]

    for msg_gemma, msg_llama in zip( gemma, llama ) :

        if msg_gemma["role"] == "user" : # 사용자 메시지는 1회만 출력 
            with st.chat_message( "user" ) :
                st.markdown( msg_gemma [ "content" ] )
        
        else : # LLM 메시지는 두개의 열로 나누어 각각 출력
            col_gemma, col_llama = st.columns(2)

            with col_gemma :
                with st.chat_message("Gemma") :
                    st.markdown(msg_gemma["content"])
                
            with col_llama :
                with st.chat_message("Llama") :
                    st.markdown(msg_llama["content"])
        
    if prompt := st.chat_input( "여기에 대화를 입력하시옵소서..." ) :

        msg_user = chat_message_user( prompt )

        gemma.append( msg_user )
        llama.append( msg_user )

        col_gemma, col_llama = st.columns(2)

        # gemma2 세션에 LLM 메시지
        with col_gemma :
            msg_gemma = chat_message_llm( "Gemma", "gemma4:e2b", gemma )
            gemma.append(msg_gemma)
        
        # llama3.1 세션에 LLM 메시지
        with col_llama :
            msg_llama = chat_message_llm( "Llama", "llama3.1:8b", llama )
            llama.append(msg_llama)

 

배트를 든 오타니 vs 은가누 대전에서 누가 이길지 물어봤는데, 확실히 최신모델인 Gemma4의 답변이 훨씬 일리있는 모습이다.

 

< 기사 번역 웹 앱 만들기 >

  • 웹 크롤링(web crawling)

웹사이트의 링크를 따라 여러 페이지를 자동으로 방문하고, 페이지의 위치와 내용을 수집하는 과정.
검색 엔진이 웹페이지를 발견하고 색인하기 위해 사용하는 방식이 대표적이다.

  • 웹 스크레이핑(web scraping)

특정 페이지에서 필요한 정보를 선별적으로 추출. 예를 들어 상품명, 가격, 뉴스 제목, 리뷰 등의 데이터를 HTML에서 가져오는 작업이다.

  • trafilatura 패키지

웹 크롤링과 웹 스크레이핑에 사용되며, 특히 HTML 문서에서 텍스트를 효율적으로 추출한다.

  • fetch_url() : 주어진 URL에 접속하여 HTML을 수집
  • extract() : 주어진 HTML에서 텍스트를 추출
  • extract_metadata() 주어진 HTML에서 제목, 작성자, 이미지 등 메타 데이터를 추출
  • 기사를 하나 골라주자

월드컵 시즌에 걸맞는 월드컵 관련 기사를 가져왔다. 현대차 아틀라스 넘 멋있음.

 

< HTML에서 텍스트 추출 >

import trafilatura

def extract_text_img( url : str ) -> tuple[ str, str ] :
    
    html = trafilatura.fetch_url(url)

    text = trafilatura.extract(
        html,
        output_format = "markdown",
        include_comments = False, # 댓글은 제외할게요
    )

    img_url = trafilatura.extract_metadata(html).image

    return text, img_url

if __name__ == "__main__" :
    
    url = "<https://www.koreaherald.com/article/10811183>"

    text, img_url = extract_text_img( url )

    print(f"{text=}")
    print(f"{img_url=}")
  • 주어진 URL에서 텍스트와 이미지 URL을 추출하는 extract_text_img 함수를 정의하자.

위 코드를 실행하면,

text='Hyundai Motor Group is set to take full control of Boston Dynamics after SoftBank exercised a put option on its remaining 9.65 percent stake in the US robotics company, as the Korean auto group accelerates its push into physical artificial intelligence.\n\nHyundai said Thursday that SoftBank exercised the option under a 2020 agreement that allows the Japanese technology investor to sell its common shares in Boston Dynamics.\n\nBoston Dynamics is currently 28 percent owned by Hyundai Motor, 22.6 percent by Hyundai Motor Group Executive Chair Chung Euisun, 17.2 percent by Kia, 11.3 percent by Hyundai Mobis and 11.25 percent by Hyundai Glovis. Once the transaction is completed, the Hyundai affiliates and Chung will collectively own the company in full.\n\nThe group is reviewing the purchase price and how SoftBank’s shares will be divided among the existing shareholders.\n\nHyundai acquired an 80 percent controlling stake in Boston Dynamics from SoftBank for $880 million in 2021. SoftBank retained a 20 percent stake at the time, but its ownership was diluted to below 10 percent through subsequent capital increases.\n\n“As part of our long-term robotics strategy, we have been reviewing ways to expand our investment in Boston Dynamics,” a Hyundai Motor Group official said. “We will continue to strengthen the competitiveness of our robotics business and pursue greater synergies.”\n\nFull ownership would give Hyundai greater control over a key part of its physical AI strategy and allow it to more closely coordinate robot development, production and deployment with its manufacturing operations.\n\nThe group plans to introduce Boston Dynamics’ Atlas humanoid robots at Hyundai Motor Group Metaplant America and Kia’s plant in Georgia, starting with tests on individual production processes.\n\nAtlas is scheduled to begin parts-sequencing work in 2028, with its role expanding to component assembly from 2030 once the robot’s operational reliability has been established.\n\nBoston Dynamics has also stepped up public demonstrations of Atlas, most recently at a FIFA World Cup match on July 5, where the humanoid delivered the match ball at halftime and mimicked goal celebrations by soccer players including Son Heung-min.\n\nHyundai aims to build annual production capacity for 30,000 robots by 2028 and deploy 25,000 units at Hyundai Motor and Kia plants before supplying outside customers.\n\nThe group also plans to establish production capacity for 350,000 actuators, which function as a robot’s joints and muscles.\n\nyeeun@heraldcorp.com'
img_url='<https://wimg.heraldcorp.com/news/cms/2026/07/16/news-p.v1.20260716.72e50109423041ac9618a062d8b8864e_T1.jpg>'

이렇게 추출된다.

이 내용을 생성형 AI를 사용해서 번역하고 streamlit 웹 앱에 출력해보자.

  • 기본 번역 프롬프트를 넣어준다.
* system.txt 파일
당신은 많은 언어에 대한 전문 지식을 갖춘 매우 숙련된 번역가입니다.
내가 제공하는 텍스트의 언어를 식별한 다음, 원문의 의미, 어조, 뉘앙스를
유지하면서 한국어로 정확하게 번역하는 것이 당신의 임무입니다.
번역된 버전에서는 문법, 철자, 구두점, 줄바꿈, 마크다운 서식을 정확하게 유지해 주세요.
import ollama

from step_1_1 import IN_DIR
from step_3_1 import extract_text_img

SYSTEM_PROMPT = ( IN_DIR / "system.txt" ).read_text( encoding = "utf-8" )

url = "<https://www.koreaherald.com/article/10811183>"
text, img_url = extract_text_img(url)

msgs = [
    { "role" : "system" , "content" : SYSTEM_PROMPT },
    { "role" : "user", "content" : text },
]

resp = ollama.chat(

    model = "gemma4:e2b",
    messages = msgs,
    options = dict( temperature = 0.2 ),

)

msg_llm = dict(resp.get("message", {}))
msg_llm
{'role': 'assistant',
 'content': '현대차그룹이 한국 자동차 그룹이 물리적 인공지능(Physical AI) 분야로의 확장을 가속화함에 따라 소프트뱅크가 미국 로봇 회사인 보스턴 다이내믹스(Boston Dynamics)의 나머지 9.65% 지분에 대한 풋옵션을 행사함에 따라 해당 회사의 완전한 통제권을 확보하게 될 예정이다.\n\n현대차는 목요일에 소프트뱅크가 일본 기술 투자자가 보스턴 다이내믹스의 보통주를 매각할 수 있도록 허용하는 2020년 계약에 따라 해당 옵션을 행사했다고 밝혔다.\n\n현재 보스턴 다이내믹스는 현대모터스가 28%, 현대자동차그룹 회장인 정의선이 22.6%, 기아차는 17.2%, 현대모비스는 11.3%, 현대글로비스는 11.25%를 소유하고 있다. 이번 거래가 완료되면 현대차 계열사들과 정 회장은 회사 전체를 공동으로 소유하게 된다.\n\n그룹은 구매 가격과 소프트뱅크의 주식이 기존 주주들 사이에 어떻게 분배될 것인지 검토하고 있다.\n\n현대차는 2021년에 소프트뱅크로부터 보스턴 다이내믹스의 80% 지분을 8억 8천만 달러에 인수했다. 당시 소프트뱅크는 20%의 지분을 보유했지만, 이후 자본 증가를 통해 그 소유권은 10% 미만으로 희석되었다.\n\n현대차그룹 관계자는 “장기적인 로봇 전략의 일환으로 보스턴 다이내믹스에 대한 투자를 확대할 방안을 검토해 왔다”라며 “우리는 로봇 사업의 경쟁력을 계속 강화하고 더 큰 시너지를 추구할 것”이라고 말했다.\n\n완전한 소유권은 현대차에게 핵심적인 물리적 AI 전략에 대한 더 큰 통제권을 부여하고, 로봇 개발, 생산 및 배포를 제조 운영과 더욱 긴밀하게 조정할 수 있게 할 것이다.\n\n그룹은 현대차그룹 메타플랜트 아메리카와 조지아주의 기아 공장에 보스턴 다이내믹스의 휴머노이드 로봇인 아틀라스(Atlas)를 도입하여 개별 생산 공정에 대한 테스트부터 시작할 계획이다.\n\n아틀라스는 2028년에 부품 시퀀싱 작업을 시작할 예정이며, 로봇의 작동 신뢰성이 확립되면 2030년부터는 부품 조립 역할로 확대될 예정이다.\n\n보스턴 다이내믹스는 또한 아틀라스에 대한 공개 시연을 강화했는데, 가장 최근에는 7월 5일 FIFA 월드컵 경기에서 휴머노이드가 하프타임에 경기공을 전달하고 손흥민을 포함한 축구 선수들의 골 세리머니를 흉내 내는 모습을 보였다.\n\n현대차는 2028년까지 연간 3만 대의 로봇 생산 능력을 구축하고 현대차 및 기아 공장에서 2만 5천 대의 로봇을 배포한 후 외부 고객에게 공급하는 것을 목표로 한다.\n\n그룹은 또한 로봇의 관절과 근육 역할을 하는 액추에이터(actuators) 35만 개의 생산 능력을 구축할 계획이다.\n\nyeeun@heraldcorp.com',
 'thinking': 'Here\'s a thinking process to arrive at the desired translation:\n\n1.  **Analyze the Request:**\n    *   **Goal:** Translate the provided English text into Korean.\n    *   **Role:** Highly skilled translator specializing in many languages, focusing on accuracy, tone, nuance, and maintaining original formatting (grammar, punctuation, line breaks, markdown).\n    *   **Source Text Analysis (Tone & Context):** The text is a formal news report about a corporate transaction, strategic investment (AI/robotics), and future production plans involving major automotive groups (Hyundai Motor Group) and technology investors (SoftBank). The tone is informative, business-oriented, and forward-looking.\n\n2.  **Segment and Draft Translation (Sentence by Sentence):**\n\n    *   *Original:* Hyundai Motor Group is set to take full control of Boston Dynamics after SoftBank exercised a put option on its remaining 9.65 percent stake in the US robotics company, as the Korean auto group accelerates its push into physical artificial intelligence.\n        *   *Drafting Focus:* Complex sentence structure. Need to clearly link the cause (SoftBank action) and the effect (Hyundai gaining control) within the context of the broader strategy (physical AI).\n\n    *   *Original:* Hyundai said Thursday that SoftBank exercised the option under a 2020 agreement that allows the Japanese technology investor to sell its common shares in Boston Dynamics.\n        *   *Drafting Focus:* Straightforward reporting of the action and the legal basis (2020 agreement).\n\n    *   *Original:* Boston Dynamics is currently 28 percent owned by Hyundai Motor, 22.6 percent by Hyundai Motor Group Executive Chair Chung Euisun, 17.2 percent by Kia, 11.3 percent by Hyundai Mobis and 11.25 percent by Hyundai Glovis. Once the transaction is completed, the Hyundai affiliates and Chung will collectively own the company in full.\n        *   *Drafting Focus:* Listing ownership percentages accurately. Maintaining clarity regarding the final outcome (full collective ownership).\n\n    *   *Original:* The group is reviewing the purchase price and how SoftBank’s shares will be divided among the existing shareholders.\n        *   *Drafting Focus:* Standard business language for ongoing review.\n\n    *   *Original:* Hyundai acquired an 80 percent controlling stake in Boston Dynamics from SoftBank for $880 million in 2021. SoftBank retained a 20 percent stake at the time, but its ownership was diluted to below 10 percent through subsequent capital increases.\n        *   *Drafting Focus:* Historical transaction details. Ensure financial terms are precise.\n\n    *   *Original:* “As part of our long-term robotics strategy, we have been reviewing ways to expand our investment in Boston Dynamics,” a Hyundai Motor Group official said. “We will continue to strengthen the competitiveness of our robotics business and pursue greater synergies.”\n        *   *Drafting Focus:* Direct quote translation. Maintain the formal, strategic tone.\n\n    *   *Original:* Full ownership would give Hyundai greater control over a key part of its physical AI strategy and allow it to more closely coordinate robot development, production and deployment with its manufacturing operations.\n        *   *Drafting Focus:* Explaining the strategic benefit clearly.\n\n    *   *Original:* The group plans to introduce Boston Dynamics’ Atlas humanoid robots at Hyundai Motor Group Metaplant America and Kia’s plant in Georgia, starting with tests on individual production processes.\n        *   *Drafting Focus:* Specific project details (Atlas, locations).\n\n    *   *Original:* Atlas is scheduled to begin parts-sequencing work in 2028, with its role expanding to component assembly from 2030 once the robot’s operational reliability has been established.\n        *   *Drafting Focus:* Timeline and phased development plan (2028, 2030).\n\n    *   *Original:* Boston Dynamics has also stepped up public demonstrations of Atlas, most recently at a FIFA World Cup match on July 5, where the humanoid delivered the match ball at halftime and mimicked goal celebrations by soccer players including Son Heung-min.\n        *   *Drafting Focus:* Anecdotal/PR detail. Needs lively translation while remaining factual.\n\n    *   *Original:* Hyundai aims to build annual production capacity for 30,000 robots by 2028 and deploy 25,000 units at Hyundai Motor and Kia plants before supplying outside customers.\n        *   *Drafting Focus:* Production targets (capacity vs. deployment).\n\n    *   *Original:* The group also plans to establish production capacity for 350,000 actuators, which function as a robot’s joints and muscles.\n        *   *Drafting Focus:* Technical detail (actuators).\n\n    *   *Original:* yeeun@heraldcorp.com\n        *   *Drafting Focus:* Signature/Email address (keep as is).\n\n3.  **Review and Refine:** (Self-Correction Phase)\n    *   Check flow: Does the Korean read naturally, or is it a literal, awkward translation? (The business terms must be idiomatic.)\n    *   Check terminology: "Put option," "stake," "diluted," "synergies," "actuators" must use standard industry Korean equivalents.\n    *   Check formatting: Ensure the paragraph breaks and structure match the original markdown style.\n\n4.  **Final Output Generation.** (This leads to the final provided translation.)',
 'images': None,
 'tool_name': None,
 'tool_calls': None}
  • ‘content’ 항목에 변역된 결과가 잘 출력된다.

이 결과를 웹에서 보기 좋게 확인해보자.

import ollama
import streamlit as st

from step_1_1 import IN_DIR
from step_3_1 import extract_text_img

SYSTEM_PROMPT = ( IN_DIR / "system.txt" ).read_text( encoding = "utf-8" )

if __name__ == "__main__" :
    st.set_page_config( layout = "wide" )
    st.title("기사를 번역해드립니다..")

    with st.form("form", border = False) :

        col_url, col_submit = st.columns([9,1])

        with col_url :
            url = st.text_input(
                "text_input", # 위젯 이름
                placeholder = "URL을 입력하세요!",
                label_visibility = "collapsed", # 위젯 이름 출력 방지
            )
        
        with col_submit :
            submitted = st.form_submit_button("번역하기", use_container_width = True )
        
    if submitted :
        st.write(f"(Source) {url}")
        text, img_url = extract_text_img(url)

        col_input, col_output = st.columns(2)

        with col_input :
            st.image( img_url, width = "stretch" )
            st.markdown(text)
        
        with col_output :
            with st.spinner("번역하는 중입니다...") :
                msgs = [
                    { "role" : "system", "content" : SYSTEM_PROMPT },
                    { "role" : "user", "content" : text },
                ]

                resp = ollama.chat(
                    model = "gemma4:e2b",
                    messages = msgs,
                    options = dict( temperature = 0.2 ),
                )

                msg_llm = resp.get("message", {})
                st.markdown(msg_llm["content"])

와우!

'짧은 호흡 > Python' 카테고리의 다른 글

[파이썬] Ch.13 (1) gemma2로 챗봇 웹 앱 만들기  (0) 2026.07.13
[파이썬] Ch.8 (2) 키워드별 경쟁강도 분석 웹 앱  (0) 2026.07.10
[파이썬] Ch.8 (1) 쇼핑 키워드 데이터 수집 + 정제  (0) 2026.07.09
[파이썬] Ch.5 (2) 광학 문자 인식 + DeepL API 번역  (0) 2026.07.07
[파이썬] Ch.5 (1) 광학 문자 인식 + 웹 앱 만들기  (0) 2026.07.04
'짧은 호흡/Python' 카테고리의 다른 글
  • [파이썬] Ch.13 (1) gemma2로 챗봇 웹 앱 만들기
  • [파이썬] Ch.8 (2) 키워드별 경쟁강도 분석 웹 앱
  • [파이썬] Ch.8 (1) 쇼핑 키워드 데이터 수집 + 정제
  • [파이썬] Ch.5 (2) 광학 문자 인식 + DeepL API 번역
jiwoo.lee
jiwoo.lee
jiwoo 님의 블로그 입니다.
  • jiwoo.lee
    jiwoo.lee
    jiwoo.lee
  • 전체
    오늘
    어제
    • 분류 전체보기 (9)
      • 이야기 (0)
      • 긴 호흡 (0)
      • 짧은 호흡 (9)
        • Python (8)
        • Git (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Python
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.6
jiwoo.lee
[파이썬] Ch.13 (2) gemma/llama 챗봇 + 기사 번역 웹
상단으로

티스토리툴바