logo

手把手搭建AI诗画:Python+文心一言全流程指南

作者:JC2025.09.26 18:46浏览量:1

简介:本文详细指导如何用Python和文心一言API构建《AI看图写诗》网页应用,包含环境配置、接口调用、前端交互全流程,附完整可运行源码。

手把手带你用Python和文心一言搭建《AI看图写诗》网页项目(附完整源码)

一、项目概述与价值

在AI技术普及的今天,让计算机理解图像内容并生成富有诗意的文字描述,已成为极具创新性的应用场景。本项目通过整合Python后端、Flask框架和文心一言(ERNIE Bot)的API,构建一个用户上传图片后自动生成对应诗歌的网页应用。该方案不仅展示了多模态AI的应用潜力,也为教育、文化创意等领域提供了实用工具。

核心价值点:

  1. 技术融合:结合计算机视觉(图片解析)与自然语言生成(NLP)
  2. 低门槛实现:无需训练模型,直接调用文心一言API
  3. 完整交付:提供从环境配置到部署上线的全流程指导

二、技术栈与先决条件

2.1 技术组件

组件 版本 用途
Python 3.8+ 后端逻辑
Flask 2.0+ Web服务框架
文心一言API 最新版 诗歌生成引擎
HTML/CSS - 前端界面
Bootstrap 5.0+ 响应式布局

2.2 开发前准备

  1. API密钥申请

  2. 环境配置

    1. # 创建虚拟环境(推荐)
    2. python -m venv ai_poem_env
    3. source ai_poem_env/bin/activate # Linux/Mac
    4. # ai_poem_env\Scripts\activate # Windows
    5. # 安装依赖
    6. pip install flask requests python-dotenv

三、核心开发步骤

3.1 项目结构规划

  1. ai_poem_project/
  2. ├── app.py # Flask主程序
  3. ├── templates/
  4. └── index.html # 前端页面
  5. ├── static/
  6. ├── css/
  7. └── style.css # 自定义样式
  8. └── js/
  9. └── main.js # 前端交互逻辑
  10. ├── .env # 环境变量配置
  11. └── requirements.txt # 依赖清单

3.2 文心一言API集成

3.2.1 获取Access Token

  1. import requests
  2. import base64
  3. import json
  4. from datetime import datetime, timedelta
  5. def get_access_token(api_key, secret_key):
  6. url = "https://aip.baidubce.com/oauth/2.0/token"
  7. params = {
  8. "grant_type": "client_credentials",
  9. "client_id": api_key,
  10. "client_secret": secret_key
  11. }
  12. response = requests.post(url, params=params)
  13. return response.json().get("access_token")

3.2.2 调用诗歌生成接口

  1. def generate_poem(access_token, image_desc):
  2. api_url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions"
  3. headers = {
  4. 'Content-Type': 'application/json'
  5. }
  6. data = {
  7. "messages": [
  8. {
  9. "role": "user",
  10. "content": f"根据以下图片描述创作一首中文古诗(五言或七言绝句):{image_desc}"
  11. }
  12. ]
  13. }
  14. params = {"access_token": access_token}
  15. response = requests.post(api_url, headers=headers, params=params, data=json.dumps(data))
  16. return response.json().get("result", "")

3.3 Flask后端实现

3.3.1 主程序(app.py)

  1. from flask import Flask, render_template, request, jsonify
  2. import os
  3. from dotenv import load_dotenv
  4. from utils import get_access_token, generate_poem # 自定义工具模块
  5. load_dotenv()
  6. app = Flask(__name__)
  7. # 缓存access_token(实际项目应考虑过期刷新)
  8. ACCESS_TOKEN = None
  9. @app.route('/')
  10. def index():
  11. return render_template('index.html')
  12. @app.route('/generate_poem', methods=['POST'])
  13. def generate_poem_route():
  14. global ACCESS_TOKEN
  15. if not ACCESS_TOKEN:
  16. ACCESS_TOKEN = get_access_token(
  17. os.getenv('API_KEY'),
  18. os.getenv('SECRET_KEY')
  19. )
  20. image_desc = request.json.get('image_desc')
  21. if not image_desc:
  22. return jsonify({"error": "图片描述不能为空"}), 400
  23. poem = generate_poem(ACCESS_TOKEN, image_desc)
  24. return jsonify({"poem": poem})
  25. if __name__ == '__main__':
  26. app.run(debug=True)

3.4 前端实现

3.4.1 HTML模板(index.html)

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>AI看图写诗</title>
  7. <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  8. <link rel="stylesheet" href="/static/css/style.css">
  9. </head>
  10. <body>
  11. <div class="container mt-5">
  12. <h1 class="text-center mb-4">AI看图写诗</h1>
  13. <div class="card">
  14. <div class="card-body">
  15. <form id="poemForm">
  16. <div class="mb-3">
  17. <label for="imageUpload" class="form-label">上传图片</label>
  18. <input class="form-control" type="file" id="imageUpload" accept="image/*">
  19. </div>
  20. <div class="mb-3">
  21. <label for="imageDesc" class="form-label">或输入图片描述</label>
  22. <textarea class="form-control" id="imageDesc" rows="3"></textarea>
  23. </div>
  24. <button type="submit" class="btn btn-primary">生成诗歌</button>
  25. </form>
  26. <div id="result" class="mt-4 p-3 border rounded" style="display:none;">
  27. <h5>生成的诗歌:</h5>
  28. <pre id="poemContent"></pre>
  29. </div>
  30. </div>
  31. </div>
  32. </div>
  33. <script src="/static/js/main.js"></script>
  34. </body>
  35. </html>

3.4.2 JavaScript交互(main.js)

  1. document.getElementById('poemForm').addEventListener('submit', async (e) => {
  2. e.preventDefault();
  3. const fileInput = document.getElementById('imageUpload');
  4. const descInput = document.getElementById('imageDesc');
  5. const resultDiv = document.getElementById('result');
  6. const poemContent = document.getElementById('poemContent');
  7. let imageDesc = '';
  8. if (fileInput.files.length > 0) {
  9. // 实际项目应在此处添加图片解析逻辑
  10. // 这里简化处理,直接使用描述框内容
  11. imageDesc = "一幅山水画,有青山绿水,云雾缭绕";
  12. } else if (descInput.value.trim()) {
  13. imageDesc = descInput.value.trim();
  14. } else {
  15. alert('请上传图片或输入描述');
  16. return;
  17. }
  18. try {
  19. const response = await fetch('/generate_poem', {
  20. method: 'POST',
  21. headers: {
  22. 'Content-Type': 'application/json',
  23. },
  24. body: JSON.stringify({ image_desc: imageDesc })
  25. });
  26. const data = await response.json();
  27. if (data.error) {
  28. throw new Error(data.error);
  29. }
  30. poemContent.textContent = data.poem;
  31. resultDiv.style.display = 'block';
  32. } catch (error) {
  33. alert(`生成失败: ${error.message}`);
  34. }
  35. });

四、完整项目源码与部署指南

4.1 源码获取方式

完整项目源码已上传至GitHub:AI-Poem-Generator(示例链接,实际使用时请替换)

4.2 部署步骤

  1. 本地运行

    1. # 克隆仓库后
    2. pip install -r requirements.txt
    3. python app.py

    访问 http://localhost:5000

  2. 生产环境部署(以Nginx+Gunicorn为例):

    1. # 安装Gunicorn
    2. pip install gunicorn
    3. # 启动服务(后台运行)
    4. gunicorn -w 4 -b 0.0.0.0:8000 app:app
    5. # Nginx配置示例
    6. server {
    7. listen 80;
    8. server_name your-domain.com;
    9. location / {
    10. proxy_pass http://127.0.0.1:8000;
    11. proxy_set_header Host $host;
    12. proxy_set_header X-Real-IP $remote_addr;
    13. }
    14. }

五、项目优化方向

  1. 图片解析增强

    • 集成OpenCV进行基础图像分析
    • 使用预训练模型提取关键元素(如山水、人物等)
  2. 性能优化

    • 实现Access Token的自动刷新机制
    • 添加请求缓存层(Redis
  3. 用户体验改进

    • 增加诗歌风格选择(五言/七言/现代诗)
    • 添加历史记录功能

六、常见问题解决方案

  1. API调用失败

    • 检查API密钥是否正确
    • 确认账号是否有足够调用配额
  2. 诗歌质量不理想

    • 优化提示词(Prompt Engineering)
    • 示例改进:
      1. prompt = f"""
      2. 请根据以下描述创作一首{style}:
      3. {image_desc}
      4. 要求:
      5. 1. 符合{poem_type}格式
      6. 2. 押韵工整
      7. 3. 意境深远
      8. """
  3. 跨域问题

    • 在Flask中添加CORS支持:
      1. from flask_cors import CORS
      2. app = Flask(__name__)
      3. CORS(app)

七、技术延伸思考

  1. 多模型对比

    • 可替换为其他大模型API(如GPT、通义千问)进行效果对比
  2. 训练专属模型

    • 收集用户反馈数据,微调诗歌生成模型
  3. 商业化路径

    • 开发SaaS平台,提供API接口服务
    • 定制企业版,集成至文化旅游、教育等行业

本项目的完整实现展示了如何快速构建AI应用,开发者可根据实际需求进行功能扩展。建议首次实现时优先保证核心功能稳定,再逐步添加高级特性。

发表评论

活动