手把手教你用Python+文心一言搭建AI看图写诗系统
2025.09.18 18:04浏览量:0简介:零基础搭建AI看图写诗网页应用,完整源码+技术解析+部署指南
手把手教你用Python+文心一言搭建AI看图写诗系统
一、项目背景与技术选型
在AI技术快速发展的今天,将图像识别与自然语言处理结合的创意应用成为热门方向。本项目通过Python构建Web服务,集成文心一言大模型实现”看图写诗”功能,用户上传图片后系统自动生成符合意境的诗歌。
技术选型方面:
- 后端框架:Flask轻量级Web框架(也可替换为FastAPI)
- 图像处理:Pillow库进行基础图像处理
- AI模型:文心一言API提供文本生成能力
- 前端交互:HTML5+Bootstrap实现响应式界面
- 部署方案:支持本地调试与云服务器部署
二、开发环境准备
2.1 系统要求
- Python 3.7+
- 推荐使用虚拟环境(venv或conda)
- 文心一言API密钥(需申请)
2.2 依赖安装
pip install flask pillow requests python-dotenv
2.3 目录结构
/ai_poetry_project
├── app.py # 主程序
├── templates/
│ └── index.html # 前端页面
├── static/
│ └── style.css # 样式文件
├── utils/
│ ├── image_processor.py # 图像处理
│ └── api_client.py # API调用
└── .env # 环境变量
三、核心功能实现
3.1 图像处理模块
# utils/image_processor.py
from PIL import Image
import io
import base64
def process_image(image_bytes):
"""基础图像处理:调整大小、格式转换"""
try:
img = Image.open(io.BytesIO(image_bytes))
# 调整为统一尺寸(示例:300x300)
img = img.resize((300, 300))
buffered = io.BytesIO()
img.save(buffered, format="JPEG")
return buffered.getvalue()
except Exception as e:
print(f"Image processing error: {e}")
return None
3.2 文心一言API集成
# utils/api_client.py
import requests
import os
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.getenv("ERNIE_API_KEY")
SECRET_KEY = os.getenv("ERNIE_SECRET_KEY")
def generate_poem(image_description):
"""调用文心一言生成诗歌"""
url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions"
headers = {
'Content-Type': 'application/json'
}
data = {
"messages": [
{
"role": "user",
"content": f"根据以下描述创作一首中文古诗:{image_description}\n要求:五言或七言,押平声韵"
}
]
}
try:
response = requests.post(url, json=data, headers=headers)
result = response.json()
return result.get("result", "")
except Exception as e:
print(f"API call failed: {e}")
return "生成诗歌时发生错误"
3.3 Flask主程序
# app.py
from flask import Flask, render_template, request, jsonify
from utils.image_processor import process_image
from utils.api_client import generate_poem
import os
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'static/uploads'
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/generate', methods=['POST'])
def generate():
if 'file' not in request.files:
return jsonify({"error": "No file uploaded"}), 400
file = request.files['file']
img_bytes = file.read()
# 简单图像处理(实际项目可增强)
processed_img = process_image(img_bytes)
# 生成描述(简化版,实际可用CLIP等模型)
description = "一幅美丽的山水画,有青山绿水" # 实际项目应替换为图像描述生成
# 调用文心一言
poem = generate_poem(description)
return jsonify({
"poem": poem,
# 可返回处理后的图片base64编码
})
if __name__ == '__main__':
app.run(debug=True)
四、前端实现要点
4.1 HTML结构
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
<title>AI看图写诗</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
.preview-area { max-width: 400px; margin: 20px auto; }
.poem-result { font-family: "KaiTi", serif; margin-top: 30px; }
</style>
</head>
<body>
<div class="container mt-5">
<h1 class="text-center">AI看图写诗</h1>
<div class="card mt-4">
<div class="card-body">
<form id="uploadForm" enctype="multipart/form-data">
<div class="mb-3">
<label for="imageUpload" class="form-label">选择图片</label>
<input class="form-control" type="file" id="imageUpload" accept="image/*" required>
</div>
<button type="submit" class="btn btn-primary">生成诗歌</button>
</form>
<div class="preview-area text-center">
<img id="imagePreview" style="max-width:100%; display:none;">
</div>
<div id="poemResult" class="poem-result text-center"></div>
</div>
</div>
</div>
<script>
document.getElementById('uploadForm').addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData();
const fileInput = document.getElementById('imageUpload');
formData.append('file', fileInput.files[0]);
// 显示预览
const reader = new FileReader();
reader.onload = (e) => {
document.getElementById('imagePreview').src = e.target.result;
document.getElementById('imagePreview').style.display = 'block';
};
reader.readAsDataURL(fileInput.files[0]);
// 调用API
const response = await fetch('/generate', {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.poem) {
document.getElementById('poemResult').innerHTML = `
<h4>生成的诗歌:</h4>
<pre>${result.poem}</pre>
`;
}
});
</script>
</body>
</html>
五、部署与优化建议
5.1 本地调试
# 设置环境变量
export ERNIE_API_KEY="your_api_key"
export ERNIE_SECRET_KEY="your_secret_key"
# 运行应用
python app.py
5.2 生产部署方案
Nginx + Gunicorn:
pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:5000 app:app
Docker化部署:
FROM python:3.9-slim
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:5000", "app:app"]
5.3 性能优化方向
- 添加图片压缩中间件
- 实现API调用缓存
- 增加异步任务队列(Celery)
- 添加用户认证系统
- 实现诗歌历史记录功能
六、完整源码获取
项目完整源码已上传至GitHub:[示例链接](实际发布时替换为真实链接),包含:
- 所有源代码文件
- 部署说明文档
- 常见问题解答
- 扩展功能建议
七、技术延伸思考
- 多模态融合:可集成CLIP模型实现更精准的图像描述
- 诗歌风格定制:通过prompt工程支持不同诗体(唐诗、宋词等)
- 社交功能:添加诗歌分享、点赞功能
- 移动端适配:开发PWA或小程序版本
本项目的核心价值在于展示了如何快速集成先进AI能力到Web应用中,开发者可根据实际需求进行功能扩展。建议初学者先完成基础版本,再逐步添加高级功能。
八、常见问题解决
- API调用失败:检查密钥配置和网络连接
- 图片上传失败:确认Nginx配置的client_max_body_size
- 诗歌质量不佳:优化prompt描述或尝试不同模型参数
- 跨域问题:在Flask中添加CORS支持
通过这个项目,开发者不仅能掌握Python Web开发技能,还能深入理解AI模型的应用方式,为开发更复杂的AI应用打下基础。
发表评论
登录后可评论,请前往 登录 或 注册