Files
aiData/LingYa/testBanana.py
HuangHai 3a0e2c3ec8 'commit'
2026-02-06 08:25:47 +08:00

139 lines
6.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import requests
import json
import time
import os
import sys
# API配置
url = 'https://api.lingyaai.cn/v1/images/generations'
api_key = 'sk-bSjxX2X1FAptXPcBjItcMcbRvcGFZTtRRcUf52BGQr1dscZM'
# 图片保存目录
save_dir = r'd:\dsWork\dsProject\dsLightRag\LingYa\Images'
if not os.path.exists(save_dir):
os.makedirs(save_dir)
# 请求头
headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
style_prompt = (
"Mobile APP UI Design, Full Screen Flat UI Screenshot. "
"View: Direct front view, strictly NO hands, NO holding device. "
"Target Audience: Parents of K12 students. Theme: 'Growth & Nature'. "
"Language: Simplified Chinese (简体中文). "
"Style: Fresh, Creative, Nature-inspired, Clean, Spacious. NOT traditional/boring. "
"Color Palette: Light Green (Primary), Soft White, Earthy accents. Fresh and airy look. "
"Decorations: Green leaves, small growing trees, cute kittens, cartoon style elements. "
"Layout: Creative non-grid layouts, rounded organic shapes, less text density, high visual hierarchy. "
"Quality: 4k resolution, figma style, vector illustration."
)
pages = [
{
"name": "智能档案",
"filename": "SmartArchive.jpg",
"content_prompt": "Page Title: '智能档案' (Smart Archive). "
"HERO SECTION (Top Half): Two Massive, Colorful, Creative Cards for Quick Actions: "
"1. '语音日记' (Voice Diary) with a microphone & kitten icon. "
"2. '拍照识别' (Photo Scan) with a camera & leaf icon. "
"These must be the biggest elements. "
"Growth Section: A beautiful illustration of a 'Growth Tree' (Little Tree) representing the student's progress. "
"Bottom: Minimalist stats summary (no dense tables). "
"Visuals: Fresh green tones, organic shapes, feeling of life and growth."
},
{
"name": "AI军师",
"filename": "AIAdvisor.jpg",
"content_prompt": "Page Title: 'AI军师' (AI Advisor). "
"Character: A friendly 'Professional Cartoon Teacher' (wearing glasses, smart look) or a 'Wise Owl' sitting on a branch. "
"Chat Interface: Clean bubbles floating among falling leaves. "
"Input Area: Modern input field with voice icon. "
"Suggestions: '如何提高专注力?', '考前焦虑怎么办?' displayed as leaves on a vine. "
"Visuals: Calming green background, trustworthy but fun teacher character."
},
{
"name": "知识智库",
"filename": "KnowledgeBase.jpg",
"content_prompt": "Page Title: '知识智库' (Knowledge Base). "
"Layout: 'Garden of Knowledge' concept. "
"Categories: Represented as different plants or fruits (e.g., 'Study Methods' is an Apple tree). "
"Cards: Minimalist cards with high-quality thumbnails (book covers, abstract concepts). "
"Text: Minimal title text, very clean. "
"Visuals: Airy, light, breathable design. No clutter."
},
{
"name": "社区连接",
"filename": "Community.jpg",
"content_prompt": "Page Title: '社区连接' (Community). "
"Layout: Modern Card Feed with soft shadows. "
"Interactions: 'Like' button is a flower blooming, 'Comment' is a leaf. "
"Content: Happy parent sharing a moment (photo of a child smiling). "
"Visuals: Warm community vibe but keeping the fresh green theme. Cartoon avatars for users."
}
]
def log(msg):
print(msg)
with open("test_banana_run.log", "a", encoding="utf-8") as f:
f.write(msg + "\n")
def download_image(url, save_path):
try:
response = requests.get(url, stream=True, timeout=30)
if response.status_code == 200:
with open(save_path, 'wb') as f:
for chunk in response.iter_content(1024):
f.write(chunk)
log(f"✅ 图片已保存: {save_path}")
else:
log(f"❌ 下载失败,状态码: {response.status_code}")
except Exception as e:
log(f"❌ 下载图片失败: {e}")
log(f"开始生成 {len(pages)} 张APP界面设计图并保存至 {save_dir}...\n")
for i, page in enumerate(pages):
log(f"[{i+1}/{len(pages)}] 正在生成: {page['name']} ...")
full_prompt = f"{style_prompt} {page['content_prompt']}"
data = {
"model": "nano-banana-pro",
"prompt": full_prompt,
"n": 1,
"size": "1024x1024",
"response_format": "url"
}
try:
log(f"Sending request for {page['name']}...")
response = requests.post(url, headers=headers, json=data, timeout=60)
if response.status_code == 200:
result = response.json()
img_url = None
if 'data' in result:
if isinstance(result['data'], list) and len(result['data']) > 0:
img_url = result['data'][0].get('url')
elif isinstance(result['data'], dict):
img_url = result['data'].get('url')
if img_url:
log(f"生成成功URL: {img_url}")
save_path = os.path.join(save_dir, page['filename'])
download_image(img_url, save_path)
else:
log(f"❌ 未找到图片URL, 完整响应: {result}")
else:
log(f"❌ 生成失败: {page['name']}")
log(f"状态码: {response.status_code}")
log(f"错误信息: {response.text}")
except Exception as e:
log(f"❌ 请求异常: {e}")
time.sleep(1)