검색
검색
공개 노트 검색
회원가입로그인

파이썬과 AI를 활용한 문학 분석 (랭체인, claude v1 라이브러리)

** 아래 글은 클로드와 지피티 4의 도움을 받아 작성이 되었습니다.

참고로 필자는 파이썬 초보입니다. ^^

reasonofmoon_Imagine_a_minimalist_book_illustration_that_portra_43e9578e-6285-431f-8f91-15faf28c425b

파이썬과 AI를 활용한 문학 분석

파이썬은 다양한 영역에서 활용될 수 있는 강력한 프로그래밍 언어입니다. 오늘은 문학 작품의 분석에 파이썬과 AI를 어떻게 사용할 수 있는지 알아보겠습니다. 특히, langchain과 anthropic 라이브러리를 이용하여 소설의 일부를 분석하는 방법을 소개합니다.

필요한 라이브러리 설치

먼저, 우리가 사용할 라이브러리인 langchainanthropic를 설치해야 합니다. 이 라이브러리들은 문학 작품의 분석과 관련된 고급 기능을 제공합니다.

!pip install langchain
!pip install anthropic

필수 라이브러리 임포트

설치가 완료되면, 필요한 모듈을 파이썬 스크립트에 임포트합니다.

import re  # 정규 표현식을 위한 모듈
from langchain.llms import Anthropic  # 문학 분석에 필요한 AI 기능을 제공하는 모듈
from langchain import PromptTemplate, LLMChain  # 문학 분석을 위한 템플릿과 체인을 구성하는 클래스

분석 코드 준비

다음으로, 문학 작품의 분석을 위한 코드를 준비합니다. 이 코드는 소설의 일부를 입력으로 받아, 다양한 분석 작업을 수행하는 구조로 되어 있습니다.

code = '''<Inputs>
{novel_excerpt}  
</Inputs>

<Instructions>
여러 문학 분석 작업 수행...
</Instructions>
'''

template = PromptTemplate(input_variables=["novel_excerpt"], template=code, validate_template=False)

PromptTemplate 클래스는 분석을 위한 입력 변수와 템플릿을 정의합니다. 여기서 {novel_excerpt}는 분석할 소설의 일부를 나타내는 변수입니다.

AI 모델 설정

Anthropic 클래스를 이용해 사용할 AI 모델을 설정합니다. 여기서는 claude-v1 모델을 사용하며, max_tokens_to_sampletemperature 등의 매개변수를 조정하여 출력의 세부 사항을 조절할 수 있습니다.

anthropic_api_key = "your_api_key_here"  # 실제 API 키로 대체하세요
llm = Anthropic(model="claude-v1", max_tokens_to_sample=100000, temperature=0.9, anthropic_api_key=anthropic_api_key)

분석 체인 실행

마지막으로, LLMChain 클래스를 사용하여 문학 분석 체인을 실행합니다. 사용자로부터 소설의 일부를 입력 받아, 앞서 정의한 템플릿과 AI 모델을 사용해 분석을 수행하고 결과를 출력합니다.

chain = LLMChain(prompt=template, llm=llm)

print("Please provide the novel excerpt to analyze:")
novel_excerpt = input()

result = chain.run(novel_excerpt=novel_excerpt)
print(result)

이 프로세스를 통해, 파이썬과 AI를 활용하여 문학 작품의 깊이 있는 분석을 자동으로 수행할 수 있습니다. 이 방법은 문학 교육이나 연구에 매우 유용하게 활용될 수 있습니다.

## 요약 (Korean Summary)

이 작품은 두 길이 갈린 황금빛 숲속에서 시인이 선택을 하게 된 경험을 통해 인생에서의 선택의 중요성을 담고 있다. 길이 두 갈래로 갈라지는 숲속에서 시인은 오랫동안 고민 끝에 덜 여행객이 다니는 쪽의 길을 선택한다. 그 선택이 삶의 큰 변화를 가져오게 된다는 내용을 담고 있다.

## 문학 분석 (Literary Analysis)

This poem uses the metaphor of a traveler coming upon a fork in the road in a "yellow wood" to represent a pivotal moment of choice in one's life. The traveler can only go down one path, and his choice is significant as "way leads on to way" - each path represents a trajectory that will shape his life's journey. Though the two roads are "just as fair" and "equally lay" at the outset, the traveler's choice of "the one less traveled by" transforms his life in some meaningful way, as he will "be telling this with a sigh" for ages to come.   

The poem's central theme is that the choices we make, even when options appear equally viable, can have a profound impact on the course of our lives. The symmetrical structure, with equal line lengths and a regular rhyme scheme, reinforces the idea that the traveler faces two ostensibly even options. However, the varied and inconsistent rhythm created by the use of enjambment and caesurae represents the uncertainty and difficulty of making such a choice. The personification of the roads "diverging" and the undergrowth where one path "bent" gives a sense of their agency and mystery. The traveler knows that he will likely never return to explore the path not taken, and must move forward aware of the significance of his choice. 

In conclusion, the poem suggests that we shape our own destinies by the choices we make at critical junctures in life, even when options seem equally unclear or ambiguous. The consequences of those choices may haunt us for a lifetime, filling us with questions about the path not chosen. But we alone are responsible for bravely forging our own way in the journey ahead.

## 토론 주제 (Discussion Topics)

1. What do the "two roads" represent metaphorically in the poem? What do their "diverging" paths symbolize?
2. Why does the traveler doubt that he will ever come back to this spot? What deeper meaning does this convey?  
3. What is the significance of the traveler choosing "the one less traveled by"? How might this choice impact the course of his journey?
4. How does the poem's symmetrical structure and rhythm represent the theme of difficult life choices? What effect does this create?
5. What perspective does the poem suggest we should have when facing important decisions where options seem equally unclear or confusing?

## 이해도 평가 문항 (Comprehension Questions)

1. Where does the traveler come upon two diverging roads? 
   - The traveler comes upon two diverging roads in a "yellow wood."  

2. Why does the traveler doubt he will return to this place?
   - The traveler doubts he will return because "way leads on to way" - each path represents a journey and trajectory in life that continues forward. Once a path is chosen, one cannot go back and undo that choice. 

3. What is the significance of the traveler's choice of "the road less traveled by"? 
   - Choosing the road less traveled represents forging one's own individual way in life, rather than following the crowd. It suggests a desire for independence, self-discovery, and adventure.

## 영어 테스트 문항 (English Test Questions)

Multiple Choice:
1. The setting of the poem is:  
   A. A misty mountain  B. A desert plain   C. A yellow wood   D. A river valley

2. The traveler chose:
   A. The road more traveled by   B. The road less traveled by 
   C. Both roads   D. Neither road

3. "Way leads on to way" suggests that: 
   A. Life's journey continues forward B. There are many paths to choose from  
   C. One should explore many options   D. Choices cannot be undone  

Short Answer: 
1. What is the central metaphor in the poem? Explain its meaning.
   - The central metaphor is the two diverging roads in the yellow wood, representing choices and life journeys that continue in a trajectory once chosen.

2. What options does the traveler face? 
   - The traveler faces the choice

전체 코드

  • 아래 코드를 구글 콜렙에 붙여넣고 작동해 보세요.

!pip install langchain
!pip install anthropic

import re
from langchain.llms import Anthropic
from langchain import PromptTemplate, LLMChain

code = '''<Inputs>
{novel_excerpt}  
</Inputs>

<Instructions>
You are Literary Explorer Plus, an AI assistant specialized in conducting in-depth literary analysis and generating educational content based on excerpts from novels. 

Your task is to analyze the provided novel excerpt, which will be enclosed in <novel_excerpt> tags, and complete the following:

1. Korean Summary
<korean_summary>
- Summarize the key points and themes of the excerpt in clear, concise Korean. 
- Keep character names and place names in English. 
</korean_summary>

2. Literary Analysis  
<literary_analysis>
- Analyze the excerpt, identifying key literary elements, themes, and techniques used.
- Discuss how these elements contribute to the overall meaning and impact of the passage.
- Cite specific examples from the text to support your analysis.
</literary_analysis>

3. Discussion Topics
<discussion_topics>
- Suggest 3-5 thought-provoking questions or topics for further exploration of the excerpt's themes and implications.
- Aim for open-ended prompts that encourage critical thinking and debate.
</discussion_topics>

4. Comprehension Questions  
<comprehension_questions>
- Create 3 key comprehension questions to assess understanding of the excerpt.
- Provide the answers to these questions, citing relevant evidence from the text.
- Questions should test literal understanding as well as inference and analysis skills.
</comprehension_questions>

Additional Components:
- Test Questions for English Learners
<english_test_questions> 
- Generate 5 multiple choice questions, 4 short answer questions, and 1-2 discussion questions about the excerpt in English.
- Questions should test understanding of key concepts, themes, and details from the text.
- Include an answer key with explanations.
</english_test_questions>

- English Summary
<english_summary>
- Provide a concise English summary of the excerpt to aid comprehension for English language learners. 
- Focus on the main ideas and events.
</english_summary>

- Flowchart Idea
<flowchart_idea>
- Suggest an idea for a simple flowchart or diagram that could help visualize a key aspect of the excerpt (e.g. plot structure, character relationships, thematic development).
- Briefly explain how the flowchart would aid understanding.   
</flowchart_idea>

- Vocabulary Table
<vocabulary_table>
- Select 5 key vocabulary words from the excerpt.
- Present them in a table with the following columns: 
  - English term
  - Definition in English 
  - Korean translation

| English Term | Definition | Korean Translation |
|--------------|------------|-------------------|
|              |            |                   |
</vocabulary_table>

If additional information is needed to complete a particular analysis or answer a question, indicate what specific details would help and where they might be found in the text.

After generating the full literary analysis worksheet, translate the entire output into Korean to make it accessible for Korean speakers. The final deliverable should include both the original English components and the full Korean translation.

<novel_excerpt>
{novel_excerpt}
</novel_excerpt>

</Instructions>
'''

template = PromptTemplate(input_variables=["novel_excerpt"], template=code, validate_template=False)

anthropic_api_key = "your_api_key_here"  # 실제 API 키로 대체하세요
llm = Anthropic(model="claude-v1", max_tokens_to_sample=100000, temperature=0.9, anthropic_api_key=anthropic_api_key)

chain = LLMChain(prompt=template, llm=llm)

print("Please provide the novel excerpt to analyze:")
novel_excerpt = input()

result = chain.run(novel_excerpt=novel_excerpt)
print(result)
조회수 : 513
공유하기
카카오로 공유하기
페이스북 공유하기
트위터로 공유하기
url 복사하기