手把手搭建AI诗画网页:Python+文心一言全流程指南
2025.09.19 14:22浏览量:0简介:从零开始用Python和文心一言API构建图像识别与诗歌生成的交互式网页,附完整代码与部署方案
引言:当AI遇见诗画意境
在人工智能技术高速发展的今天,将图像识别与自然语言处理结合的创新应用不断涌现。本文将详细介绍如何使用Python开发框架(Flask)与文心一言API,构建一个可交互的《AI看图写诗》网页项目。用户上传图片后,系统通过图像识别提取关键元素,再调用文心一言生成符合画面意境的诗歌,最终实现”所见即所得”的创作体验。
一、技术选型与架构设计
1.1 核心组件
- 前端框架:HTML5 + CSS3 + JavaScript(基础交互)
- 后端框架:Flask(轻量级Web框架)
- AI能力:文心一言API(文本生成)
- 辅助工具:Pillow(图像处理)、Requests(API调用)
1.2 系统架构
用户浏览器 → Flask服务器 → 文心一言API
↑ ↓
图片上传 诗歌返回 图像预处理
该架构采用前后端分离设计,Flask作为中间层处理业务逻辑,文心一言负责核心AI计算,确保系统可扩展性。
二、开发环境准备
2.1 基础环境配置
# 创建虚拟环境(推荐)
python -m venv ai_poem_env
source ai_poem_env/bin/activate # Linux/Mac
.\ai_poem_env\Scripts\activate # Windows
# 安装依赖包
pip install flask pillow requests
2.2 文心一言API申请
- 访问文心一言开放平台
- 创建应用获取API Key
- 记录以下关键信息:
- API Key
- Secret Key
- 访问域名(需白名单配置)
三、核心功能实现
3.1 Flask项目初始化
from flask import Flask, render_template, request, jsonify
import os
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'static/uploads'
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
3.2 图片上传处理
from PIL import Image
import base64
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['image']
if file:
# 保存原始图片
img_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(img_path)
# 图片预处理(示例:调整大小)
try:
with Image.open(img_path) as img:
img.thumbnail((800, 800))
img.save(img_path)
return process_image(img_path)
except Exception as e:
return jsonify({'error': str(e)})
return render_template('index.html')
3.3 文心一言API调用
import requests
import hashlib
import time
def call_wenxin_api(prompt):
# 实际开发中需替换为真实参数
api_key = "YOUR_API_KEY"
secret_key = "YOUR_SECRET_KEY"
# 生成签名(示例简化版)
timestamp = str(int(time.time()))
signature = hashlib.md5((api_key + secret_key + timestamp).encode()).hexdigest()
headers = {
'Content-Type': 'application/json',
'X-Api-Key': api_key,
'X-Timestamp': timestamp,
'X-Signature': signature
}
data = {
"prompt": f"根据以下图片描述创作一首中文诗歌:{prompt}",
"parameters": {
"temperature": 0.7,
"max_tokens": 200
}
}
response = requests.post(
"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions",
headers=headers,
json=data
)
return response.json().get('result', '')
3.4 图像特征提取(简化版)
def extract_image_features(img_path):
# 实际应用中可接入图像识别API
# 此处模拟返回图像特征
with Image.open(img_path) as img:
width, height = img.size
# 简单特征提取示例
features = {
'dominant_color': '蓝色',
'scene_type': '自然风景',
'elements': ['山', '水', '云']
}
return features
四、完整业务逻辑整合
def process_image(img_path):
# 1. 提取图像特征
features = extract_image_features(img_path)
# 2. 构造AI提示词
prompt = f"画面包含{','.join(features['elements'])}," \
f"以{features['dominant_color']}为主色调," \
f"场景类型为{features['scene_type']}。"
# 3. 调用文心一言生成诗歌
poem = call_wenxin_api(prompt)
# 4. 返回结果(实际项目可渲染到模板)
return jsonify({
'poem': poem,
'features': features,
'image_url': f"/uploads/{os.path.basename(img_path)}"
})
五、前端页面实现
5.1 HTML模板(templates/index.html)
<!DOCTYPE html>
<html>
<head>
<title>AI看图写诗</title>
<style>
.container { max-width: 800px; margin: 0 auto; padding: 20px; }
.preview { margin: 20px 0; text-align: center; }
.poem { font-family: "楷体", cursive; font-size: 18px; line-height: 1.8; }
</style>
</head>
<body>
<div class="container">
<h1>AI看图写诗</h1>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="image" accept="image/*" required>
<button type="submit">生成诗歌</button>
</form>
<div class="preview" id="preview">
<!-- 图片和诗歌将动态插入 -->
</div>
</div>
<script>
document.getElementById('uploadForm').addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const response = await fetch('/', {
method: 'POST',
body: formData
});
const result = await response.json();
if(result.poem) {
document.getElementById('preview').innerHTML = `
<img src="${result.image_url}" style="max-width:100%;">
<div class="poem">${result.poem}</div>
`;
}
});
</script>
</body>
</html>
六、项目部署与优化
6.1 本地测试运行
export FLASK_APP=app.py
flask run --host=0.0.0.0 --port=5000
6.2 生产环境建议
API安全:
- 使用HTTPS加密通信
- 添加请求频率限制
- 实现API Key轮换机制
性能优化:
扩展功能:
- 添加用户系统保存创作历史
- 支持多种诗歌体裁选择
- 实现社交分享功能
七、完整项目源码
# app.py 完整代码
from flask import Flask, render_template, request, jsonify
import os
from PIL import Image
import requests
import hashlib
import time
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'static/uploads'
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
def call_wenxin_api(prompt):
# 实际开发需替换为真实参数
api_key = "YOUR_API_KEY"
secret_key = "YOUR_SECRET_KEY"
timestamp = str(int(time.time()))
signature = hashlib.md5((api_key + secret_key + timestamp).encode()).hexdigest()
headers = {
'Content-Type': 'application/json',
'X-Api-Key': api_key,
'X-Timestamp': timestamp,
'X-Signature': signature
}
data = {
"prompt": f"根据以下图片描述创作一首中文诗歌:{prompt}",
"parameters": {
"temperature": 0.7,
"max_tokens": 200
}
}
response = requests.post(
"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions",
headers=headers,
json=data
)
return response.json().get('result', '')
def extract_image_features(img_path):
# 模拟特征提取
return {
'dominant_color': '蓝色',
'scene_type': '自然风景',
'elements': ['山', '水', '云']
}
def process_image(img_path):
features = extract_image_features(img_path)
prompt = f"画面包含{','.join(features['elements'])}," \
f"以{features['dominant_color']}为主色调," \
f"场景类型为{features['scene_type']}。"
poem = call_wenxin_api(prompt)
return {
'poem': poem,
'image_url': f"/uploads/{os.path.basename(img_path)}"
}
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['image']
if file:
img_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(img_path)
try:
with Image.open(img_path) as img:
img.thumbnail((800, 800))
img.save(img_path)
return jsonify(process_image(img_path))
except Exception as e:
return jsonify({'error': str(e)})
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
八、技术延伸与进阶
- 多模态融合:结合图像语义分割与文本情感分析
- 风格定制:训练微调模型实现特定诗人风格模仿
- 实时交互:使用WebSocket实现流式诗歌生成
- 移动适配:开发PWA应用支持离线使用
结语:AI创作的无限可能
本项目展示了如何通过简单技术栈实现AI与艺术的跨界融合。开发者可基于此框架进一步探索:接入更精确的图像识别API、优化提示词工程、添加多语言支持等。随着AI技术的演进,这类应用将在文化创意领域发挥更大价值。
完整项目代码已提供核心实现,实际部署时需注意:
- 替换API Key为真实凭证
- 添加错误处理和日志记录
- 考虑使用环境变量管理敏感信息
- 遵守各平台API调用规范
希望这个项目能激发更多开发者探索AI与人文结合的创新应用!
发表评论
登录后可评论,请前往 登录 或 注册