Error in user YAML: (<unknown>): could not find expected ':' while scanning a simple key at line 3 column 1
---
- oeasy Python 0791
- 这是 oeasy 系统化 Python 教程,从基础一步步讲,扎实、完整、不跳步。愿意花时间学,就能真正学会。
本教程同步发布在:
个人网站: `https://oeasy.org`
蓝桥云课: `https://www.lanqiao.cn/courses/3584`
GitHub: `https://github.com/overmind1980/oeasy-python-tutorial`
Gitee: `https://gitee.com/overmind1980/oeasypython`
---firefox http://modelscope.cn
- 首先要注册魔搭社区
- 注意魔搭社区要使用阿里云上的资源
- 需要授权
- 点击 模型库
- 文生图
- 筛选 支持体验
API-inference
- 单词解释
API >> Application Programming Interface >>> 应用程序接口
inference >> 推理 >>> 可以直接在服务器
云端推理
- 进入模型页面后
- 体验 在线推理
一个小丑在北海公园的白塔下面吃面条
- 输入关键词
- 如何编程实现呢?
- 魔搭社区 根据你的登录状态
- 会找到你的api-key
- 然后生成代码
cd Code
vi txt2img.py
- 运行文生图代码
- 如果在蓝桥运行 需要有网络
- 可能需要会员权限
import requests
import time
import json
from PIL import Image
from io import BytesIO
base_url = 'https://api-inference.modelscope.cn/'
api_key = "ms-81c1f87a-fa0a-4edc-a4a5-4bc7ba3cbbbaa" # ModelScope Token
common_headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
response = requests.post(
f"{base_url}v1/images/generations",
headers={**common_headers, "X-ModelScope-Async-Mode": "true"},
data=json.dumps({
"model": "Qwen/Qwen-Image", # ModelScope Model-Id, required
"prompt": "A golden cat"
}, ensure_ascii=False).encode('utf-8')
)
response.raise_for_status()
task_id = response.json()["task_id"]
while True:
result = requests.get(
f"{base_url}v1/tasks/{task_id}",
headers={**common_headers, "X-ModelScope-Task-Type": "image_generation"},
)
result.raise_for_status()
data = result.json()
if data["task_status"] == "SUCCEED":
image = Image.open(BytesIO(requests.get(data["output_images"][0]).content))
image.save("result_image.jpg")
break
elif data["task_status"] == "FAILED":
print("Image Generation Failed.")
break
time.sleep(5)
- 如果报401错误的话
- 需要确认是否阿里云已经授权
- 为什么会是一只猫呢?
- 修改第20行代码
- 把 金猫 修改为 金猫吃鱼
- 这下吃上鱼啦
- 终端里面没有任何提示啊
- 干脆就输出这个任务id
print("task_id-------", task_id)
- 输出任务id
- 但是图片每次生成都会自我覆盖
- 输出文件名取决于任务id了
- 但是命名无规律
- 首先定义 提示词(prompt)
- 然后 在后台输出 时间 和 提示词
- 将 时间和提示词 输出到 文件名中
- 这次使用 魔搭社区的api
- 构建了 文生图的应用
- 文生图 还能怎么玩呢?🤔
- 下次再说👋
- 本文来自 oeasy Python 系统教程。
- 想完整、扎实学 Python,
- 搜索 oeasy 即可。














