logo

手把手教你Python+文心一言:打造AI看图写诗网页

作者:菠萝爱吃肉2025.10.10 16:40浏览量:5

简介:本文详细指导如何用Python和文心一言API搭建《AI看图写诗》网页项目,涵盖环境配置、前端开发、后端集成及完整源码解析。

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

一、项目背景与价值

在AI技术快速发展的今天,图像识别自然语言处理的结合催生了众多创新应用场景。《AI看图写诗》项目通过分析用户上传的图片内容,自动生成与之匹配的诗歌,既可作为创意工具辅助文学创作,也可作为教育平台激发青少年对古典诗词的兴趣。

本项目的核心价值体现在:

  1. 技术融合:整合计算机视觉与NLP两大AI领域
  2. 实践价值:完整展示前后端分离架构的实现过程
  3. 商业潜力:可作为SaaS产品或创意工具进行商业化

二、技术栈选择

2.1 核心组件

  • 前端框架:Flask(轻量级Web框架)
  • 后端服务:Python 3.8+
  • AI引擎:文心一言API(需申请开发者权限)
  • 图像处理:Pillow库(Python图像处理标准库)

2.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 pillow requests

三、系统架构设计

3.1 架构图解

  1. ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
  2. 用户浏览器 │───>│ Flask服务 │───>│ 文心一言API
  3. └─────────────┘ └─────────────┘ └─────────────┘
  4. └────────────────────┘

3.2 关键模块

  1. 图像上传模块:处理多格式图片上传
  2. 预处理模块:调整图片尺寸、提取特征
  3. API调用模块:封装文心一言请求逻辑
  4. 结果展示模块:动态渲染生成的诗歌

四、详细实现步骤

4.1 前端开发(HTML+CSS)

  1. <!-- templates/index.html -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <title>AI看图写诗</title>
  6. <style>
  7. .container { max-width: 800px; margin: 0 auto; }
  8. .preview { max-width: 400px; margin: 20px 0; }
  9. .poem-box {
  10. background: #f5f5f5;
  11. padding: 20px;
  12. border-radius: 8px;
  13. }
  14. </style>
  15. </head>
  16. <body>
  17. <div class="container">
  18. <h1>AI看图写诗</h1>
  19. <form method="post" enctype="multipart/form-data">
  20. <input type="file" name="image" accept="image/*" required>
  21. <button type="submit">生成诗歌</button>
  22. </form>
  23. {% if image_path %}
  24. <img src="{{ image_path }}" class="preview">
  25. {% endif %}
  26. {% if poem %}
  27. <div class="poem-box">
  28. <h3>AI生成的诗歌:</h3>
  29. <pre>{{ poem }}</pre>
  30. </div>
  31. {% endif %}
  32. </div>
  33. </body>
  34. </html>

4.2 后端实现(Python Flask)

  1. # app.py
  2. from flask import Flask, render_template, request
  3. import requests
  4. from PIL import Image
  5. import io
  6. import os
  7. app = Flask(__name__)
  8. app.config['UPLOAD_FOLDER'] = 'static/uploads'
  9. os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
  10. # 文心一言API配置(需替换为实际值)
  11. ERNIE_API_URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions"
  12. ERNIE_API_KEY = "your_api_key"
  13. ERNIE_SECRET_KEY = "your_secret_key"
  14. def get_access_token():
  15. """获取文心一言API访问令牌"""
  16. # 实际实现需通过百度智能云API获取token
  17. pass
  18. def call_ernie_api(prompt):
  19. """调用文心一言API生成诗歌"""
  20. token = get_access_token()
  21. headers = {
  22. 'Content-Type': 'application/json',
  23. 'X-Bce-Signature': 'your_signature',
  24. 'X-Bce-Request-Id': 'your_request_id'
  25. }
  26. payload = {
  27. "messages": [{"role": "user", "content": prompt}]
  28. }
  29. response = requests.post(
  30. ERNIE_API_URL,
  31. headers=headers,
  32. json=payload
  33. )
  34. return response.json().get('result', '')
  35. def process_image(image_file):
  36. """图像预处理"""
  37. img = Image.open(image_file)
  38. img.thumbnail((400, 400))
  39. # 保存处理后的图片
  40. img_path = os.path.join(app.config['UPLOAD_FOLDER'], 'preview.jpg')
  41. img.save(img_path)
  42. return img_path
  43. @app.route('/', methods=['GET', 'POST'])
  44. def index():
  45. poem = None
  46. image_path = None
  47. if request.method == 'POST':
  48. if 'image' not in request.files:
  49. return render_template('index.html', error="请选择图片")
  50. image_file = request.files['image']
  51. if image_file.filename == '':
  52. return render_template('index.html', error="未选择文件")
  53. # 处理图像
  54. image_path = process_image(image_file)
  55. # 生成提示词(示例)
  56. prompt = f"根据这张图片的风格和内容,创作一首五言绝句,要求意境深远,用词典雅。"
  57. # 调用AI生成诗歌
  58. poem = call_ernie_api(prompt)
  59. return render_template('index.html',
  60. image_path=image_path if image_path else None,
  61. poem=poem)
  62. if __name__ == '__main__':
  63. app.run(debug=True)

4.3 文心一言API集成要点

  1. 认证机制:需通过百度智能云控制台获取API Key和Secret Key
  2. 请求格式:遵循JSON-RPC 2.0协议规范
  3. 提示工程:精心设计prompt以获得优质诗歌
    1. # 优化后的prompt示例
    2. optimized_prompt = """
    3. 图片描述:{image_description}
    4. 创作要求:
    5. 1. 体裁:七言律诗
    6. 2. 主题:{theme_suggestion}
    7. 3. 风格:模仿李白诗风
    8. 4. 押韵:平水韵
    9. 请严格按照要求创作,每句七个字,共八句
    10. """

五、完整项目源码结构

  1. ai_poem_project/
  2. ├── app.py # 主程序文件
  3. ├── templates/
  4. └── index.html # 前端页面
  5. ├── static/
  6. └── uploads/ # 图片存储目录
  7. ├── requirements.txt # 依赖包列表
  8. └── README.md # 项目说明

六、部署与优化建议

6.1 生产环境部署

  1. 使用WSGI服务器:推荐Gunicorn或uWSGI

    1. pip install gunicorn
    2. gunicorn -w 4 -b 0.0.0.0:5000 app:app
  2. Nginx反向代理配置示例:

    1. server {
    2. listen 80;
    3. server_name ai-poem.example.com;
    4. location / {
    5. proxy_pass http://127.0.0.1:5000;
    6. proxy_set_header Host $host;
    7. proxy_set_header X-Real-IP $remote_addr;
    8. }
    9. location /static/ {
    10. alias /path/to/ai_poem_project/static/;
    11. }
    12. }

6.2 性能优化方案

  1. 图片处理优化

    • 使用OpenCV替代Pillow进行更高效的图像处理
    • 实现异步图片处理队列
  2. API调用优化

    • 实现请求缓存机制
    • 设置合理的重试策略
  3. 前端优化

    • 添加加载动画
    • 实现AJAX无刷新交互

七、常见问题解决方案

7.1 图片上传失败

  • 检查UPLOAD_FOLDER权限
  • 验证文件大小限制(Flask默认16MB)
    1. app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024 # 10MB

7.2 API调用错误处理

  1. def safe_call_ernie(prompt):
  2. try:
  3. response = call_ernie_api(prompt)
  4. if response.get('error_code'):
  5. raise Exception(f"API错误: {response.get('error_msg')}")
  6. return response.get('result')
  7. except requests.exceptions.RequestException as e:
  8. print(f"请求失败: {str(e)}")
  9. return "生成诗歌时发生错误,请稍后再试"

八、扩展功能建议

  1. 多风格支持

    • 添加风格选择下拉框(唐诗、宋词、现代诗等)
    • 在prompt中动态插入风格参数
  2. 社交分享功能

    • 集成分享到微博、微信的SDK
    • 生成带水印的分享图片
  3. 用户系统

    • 添加注册登录功能
    • 实现诗歌收藏功能

九、总结与展望

本项目完整演示了如何使用Python和文心一言API构建一个实用的AI应用。通过这个项目,开发者可以:

  1. 掌握Flask框架的实际应用
  2. 理解AI API的集成方法
  3. 学习前后端交互的最佳实践

未来发展方向:

  • 接入更先进的图像描述模型(如BLIP-2)
  • 开发移动端APP版本
  • 添加多人协作写诗功能

完整项目源码已附上,建议开发者按照本文步骤逐步实现,在实践过程中深入理解每个技术点的实现原理。遇到问题时,可优先检查API密钥配置、网络连接状态和依赖包版本这三个常见故障点。

相关文章推荐

发表评论

活动