je010112 commited on
Commit
a2e0332
·
2 Parent(s): 57059f8 e8dd7e6

Merge branch 'main' of https://huggingface.co/spaces/teameight/fairytale_generator

Browse files
blip-image-captioning-base01.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # 필요한 라이브러리 임포트
2
+ # from transformers import BlipProcessor, BlipForConditionalGeneration # 이미지 → 텍스트 설명 생성용
3
+ # from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline # 텍스트 생성 (동화 생성)용
4
+ # from PIL import Image # 이미지 처리용
5
+ # import gradio as gr # 웹 인터페이스용
6
+ # import torch # PyTorch (모델 구동)
7
+
8
+ # # 1. BLIP 모델: 이미지 설명 생성용 모델 및 전처리기 로딩
9
+ # caption_processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
10
+ # caption_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
11
+
12
+ # # 2. KoT5 모델: 설명 → 동화 생성용 한국어 텍스트 생성 모델 로딩
13
+ # story_tokenizer = AutoTokenizer.from_pretrained("paust/pko-t5-base")
14
+ # story_model = AutoModelForSeq2SeqLM.from_pretrained("paust/pko-t5-base")
15
+
16
+ # # Hugging Face pipeline으로 간편한 생성 함수 구성
17
+ # story_generator = pipeline("text2text-generation", model=story_model, tokenizer=story_tokenizer)
18
+
19
+ # # 3. 핵심 함수: 이미지 입력 → 설명 생성 → 동화 생성
20
+ # def generate_fairytale(image):
21
+ # # 이미지 → 설명 생성 (BLIP)
22
+ # inputs = caption_processor(images=image, return_tensors="pt") # 이미지 전처리
23
+ # outputs = caption_model.generate(**inputs) # 설명 생성
24
+ # caption = caption_processor.decode(outputs[0], skip_special_tokens=True) # 설명 텍스트 디코딩
25
+
26
+ # # 프롬프트 구성: 설명을 바탕으로 동화를 써달라고 요청
27
+ # prompt = f"다음 설명을 바탕으로 어린이 동화를 써줘:\n\"{caption}\""
28
+
29
+ # # 설명 → 동화 생성 (KoT5)
30
+ # story = story_generator(prompt, max_length=300, do_sample=True)[0]['generated_text']
31
+
32
+ # # Gradio에 표시할 두 개 결과 반환: 설명, 동화
33
+ # return caption, story
34
+
35
+ # # 4. Gradio 인터페이스 구성
36
+ # interface = gr.Interface(
37
+ # fn=generate_fairytale, # 호출할 함수
38
+ # inputs=gr.Image(type="pil", label="🖼️ 그림을 업로드하세요"), # 이미지 업로드 창
39
+ # outputs=[
40
+ # gr.Textbox(label="📌 이미지 설명"), # 텍스트 설명 출력
41
+ # gr.Textbox(label="📖 생성된 동화") # 생성된 동화 출력
42
+ # ],
43
+ # title="🎨 AI 이미지 동화 생성기", # 앱 제목
44
+ # description="이미지를 업로드하면 설명과 동화를 자동으로 생성해주는 서비스입니다.",
45
+ # theme="soft" # 부드러운 Gradio 테마
46
+ # )
47
+
48
+ # # 5. 웹 앱 실행 (URL 콘솔 출력)
49
+ # interface.launch(share=True, debug=True, inbrowser=True)
50
+
51
+
52
+ from transformers import BlipProcessor, BlipForConditionalGeneration
53
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
54
+ from PIL import Image
55
+ import gradio as gr
56
+ import torch
57
+
58
+ # 1. BLIP 이미지 캡셔닝 모델
59
+ caption_processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
60
+ caption_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
61
+
62
+ # 2. 영어 동화 생성 모델 (Flan-T5)
63
+ story_tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-base")
64
+ story_model = AutoModelForSeq2SeqLM.from_pretrained("google/flan-t5-base")
65
+ story_generator = pipeline("text2text-generation", model=story_model, tokenizer=story_tokenizer)
66
+
67
+ # 3. 메인 함수
68
+ def generate_fairytale(image):
69
+ # (1) 이미지 → 캡션 생성
70
+ inputs = caption_processor(images=image, return_tensors="pt").to(caption_model.device)
71
+ outputs = caption_model.generate(**inputs)
72
+ caption = caption_processor.decode(outputs[0], skip_special_tokens=True).strip()
73
+
74
+ # (2) 캡션이 너무 짧으면 보정
75
+ if len(caption.split()) < 5:
76
+ caption += ". They appear to be magical characters from a fantasy world."
77
+
78
+ # (3) 영어 프롬프트 구성
79
+ prompt = (
80
+ f"Write a short and magical fairytale for children based on the description below.\n"
81
+ f"Description: \"{caption}\"\n"
82
+ f"Story:"
83
+ )
84
+
85
+ # (4) 동화 생성
86
+ story = story_generator(prompt, max_length=300, do_sample=True)[0]['generated_text']
87
+
88
+ return caption, story
89
+
90
+ # 4. Gradio UI
91
+ interface = gr.Interface(
92
+ fn=generate_fairytale,
93
+ inputs=gr.Image(type="pil", label="🖼️ Upload an Image"),
94
+ outputs=[
95
+ gr.Textbox(label="📌 Image Description"),
96
+ gr.Textbox(label="📖 Generated Fairytale")
97
+ ],
98
+ title="🧚 AI Fairytale Generator from Image",
99
+ description="Upload an image, and this AI will create a magical story based on it!",
100
+ theme="soft"
101
+ )
102
+
103
+ # 5. 앱 실행
104
+ interface.launch(share=True, debug=True, inbrowser=True)
blip-image-captioning-base02.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import BlipProcessor, BlipForConditionalGeneration
2
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
3
+ from PIL import Image
4
+ import gradio as gr
5
+ import torch
6
+
7
+ # 1. 이미지 캡셔닝 모델 로드 (BLIP)
8
+ caption_processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
9
+ caption_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
10
+
11
+ # 2. 동화 생성 모델 (Flan-T5)
12
+ story_tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-base")
13
+ story_model = AutoModelForSeq2SeqLM.from_pretrained("google/flan-t5-base")
14
+ story_generator = pipeline("text2text-generation", model=story_model, tokenizer=story_tokenizer)
15
+
16
+ # 3. 동화 생성 함수
17
+ def generate_fairytale(image):
18
+ # (1) 이미지 → 캡션
19
+ inputs = caption_processor(images=image, return_tensors="pt").to(caption_model.device)
20
+ outputs = caption_model.generate(**inputs)
21
+ caption = caption_processor.decode(outputs[0], skip_special_tokens=True).strip()
22
+
23
+ # (2) 캡션이 짧으면 보완
24
+ if len(caption.split()) < 5:
25
+ caption += ". They look like magical characters from a fantasy story."
26
+
27
+ # (3) 프롬프트 설정
28
+ prompt = f"""
29
+ Write a magical and imaginative fairytale for children based on the following image description.
30
+
31
+ Description: "{caption}"
32
+
33
+ Your story should:
34
+ - Be at least 3 paragraphs long
35
+ - Start with "Once upon a time"
36
+ - Include fantasy, adventure, or mystery elements
37
+ - Be creative and heartwarming
38
+
39
+ Story:
40
+ """
41
+
42
+ # (4) 동화 생성 (길이 충분히 늘리기)
43
+ story = story_generator(prompt, max_length=500, do_sample=True)[0]['generated_text']
44
+
45
+ return caption, story
46
+
47
+ # 4. Gradio 인터페이스
48
+ interface = gr.Interface(
49
+ fn=generate_fairytale,
50
+ inputs=gr.Image(type="pil", label="🖼️ Upload an Image"),
51
+ outputs=[
52
+ gr.Textbox(label="📌 Image Description"),
53
+ gr.Textbox(label="📖 Generated Fairytale")
54
+ ],
55
+ title="🌟 AI Fairytale Generator from Image",
56
+ description="Upload an image and get a rich fairytale story created from it!",
57
+ theme="soft"
58
+ )
59
+
60
+ # 5. 실행
61
+ interface.launch(share=True, debug=True, inbrowser=True)
62
+
63
+
64
+ # from transformers import BlipProcessor, BlipForConditionalGeneration
65
+ # from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
66
+ # from PIL import Image
67
+ # import gradio as gr
68
+ # import torch
69
+
70
+ # # 1. 이미지 설명 생성 모델 (BLIP)
71
+ # caption_processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
72
+ # caption_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
73
+
74
+ # # 2. 영어 동화 생성 모델 (FLAN-T5)
75
+ # story_tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-base")
76
+ # story_model = AutoModelForSeq2SeqLM.from_pretrained("google/flan-t5-base")
77
+
78
+ # # 3. 동화 생성 함수
79
+ # def generate_fairytale(image):
80
+ # # 1. 이미지 → 텍스트 설명 생성
81
+ # inputs = caption_processor(images=image, return_tensors="pt").to(caption_model.device)
82
+ # outputs = caption_model.generate(**inputs)
83
+ # caption = caption_processor.decode(outputs[0], skip_special_tokens=True).strip()
84
+
85
+ # # 2. 프롬프트 구성 (중복 방지 조건 추가)
86
+ # prompt = f"""Write a magical and imaginative children's story based on the following image description.
87
+ # Description: "{caption}"
88
+ # The story should be at least 3 paragraphs and must not repeat any sentences.
89
+ # Story:"""
90
+
91
+ # # 3. 텍스트 생성
92
+ # input_ids = story_tokenizer(prompt, return_tensors="pt").input_ids.to(story_model.device)
93
+ # output_ids = story_model.generate(
94
+ # input_ids,
95
+ # max_length=600, # 더 길고 풍부한 텍스트
96
+ # num_beams=4, # 빔 탐색
97
+ # no_repeat_ngram_size=3, # 반복 방지
98
+ # repetition_penalty=1.3, # 반복 패널티
99
+ # early_stopping=True,
100
+ # do_sample=False # 확정적 결과
101
+ # )
102
+ # story = story_tokenizer.decode(output_ids[0], skip_special_tokens=True)
103
+
104
+ # return caption, story
105
+
106
+ # # 4. Gradio UI 인터페이스
107
+ # interface = gr.Interface(
108
+ # fn=generate_fairytale,
109
+ # inputs=gr.Image(type="pil", label="📷 Upload an Image"),
110
+ # outputs=[
111
+ # gr.Textbox(label="📌 Image Description"),
112
+ # gr.Textbox(label="📖 Generated Fairytale")
113
+ # ],
114
+ # title="🌟 AI Fairytale Generator from Image",
115
+ # description="Upload an image and get a rich fairytale story created from it!",
116
+ # theme="default"
117
+ # )
118
+
119
+ # # 5. 실행
120
+ # interface.launch(share=True)