logo

手把手搭建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 系统架构

  1. 用户浏览器 Flask服务器 文心一言API
  2. 图片上传 诗歌返回 图像预处理

该架构采用前后端分离设计,Flask作为中间层处理业务逻辑,文心一言负责核心AI计算,确保系统可扩展性。

二、开发环境准备

2.1 基础环境配置

  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

2.2 文心一言API申请

  1. 访问文心一言开放平台
  2. 创建应用获取API Key
  3. 记录以下关键信息:
    • API Key
    • Secret Key
    • 访问域名(需白名单配置)

三、核心功能实现

3.1 Flask项目初始化

  1. from flask import Flask, render_template, request, jsonify
  2. import os
  3. app = Flask(__name__)
  4. app.config['UPLOAD_FOLDER'] = 'static/uploads'
  5. os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

3.2 图片上传处理

  1. from PIL import Image
  2. import base64
  3. @app.route('/', methods=['GET', 'POST'])
  4. def upload_file():
  5. if request.method == 'POST':
  6. file = request.files['image']
  7. if file:
  8. # 保存原始图片
  9. img_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
  10. file.save(img_path)
  11. # 图片预处理(示例:调整大小)
  12. try:
  13. with Image.open(img_path) as img:
  14. img.thumbnail((800, 800))
  15. img.save(img_path)
  16. return process_image(img_path)
  17. except Exception as e:
  18. return jsonify({'error': str(e)})
  19. return render_template('index.html')

3.3 文心一言API调用

  1. import requests
  2. import hashlib
  3. import time
  4. def call_wenxin_api(prompt):
  5. # 实际开发中需替换为真实参数
  6. api_key = "YOUR_API_KEY"
  7. secret_key = "YOUR_SECRET_KEY"
  8. # 生成签名(示例简化版)
  9. timestamp = str(int(time.time()))
  10. signature = hashlib.md5((api_key + secret_key + timestamp).encode()).hexdigest()
  11. headers = {
  12. 'Content-Type': 'application/json',
  13. 'X-Api-Key': api_key,
  14. 'X-Timestamp': timestamp,
  15. 'X-Signature': signature
  16. }
  17. data = {
  18. "prompt": f"根据以下图片描述创作一首中文诗歌:{prompt}",
  19. "parameters": {
  20. "temperature": 0.7,
  21. "max_tokens": 200
  22. }
  23. }
  24. response = requests.post(
  25. "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions",
  26. headers=headers,
  27. json=data
  28. )
  29. return response.json().get('result', '')

3.4 图像特征提取(简化版)

  1. def extract_image_features(img_path):
  2. # 实际应用中可接入图像识别API
  3. # 此处模拟返回图像特征
  4. with Image.open(img_path) as img:
  5. width, height = img.size
  6. # 简单特征提取示例
  7. features = {
  8. 'dominant_color': '蓝色',
  9. 'scene_type': '自然风景',
  10. 'elements': ['山', '水', '云']
  11. }
  12. return features

四、完整业务逻辑整合

  1. def process_image(img_path):
  2. # 1. 提取图像特征
  3. features = extract_image_features(img_path)
  4. # 2. 构造AI提示词
  5. prompt = f"画面包含{','.join(features['elements'])}," \
  6. f"以{features['dominant_color']}为主色调," \
  7. f"场景类型为{features['scene_type']}。"
  8. # 3. 调用文心一言生成诗歌
  9. poem = call_wenxin_api(prompt)
  10. # 4. 返回结果(实际项目可渲染到模板)
  11. return jsonify({
  12. 'poem': poem,
  13. 'features': features,
  14. 'image_url': f"/uploads/{os.path.basename(img_path)}"
  15. })

五、前端页面实现

5.1 HTML模板(templates/index.html)

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>AI看图写诗</title>
  5. <style>
  6. .container { max-width: 800px; margin: 0 auto; padding: 20px; }
  7. .preview { margin: 20px 0; text-align: center; }
  8. .poem { font-family: "楷体", cursive; font-size: 18px; line-height: 1.8; }
  9. </style>
  10. </head>
  11. <body>
  12. <div class="container">
  13. <h1>AI看图写诗</h1>
  14. <form id="uploadForm" enctype="multipart/form-data">
  15. <input type="file" name="image" accept="image/*" required>
  16. <button type="submit">生成诗歌</button>
  17. </form>
  18. <div class="preview" id="preview">
  19. <!-- 图片和诗歌将动态插入 -->
  20. </div>
  21. </div>
  22. <script>
  23. document.getElementById('uploadForm').addEventListener('submit', async (e) => {
  24. e.preventDefault();
  25. const formData = new FormData(e.target);
  26. const response = await fetch('/', {
  27. method: 'POST',
  28. body: formData
  29. });
  30. const result = await response.json();
  31. if(result.poem) {
  32. document.getElementById('preview').innerHTML = `
  33. <img src="${result.image_url}" style="max-width:100%;">
  34. <div class="poem">${result.poem}</div>
  35. `;
  36. }
  37. });
  38. </script>
  39. </body>
  40. </html>

六、项目部署与优化

6.1 本地测试运行

  1. export FLASK_APP=app.py
  2. flask run --host=0.0.0.0 --port=5000

6.2 生产环境建议

  1. API安全

    • 使用HTTPS加密通信
    • 添加请求频率限制
    • 实现API Key轮换机制
  2. 性能优化

    • 添加缓存层(Redis存储诗歌结果)
    • 实现异步任务队列(Celery处理耗时操作)
    • 图片压缩与CDN加速
  3. 扩展功能

    • 添加用户系统保存创作历史
    • 支持多种诗歌体裁选择
    • 实现社交分享功能

七、完整项目源码

  1. # app.py 完整代码
  2. from flask import Flask, render_template, request, jsonify
  3. import os
  4. from PIL import Image
  5. import requests
  6. import hashlib
  7. import time
  8. app = Flask(__name__)
  9. app.config['UPLOAD_FOLDER'] = 'static/uploads'
  10. os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
  11. def call_wenxin_api(prompt):
  12. # 实际开发需替换为真实参数
  13. api_key = "YOUR_API_KEY"
  14. secret_key = "YOUR_SECRET_KEY"
  15. timestamp = str(int(time.time()))
  16. signature = hashlib.md5((api_key + secret_key + timestamp).encode()).hexdigest()
  17. headers = {
  18. 'Content-Type': 'application/json',
  19. 'X-Api-Key': api_key,
  20. 'X-Timestamp': timestamp,
  21. 'X-Signature': signature
  22. }
  23. data = {
  24. "prompt": f"根据以下图片描述创作一首中文诗歌:{prompt}",
  25. "parameters": {
  26. "temperature": 0.7,
  27. "max_tokens": 200
  28. }
  29. }
  30. response = requests.post(
  31. "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions",
  32. headers=headers,
  33. json=data
  34. )
  35. return response.json().get('result', '')
  36. def extract_image_features(img_path):
  37. # 模拟特征提取
  38. return {
  39. 'dominant_color': '蓝色',
  40. 'scene_type': '自然风景',
  41. 'elements': ['山', '水', '云']
  42. }
  43. def process_image(img_path):
  44. features = extract_image_features(img_path)
  45. prompt = f"画面包含{','.join(features['elements'])}," \
  46. f"以{features['dominant_color']}为主色调," \
  47. f"场景类型为{features['scene_type']}。"
  48. poem = call_wenxin_api(prompt)
  49. return {
  50. 'poem': poem,
  51. 'image_url': f"/uploads/{os.path.basename(img_path)}"
  52. }
  53. @app.route('/', methods=['GET', 'POST'])
  54. def upload_file():
  55. if request.method == 'POST':
  56. file = request.files['image']
  57. if file:
  58. img_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
  59. file.save(img_path)
  60. try:
  61. with Image.open(img_path) as img:
  62. img.thumbnail((800, 800))
  63. img.save(img_path)
  64. return jsonify(process_image(img_path))
  65. except Exception as e:
  66. return jsonify({'error': str(e)})
  67. return render_template('index.html')
  68. if __name__ == '__main__':
  69. app.run(debug=True)

八、技术延伸与进阶

  1. 多模态融合:结合图像语义分割与文本情感分析
  2. 风格定制:训练微调模型实现特定诗人风格模仿
  3. 实时交互:使用WebSocket实现流式诗歌生成
  4. 移动适配:开发PWA应用支持离线使用

结语:AI创作的无限可能

本项目展示了如何通过简单技术栈实现AI与艺术的跨界融合。开发者可基于此框架进一步探索:接入更精确的图像识别API、优化提示词工程、添加多语言支持等。随着AI技术的演进,这类应用将在文化创意领域发挥更大价值。

完整项目代码已提供核心实现,实际部署时需注意:

  1. 替换API Key为真实凭证
  2. 添加错误处理和日志记录
  3. 考虑使用环境变量管理敏感信息
  4. 遵守各平台API调用规范

希望这个项目能激发更多开发者探索AI与人文结合的创新应用!

相关文章推荐

发表评论