简介:本文详细指导如何用Python和文心一言API搭建AI看图写诗网页应用,涵盖前端交互、后端开发、API调用及完整代码实现,适合开发者快速上手。
本文将通过分步教程,结合Python Flask框架与文心一言API,手把手教你实现一个完整的《AI看图写诗》网页项目。从环境配置、前端界面设计、后端API对接到完整代码实现,覆盖项目开发全流程,并提供可运行的完整源码。适合Python开发者、AI爱好者及教育场景应用。
AI看图写诗结合了计算机视觉与自然语言生成技术,通过分析图片内容自动生成符合意境的诗歌。这种应用在教育领域可辅助诗词教学,在创意领域可激发灵感,在社交场景可增加趣味性。文心一言的中文理解与生成能力使其成为理想选择。
pip install flask requests pillow
flask:Web服务框架requests:HTTP请求库pillow:图像处理库
/ai_poem_project│── app.py # 主程序入口│── templates/│ └── index.html # 前端页面│── static/│ └── style.css # 样式文件│── requirements.txt # 依赖清单
创建templates/index.html,实现以下功能:
<!DOCTYPE html><html><head><title>AI看图写诗</title><link rel="stylesheet" href="/static/style.css"></head><body><div class="container"><h1>AI看图写诗</h1><form id="uploadForm" enctype="multipart/form-data"><input type="file" id="imageInput" accept="image/*" required><button type="submit">生成诗歌</button></form><div id="loading" class="hidden">生成中...</div><div id="result"></div></div><script src="/static/script.js"></script></body></html>
创建app.py,实现以下功能:
from flask import Flask, request, jsonify, render_templateimport requestsimport base64import osapp = Flask(__name__)API_KEY = "你的文心一言API密钥" # 替换为实际密钥API_URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions"def call_ernie_api(prompt):headers = {'Content-Type': 'application/json'}data = {"messages": [{"role": "user", "content": prompt}]}response = requests.post(API_URL,headers=headers,json=data,params={"access_token": API_KEY})return response.json().get("result", "")@app.route('/')def index():return render_template('index.html')@app.route('/generate', methods=['POST'])def generate_poem():if 'image' not in request.files:return jsonify({"error": "未上传图片"}), 400image_file = request.files['image']image_bytes = image_file.read()# 简单图片分析提示词(实际项目可接入CV模型)prompt = f"根据这张图片生成一首中文五言绝句,描述画面意境:"poem = call_ernie_api(prompt)return jsonify({"poem": poem})if __name__ == '__main__':app.run(debug=True)
messages:包含用户输入的对话历史temperature:控制生成随机性(建议0.5-0.8)当前实现使用简单提示词,可扩展:
from PIL import Imageimport iodef analyze_image(image_bytes):# 示例:简单颜色分析(实际可用OpenCV等)img = Image.open(io.BytesIO(image_bytes))colors = img.getcolors(maxcolors=5)dominant_colors = [f"#{r:02x}{g:02x}{b:02x}" for _, (r,g,b) in colors[:3]]return f"图片主要包含{', '.join(dominant_colors)}等色彩"
def build_prompt(image_desc):return f"""你是一位资深诗人,请根据以下描述创作一首中文五言绝句:{image_desc}要求:1. 符合平仄格律2. 意境深远3. 用典自然"""
[GitHub仓库链接](示例,实际应提供真实链接)
包含:
pip install -r requirements.txt
export ERNIE_API_KEY="你的密钥"
python app.pyhttp://localhost:5000@app.after_request处理CORS本项目通过Python与文心一言API的集成,展示了AI在创意领域的应用潜力。关键技术点包括:
未来发展方向:
通过这个项目,开发者可以深入理解AI应用开发的全流程,从需求分析到部署上线,积累宝贵的实战经验。完整源码与详细文档已提供,建议开发者在实际操作中根据需求进行调整优化。