test commited on
Commit
20f56bb
·
1 Parent(s): 5bb27ac

Add Gradio app for AI research note summary

Browse files
Files changed (4) hide show
  1. 0903_ai_memo.bak +89 -0
  2. 0903_ai_memo.py +89 -0
  3. 0903_ai_memo_test.py +99 -0
  4. requirements.txt +116 -0
0903_ai_memo.bak ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AI 학습/연구 메모 요약기
2
+ # 기능: 사용자가 긴 글(논문 초록, 블로그 글, 수업 필기)을 입력 → LLaMA 모델로 핵심 요약 + 키워드 추출
3
+ # 추가: OpenAPI로 사전/위키 검색해서 어려운 용어 간단 설명 붙여주기
4
+ # 결과: Gradio UI에서 "원문 / 요약 / 키워드 / 추가설명" 탭으로 보기
5
+
6
+ # -*- coding: utf-8 -*-
7
+ import gradio as gr
8
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
9
+ from sklearn.feature_extraction.text import TfidfVectorizer
10
+ import numpy as np
11
+ import re
12
+
13
+ # =========================
14
+ # 1) 모델 로드 (한국어 요약)
15
+ # =========================
16
+ summarizer_model_name = "lcw99/t5-base-korean-text-summary"
17
+ summarizer_tokenizer = AutoTokenizer.from_pretrained(summarizer_model_name)
18
+ summarizer_model = AutoModelForSeq2SeqLM.from_pretrained(summarizer_model_name)
19
+
20
+ # =========================
21
+ # 2) 키워드 추출 함수 (TF-IDF 기반)
22
+ # =========================
23
+ def extract_keywords_korean(text, top_n=5):
24
+ # 한글 명사 중심 단어만 추출
25
+ text = re.sub(r"[^가-힣\s]", "", text)
26
+ stop_words = ['은','는','이','가','을','를','에','의','와','과','도','으로','까지','하다','있다','있음']
27
+ vectorizer = TfidfVectorizer(stop_words=stop_words)
28
+
29
+ try:
30
+ X = vectorizer.fit_transform([text])
31
+ except ValueError:
32
+ return "키워드 추출 불가 (글이 너무 짧음)"
33
+
34
+ indices = np.argsort(vectorizer.idf_)[::-1]
35
+ features = vectorizer.get_feature_names_out()
36
+ keywords = [features[i] for i in indices[:top_n]]
37
+ return ", ".join(keywords)
38
+
39
+ # =========================
40
+ # 3) 요약 + 키워드 함수
41
+ # =========================
42
+ def summarize_and_extract_keywords(text):
43
+ if not text.strip():
44
+ return "원문을 입력하세요.", "", ""
45
+
46
+ # -------------------------
47
+ # 1) 요약
48
+ # -------------------------
49
+ inputs = summarizer_tokenizer(text, return_tensors="pt", max_length=512, truncation=True)
50
+ summary_ids = summarizer_model.generate(
51
+ inputs['input_ids'],
52
+ max_length=200,
53
+ min_length=50,
54
+ num_beams=4,
55
+ early_stopping=True
56
+ )
57
+ summary = summarizer_tokenizer.decode(summary_ids[0], skip_special_tokens=True)
58
+
59
+ # -------------------------
60
+ # 2) 키워드 추출
61
+ # -------------------------
62
+ keywords = extract_keywords_korean(text, top_n=5)
63
+
64
+ return text, summary, keywords
65
+
66
+ # =========================
67
+ # 4) Gradio UI
68
+ # =========================
69
+ with gr.Blocks() as demo:
70
+ gr.Markdown("## 📝 한국어 AI 요약 & 키워드 추출기")
71
+
72
+ inp = gr.Textbox(lines=12, placeholder="여기에 한국어 텍스트를 붙여넣으세요.", label="원문 입력")
73
+ btn = gr.Button("실행")
74
+
75
+ with gr.Tabs():
76
+ with gr.Tab("원문"):
77
+ out_original = gr.Textbox(label="원문", lines=8)
78
+ with gr.Tab("요약"):
79
+ out_summary = gr.Textbox(label="요약", lines=8)
80
+ with gr.Tab("키워드"):
81
+ out_keywords = gr.Textbox(label="키워드", lines=4)
82
+
83
+ btn.click(summarize_and_extract_keywords, inputs=inp, outputs=[out_original, out_summary, out_keywords])
84
+
85
+ # =========================
86
+ # 5) 실행
87
+ # =========================
88
+ if __name__ == "__main__":
89
+ demo.launch()
0903_ai_memo.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AI 학습/연구 메모 요약기
2
+ # 기능: 사용자가 긴 글(논문 초록, 블로그 글, 수업 필기)을 입력 → LLaMA 모델로 핵심 요약 + 키워드 추출
3
+ # 추가: OpenAPI로 사전/위키 검색해서 어려운 용어 간단 설명 붙여주기
4
+ # 결과: Gradio UI에서 "원문 / 요약 / 키워드 / 추가설명" 탭으로 보기
5
+
6
+ # -*- coding: utf-8 -*-
7
+ import gradio as gr
8
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
9
+ from sklearn.feature_extraction.text import TfidfVectorizer
10
+ import numpy as np
11
+ import re
12
+
13
+ # =========================
14
+ # 1) 모델 로드 (한국어 요약)
15
+ # =========================
16
+ summarizer_model_name = "lcw99/t5-base-korean-text-summary"
17
+ summarizer_tokenizer = AutoTokenizer.from_pretrained(summarizer_model_name)
18
+ summarizer_model = AutoModelForSeq2SeqLM.from_pretrained(summarizer_model_name)
19
+
20
+ # =========================
21
+ # 2) 키워드 추출 함수 (TF-IDF 기반)
22
+ # =========================
23
+ def extract_keywords_korean(text, top_n=5):
24
+ # 한글 명사 중심 단어만 추출
25
+ text = re.sub(r"[^가-힣\s]", "", text)
26
+ stop_words = ['은','는','이','가','을','를','에','의','와','과','도','으로','까지','하다','있다','있음']
27
+ vectorizer = TfidfVectorizer(stop_words=stop_words)
28
+
29
+ try:
30
+ X = vectorizer.fit_transform([text])
31
+ except ValueError:
32
+ return "키워드 추출 불가 (글이 너무 짧음)"
33
+
34
+ indices = np.argsort(vectorizer.idf_)[::-1]
35
+ features = vectorizer.get_feature_names_out()
36
+ keywords = [features[i] for i in indices[:top_n]]
37
+ return ", ".join(keywords)
38
+
39
+ # =========================
40
+ # 3) 요약 + 키워드 함수
41
+ # =========================
42
+ def summarize_and_extract_keywords(text):
43
+ if not text.strip():
44
+ return "원문을 입력하세요.", "", ""
45
+
46
+ # -------------------------
47
+ # 1) 요약
48
+ # -------------------------
49
+ inputs = summarizer_tokenizer(text, return_tensors="pt", max_length=512, truncation=True)
50
+ summary_ids = summarizer_model.generate(
51
+ inputs['input_ids'],
52
+ max_length=200,
53
+ min_length=50,
54
+ num_beams=4,
55
+ early_stopping=True
56
+ )
57
+ summary = summarizer_tokenizer.decode(summary_ids[0], skip_special_tokens=True)
58
+
59
+ # -------------------------
60
+ # 2) 키워드 추출
61
+ # -------------------------
62
+ keywords = extract_keywords_korean(text, top_n=5)
63
+
64
+ return text, summary, keywords
65
+
66
+ # =========================
67
+ # 4) Gradio UI
68
+ # =========================
69
+ with gr.Blocks() as demo:
70
+ gr.Markdown("## 📝 한국어 AI 요약 & 키워드 추출기")
71
+
72
+ inp = gr.Textbox(lines=12, placeholder="여기에 한국어 텍스트를 붙여넣으세요.", label="원문 입력")
73
+ btn = gr.Button("실행")
74
+
75
+ with gr.Tabs():
76
+ with gr.Tab("원문"):
77
+ out_original = gr.Textbox(label="원문", lines=8)
78
+ with gr.Tab("요약"):
79
+ out_summary = gr.Textbox(label="요약", lines=8)
80
+ with gr.Tab("키워드"):
81
+ out_keywords = gr.Textbox(label="키워드", lines=4)
82
+
83
+ btn.click(summarize_and_extract_keywords, inputs=inp, outputs=[out_original, out_summary, out_keywords])
84
+
85
+ # =========================
86
+ # 5) 실행
87
+ # =========================
88
+ if __name__ == "__main__":
89
+ demo.launch()
0903_ai_memo_test.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AI 학습/연구 메모 요약기
2
+ # 기능: 사용자가 긴 글(논문 초록, 블로그 글, 수업 필기)을 입력 → LLaMA 모델로 핵심 요약
3
+ # 결과: Gradio UI에서 "원문 / 요약 탭으로 보기
4
+
5
+ # -*- coding: utf-8 -*-
6
+ import gradio as gr
7
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
8
+
9
+ # =========================
10
+ # 1) 모델 로드 (한국어 요약)
11
+ # =========================
12
+ summarizer_model_name = "lcw99/t5-base-korean-text-summary"
13
+ summarizer_tokenizer = AutoTokenizer.from_pretrained(summarizer_model_name)
14
+ summarizer_model = AutoModelForSeq2SeqLM.from_pretrained(summarizer_model_name)
15
+
16
+ # =========================
17
+ # 2) 요약 함수
18
+ # =========================
19
+ def summarize_text(text, length_option="보통"):
20
+ text = text.strip()
21
+
22
+ # 짧은 글 예외 처리
23
+ if len(text) < 100:
24
+ return text
25
+
26
+ if length_option == "짧게":
27
+ max_len, min_len = 80, 30
28
+ else: # 보통
29
+ max_len, min_len = 200, 50
30
+
31
+ inputs = summarizer_tokenizer(
32
+ text,
33
+ return_tensors="pt",
34
+ max_length=1024,
35
+ truncation=True
36
+ )
37
+ summary_ids = summarizer_model.generate(
38
+ inputs['input_ids'],
39
+ max_length=max_len,
40
+ min_length=min_len,
41
+ num_beams=4,
42
+ early_stopping=True,
43
+ no_repeat_ngram_size=3
44
+ )
45
+ summary = summarizer_tokenizer.decode(summary_ids[0], skip_special_tokens=True)
46
+ return summary
47
+
48
+ def summarize_and_process(text, length_option):
49
+ text = text.strip()
50
+ original_len = len(text)
51
+
52
+ if not text:
53
+ return "원문을 입력하세요.", ""
54
+
55
+ summary = summarize_text(text, length_option)
56
+ summary_len = len(summary)
57
+
58
+ out_original = f"{text}\n\n(총 글자수: {original_len})"
59
+ out_summary = f"{summary}\n\n(총 글자수: {summary_len})"
60
+
61
+ return out_original, out_summary
62
+
63
+ # =========================
64
+ # 3) Gradio UI
65
+ # =========================
66
+ with gr.Blocks() as demo:
67
+ gr.Markdown("## 📝 한국어 AI 요약 (예시 글 입력해놨음)")
68
+
69
+ inp = gr.Textbox(
70
+ lines=12,
71
+ placeholder="여기에 한국어 텍스트를 붙여넣으세요. 100글자 이상",
72
+ label="원문 입력",
73
+ value="""트랜스포머 모델은 2017년에 소개된 딥러닝 모델로, 자연어 처리에서 큰 혁신을 가져왔다.
74
+ 이 모델은 셀프 어텐션(Self-Attention) 메커니즘을 사용하여 입력 시퀀스를 병렬로 처리할 수 있다.
75
+ 기존의 RNN과 달리 장기 의존성 문제를 효과적으로 해결할 수 있어 번역, 요약, 질문응답 등 다양한 NLP 태스크에서 우수한 성능을 보인다.
76
+ 트랜스포머 기반의 모델들은 이후 BERT, GPT, T5 등 여러 파생 모델의 기초가 되었으며, 현재 자연어 처리 연구에서 표준으로 자리 잡았다.
77
+ 이러한 발전 덕분에 챗봇, 기계번역, 자동 요약 등 실제 서비스에 바로 활용할 수 있는 수준까지 도달하였다."""
78
+ )
79
+
80
+ length_option = gr.Radio(["짧게", "보통"], label="요약 길이 선택", value="보통")
81
+ btn = gr.Button("실행")
82
+
83
+ with gr.Tabs():
84
+ with gr.Tab("원문"):
85
+ out_original = gr.Textbox(label="원문 + 글자수", lines=8)
86
+ with gr.Tab("요약"):
87
+ out_summary = gr.Textbox(label="요약 + 글자수", lines=8)
88
+
89
+ btn.click(
90
+ summarize_and_process,
91
+ inputs=[inp, length_option],
92
+ outputs=[out_original, out_summary]
93
+ )
94
+
95
+ # =========================
96
+ # 4) 실행
97
+ # =========================
98
+ if __name__ == "__main__":
99
+ demo.launch(share=True)
requirements.txt ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiofiles==23.2.1
2
+ annotated-types==0.7.0
3
+ anyio==4.5.2
4
+ beautifulsoup4==4.13.5
5
+ bidict==0.23.1
6
+ blinker==1.8.2
7
+ boto3==1.37.38
8
+ botocore==1.37.38
9
+ bs4==0.0.2
10
+ certifi==2025.8.3
11
+ charset-normalizer==3.4.3
12
+ click==8.1.8
13
+ cmudict==1.0.33
14
+ colorama==0.4.6
15
+ contourpy==1.1.1
16
+ cycler==0.12.1
17
+ diskcache==5.6.3
18
+ Distance==0.1.3
19
+ distro==1.9.0
20
+ emoji==1.2.0
21
+ exceptiongroup==1.3.0
22
+ fastapi==0.116.1
23
+ ffmpy==0.5.0
24
+ filelock==3.16.1
25
+ Flask==3.0.3
26
+ fonttools==4.57.0
27
+ fsspec==2025.3.0
28
+ gradio==4.44.1
29
+ gradio_client==1.3.0
30
+ h11==0.16.0
31
+ hangul-jamo==1.0.1
32
+ httpcore==1.0.9
33
+ httpx==0.28.1
34
+ huggingface-hub==0.34.4
35
+ idna==3.10
36
+ importlib_metadata==8.5.0
37
+ importlib_resources==6.4.5
38
+ iniconfig==2.1.0
39
+ itsdangerous==2.2.0
40
+ jamo==0.4.1
41
+ Jinja2==3.1.6
42
+ jiter==0.9.1
43
+ jmespath==1.0.1
44
+ joblib==1.4.2
45
+ jpype1==1.6.0
46
+ keybert==0.9.0
47
+ kiwisolver==1.4.7
48
+ kollocate==0.0.2
49
+ konlpy==0.6.0
50
+ koparadigm==0.10.0
51
+ kss==6.0.5
52
+ llama_cpp_python==0.3.16
53
+ lxml==6.0.1
54
+ markdown-it-py==3.0.0
55
+ MarkupSafe==2.1.5
56
+ matplotlib==3.7.5
57
+ mdurl==0.1.2
58
+ mpmath==1.3.0
59
+ networkx==3.1
60
+ numpy==1.24.4
61
+ openai==1.102.0
62
+ orjson==3.10.15
63
+ packaging==25.0
64
+ pandas==2.0.3
65
+ pecab==1.0.8
66
+ pillow==10.4.0
67
+ pluggy==1.5.0
68
+ predictor==0.1.2
69
+ pyarrow==17.0.0
70
+ pydantic==2.10.6
71
+ pydantic_core==2.27.2
72
+ pydub==0.25.1
73
+ Pygments==2.19.2
74
+ pyparsing==3.1.4
75
+ pytest==8.3.5
76
+ python-dateutil==2.9.0.post0
77
+ python-multipart==0.0.20
78
+ pytz==2025.2
79
+ PyYAML==6.0.2
80
+ regex==2024.11.6
81
+ requests==2.32.4
82
+ rich==14.1.0
83
+ ruff==0.12.10
84
+ s3transfer==0.11.5
85
+ safetensors==0.5.3
86
+ scikit-learn==1.3.2
87
+ scipy==1.10.1
88
+ semantic-version==2.10.0
89
+ sentence-transformers==3.2.1
90
+ sentencepiece==0.2.0
91
+ shellingham==1.5.4
92
+ six==1.17.0
93
+ sniffio==1.3.1
94
+ soupsieve==2.7
95
+ starlette==0.44.0
96
+ sympy==1.13.3
97
+ threadpoolctl==3.5.0
98
+ tokenizers==0.20.3
99
+ tomli==2.2.1
100
+ tomlkit==0.12.0
101
+ torch==2.4.1
102
+ torchvision==0.19.1
103
+ tossi==0.3.1
104
+ tqdm==4.67.1
105
+ transformers==4.46.3
106
+ typer==0.16.1
107
+ typing_extensions==4.13.2
108
+ tzdata==2025.2
109
+ Unidecode==1.4.0
110
+ urllib3==2.2.3
111
+ uvicorn==0.33.0
112
+ websockets==12.0
113
+ Werkzeug==3.0.6
114
+ Whoosh==2.7.4
115
+ xlrd==1.2.0
116
+ zipp==3.20.2