Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,113 +1,70 @@
|
|
| 1 |
-
#
|
| 2 |
-
|
| 3 |
-
鸟类知识科普系统(修正版) by [你的名字]
|
| 4 |
-
ISOM5240 Group Project
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
import gradio as gr
|
| 8 |
-
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
|
| 9 |
from PIL import Image
|
|
|
|
|
|
|
| 10 |
import torch
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
def
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
)
|
| 20 |
|
| 21 |
-
#
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
torch_dtype=torch.bfloat16,
|
| 26 |
-
device_map="auto",
|
| 27 |
-
model_kwargs={
|
| 28 |
-
"load_in_4bit": True,
|
| 29 |
-
"trust_remote_code": True # 必须开启远程代码执行
|
| 30 |
-
}
|
| 31 |
-
)
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
device=0 if torch.cuda.is_available() else -1
|
| 38 |
-
)
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
1. 用动物拟人化的方式描述特征(例如:穿彩色外套的鸟)
|
| 46 |
-
2. 解释生活习性时结合日常场景(如:像小朋友一样喜欢玩耍)
|
| 47 |
-
3. 包含一个趣味冷知识(例如:飞行距离相当于绕操场XX圈)
|
| 48 |
-
4. 语句长度控制在10-15个英文单词
|
| 49 |
-
5. 使用比喻手法代替专业术语"""
|
| 50 |
-
|
| 51 |
-
response = text_generator(
|
| 52 |
-
PROMPT,
|
| 53 |
-
max_new_tokens=150,
|
| 54 |
-
temperature=0.8,
|
| 55 |
-
top_k=40,
|
| 56 |
-
do_sample=True
|
| 57 |
-
)
|
| 58 |
|
| 59 |
-
|
| 60 |
-
cleaned_text = response[0]['generated_text'].split('\n')[2]
|
| 61 |
-
return cleaned_text.replace("**", "") # 去除多余符号
|
| 62 |
|
| 63 |
-
#
|
| 64 |
-
def
|
| 65 |
try:
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
"description": description,
|
| 74 |
-
"audio": speech["audio"]
|
| 75 |
-
}
|
| 76 |
-
except Exception as e:
|
| 77 |
-
return f"处理错误: {str(e)}"
|
| 78 |
|
| 79 |
-
#
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
-
#
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
examples = gr.Examples(
|
| 92 |
-
examples=["eagle.jpg", "penguin.jpg", "peacock.jpg"],
|
| 93 |
-
inputs=image_input,
|
| 94 |
-
label="示例图片"
|
| 95 |
-
)
|
| 96 |
-
|
| 97 |
-
with gr.Column(scale=3):
|
| 98 |
-
name_output = gr.Textbox(label="识别到的鸟类", interactive=False)
|
| 99 |
-
text_output = gr.Textbox(label="趣味知识", lines=4, max_lines=6)
|
| 100 |
-
audio_output = gr.Audio(label="语音讲解", autoplay=True, visible=True)
|
| 101 |
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
# 部署配置(增加硬件检测)
|
| 109 |
-
if torch.cuda.is_available():
|
| 110 |
-
demo.launch(server_name="0.0.0.0", server_port=7860, share=True)
|
| 111 |
-
else:
|
| 112 |
-
print("警告:未检测到GPU,建议在Colab或A10G实例运行")
|
| 113 |
-
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 1 |
+
# 导入必要库
|
| 2 |
+
from transformers import AutoFeatureExtractor, AutoModelForImageClassification
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from PIL import Image
|
| 4 |
+
import requests
|
| 5 |
+
from io import BytesIO
|
| 6 |
import torch
|
| 7 |
+
from transformers import pipeline
|
| 8 |
+
import wikipedia # 用于获取鸟类百科信息
|
| 9 |
+
from wikipedia.exceptions import DisambiguationError, PageError
|
| 10 |
|
| 11 |
+
# 1. 鸟类图片识别(使用指定模型)
|
| 12 |
+
def bird_classification(image_url):
|
| 13 |
+
model_name = "chriamue/bird-species-classifier"
|
| 14 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
|
| 15 |
+
model = AutoModelForImageClassification.from_pretrained(model_name)
|
| 16 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 17 |
+
model.to(device)
|
|
|
|
| 18 |
|
| 19 |
+
# 下载并预处理图片
|
| 20 |
+
response = requests.get(image_url)
|
| 21 |
+
img = Image.open(BytesIO(response.content)).convert("RGB")
|
| 22 |
+
inputs = feature_extractor(img, return_tensors="pt").to(device)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
# 模型推理
|
| 25 |
+
with torch.no_grad():
|
| 26 |
+
outputs = model(**inputs)
|
| 27 |
+
probabilities = torch.nn.functional.softmax(outputs.logits, dim=1)[0]
|
|
|
|
|
|
|
| 28 |
|
| 29 |
+
# 获取前1个预测结果
|
| 30 |
+
predicted_id = torch.argmax(probabilities).item()
|
| 31 |
+
labels = model.config.id2label
|
| 32 |
+
bird_species = labels[predicted_id]
|
| 33 |
+
confidence = round(probabilities[predicted_id].item(), 3)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
+
return bird_species, confidence
|
|
|
|
|
|
|
| 36 |
|
| 37 |
+
# 2. 鸟类信息获取(使用维基百科API)
|
| 38 |
+
def get_bird_info(species_name):
|
| 39 |
try:
|
| 40 |
+
# 去除可能的多余标签(如模型输出中的括号内容)
|
| 41 |
+
clean_name = species_name.split("(")[0].strip()
|
| 42 |
+
# 从维基百科获取摘要(英文转中文)
|
| 43 |
+
summary = wikipedia.summary(clean_name, sentences=3, auto_suggest=False)
|
| 44 |
+
return summary
|
| 45 |
+
except (DisambiguationError, PageError):
|
| 46 |
+
return "抱歉,未找到该鸟类的详细信息。"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
# 3. 文本转语音(使用TTS模型)
|
| 49 |
+
def text_to_speech(text, output_file="bird_info.mp3"):
|
| 50 |
+
tts = pipeline("text-to-speech", model="tts_models/en_US/tacotron2")
|
| 51 |
+
speech = tts(text)
|
| 52 |
+
with open(output_file, "wb") as f:
|
| 53 |
+
f.write(speech["audio"])
|
| 54 |
+
return output_file
|
| 55 |
|
| 56 |
+
# 主函数
|
| 57 |
+
def bird_knowledge_pipeline(image_url):
|
| 58 |
+
# 1. 鸟类识别
|
| 59 |
+
species, confidence = bird_classification(image_url)
|
| 60 |
+
print(f"识别结果:{species}(置信度:{confidence*100:.1f}%)")
|
| 61 |
|
| 62 |
+
# 2. 获取详细信息
|
| 63 |
+
info = get_bird_info(species)
|
| 64 |
+
print(f"鸟类介绍:\n{info}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
+
# 3. 生成语音
|
| 67 |
+
audio_file = text_to_speech(f"这是{species}的介绍:{info}")
|
| 68 |
+
print(f"语音文件已保存:{audio_file}")
|
| 69 |
+
|
| 70 |
+
return species, info, audio_file
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|