sshenai commited on
Commit
8ca204e
·
verified ·
1 Parent(s): 4de0974

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -48
app.py CHANGED
@@ -1,57 +1,103 @@
1
- # 导入库
2
- from transformers import VisionEncoderDecoderModel, ViTFeatureExtractor, AutoTokenizer
3
  from PIL import Image
4
  import torch
5
- from transformers import pipeline
6
- import requests
7
- from io import BytesIO
8
 
9
- # 1. 图像标题生成(使用指定模型)
10
- def generate_caption(image_url):
11
- model_name = "bipin/image-caption-generator"
12
- model = VisionEncoderDecoderModel.from_pretrained(model_name)
13
- feature_extractor = ViTFeatureExtractor.from_pretrained(model_name)
14
- tokenizer = AutoTokenizer.from_pretrained("gpt2")
15
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
16
- model.to(device)
17
-
18
- # 下载并预处理图像
19
- response = requests.get(image_url)
20
- img = Image.open(BytesIO(response.content)).convert("RGB")
21
- pixel_values = feature_extractor(images=[img], return_tensors="pt").pixel_values.to(device)
22
-
23
- # 生成标题(限制50字内)
24
- output_ids = model.generate(pixel_values, num_beams=4, max_length=50)
25
- caption = tokenizer.decode(output_ids[0], skip_special_tokens=True)
26
- return caption
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
- # 2. 标题扩写为宣传文案(使用文本生成模型)
29
- def expand_to_copy(caption):
30
- generator = pipeline("text-generation", model="gpt2", max_length=200)
31
- prompt = f"根据以下图片标题生成宣传文案:{caption}\n要求:生动形象,突出产品优势,适合社交媒体传播。"
32
- copy = generator(prompt, num_return_sequences=1)[0]['generated_text']
33
- return copy.strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
- # 3. 文本转语音(使用TTS模型)
36
- def text_to_speech(text, output_file="output.mp3"):
37
- tts = pipeline("text-to-speech", model="facebook/t5-small")
38
- speech = tts(text)
39
- with open(output_file, "wb") as f:
40
- f.write(speech["audio"])
41
- return output_file
42
 
43
- # 主函数
44
- def marketing_pipeline(image_url):
45
- # 生成标题
46
- caption = generate_caption(image_url)
47
- print(f"生成标题:{caption}")
48
 
49
- # 扩写文案
50
- copy = expand_to_copy(caption)
51
- print(f"宣传文案:\n{copy}")
52
 
53
- # 生成语音
54
- audio_file = text_to_speech(copy)
55
- print(f"语音文件已保存:{audio_file}")
56
 
57
- return caption, copy, audio_file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
  from PIL import Image
4
  import torch
 
 
 
5
 
6
+ # 初始化模型(缓存加载)
7
+ def init_models():
8
+ # 鸟类分类模型
9
+ classifier = pipeline(
10
+ "image-classification",
11
+ model="chriamue/bird-species-classifier",
12
+ device=0 if torch.cuda.is_available() else -1
13
+ )
14
+
15
+ # 文本生成模型(设置量化降低显存占用)
16
+ text_generator = pipeline(
17
+ "text-generation",
18
+ model="Qwen/Qwen3-235B-A22B",
19
+ torch_dtype=torch.bfloat16,
20
+ device_map="auto",
21
+ model_kwargs={"load_in_4bit": True}
22
+ )
23
+
24
+ # 语音合成模型
25
+ tts = pipeline(
26
+ "text-to-speech",
27
+ model="facebook/mms-tts-eng",
28
+ device=0 if torch.cuda.is_available() else -1
29
+ )
30
+
31
+ return classifier, text_generator, tts
32
+
33
+ # 生成儿童友好的鸟类描述
34
+ def generate_child_friendly_text(bird_name):
35
+ PROMPT = f"""请用简单易懂的语言,向6-12岁儿童介绍{bird_name}:
36
+ 1. 用比喻手法描述外形特征
37
+ 2. 解释生活习性时使用拟人化
38
+ 3. 包含一个有趣的小知识
39
+ 4. 语句长度不超过15个英文单词
40
+ 5. 避免使用专业术语"""
41
+
42
+ response = text_generator(
43
+ PROMPT,
44
+ max_new_tokens=200,
45
+ temperature=0.7,
46
+ do_sample=True
47
+ )
48
+
49
+ return response[0]['generated_text'].split('\n')[2:] # 提取核心内容
50
 
51
+ # 主处理流程
52
+ def process_image(image):
53
+ try:
54
+ # Step 1: 鸟类识别
55
+ classification = classifier(image)
56
+ bird_name = classification[0]['label']
57
+
58
+ # Step 2: 生成描述
59
+ description = generate_child_friendly_text(bird_name)
60
+
61
+ # Step 3: 语音合成
62
+ speech = tts(description, forward_params={"speaker_id": 6}) # 使用儿童语音
63
+
64
+ return {
65
+ "bird_name": bird_name,
66
+ "description": "\n".join(description),
67
+ "audio": speech["audio"]
68
+ }
69
+ except Exception as e:
70
+ return f"处理错误: {str(e)}"
71
 
72
+ # 初始化模型
73
+ classifier, text_generator, tts = init_models()
 
 
 
 
 
74
 
75
+ # 创建Gradio界面
76
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
77
+ gr.Markdown("# 🐦 鸟类知识小课堂")
 
 
78
 
79
+ with gr.Row():
80
+ image_input = gr.Image(type="pil", label="上传鸟类图片")
81
+ audio_output = gr.Audio(label="语音讲解", autoplay=True)
82
 
83
+ with gr.Column():
84
+ name_output = gr.Textbox(label="识别到的鸟类")
85
+ text_output = gr.Textbox(label="趣味知识", lines=4)
86
 
87
+ examples = gr.Examples(
88
+ examples=["eagle.jpg", "penguin.jpg", "peacock.jpg"],
89
+ inputs=image_input
90
+ )
91
+
92
+ image_input.change(
93
+ process_image,
94
+ inputs=image_input,
95
+ outputs=[name_output, text_output, audio_output]
96
+ )
97
+
98
+ # 部署配置
99
+ demo.launch(
100
+ server_name="0.0.0.0",
101
+ server_port=7860,
102
+ share=True
103
+ )