软件工程第一次作业
| 这个作业属于哪个课程 | H202601软件工程与软件工程实践 |
|---|---|
| 这个作业要求在哪里 | 2026秋软件工程个人作业(第一次) |
| 这个作业的目标 | 学习使用 Hugging Face API 调用 AI 图像生成模型,并结合前端实现交互式图片生成;掌握 Markdown 编写博客的方法,同时提升 AI 应用开发实践能力 |
| 学号 | 102401205 |
一、Hugging Face API调用 Flux模型生成图像
1.1 实验目的
本次实验通过调用 Hugging Face 平台提供的 API,实现基于 Flux 模型的 AI 图像生成。
实验目标:
- 注册并使用 Hugging Face 平台;
- 获取 API Token;
- 调用 XLabs-AI/flux-RealismLora 模型生成真实感图片;
- 编写后端程序处理 API 请求;
- 结合 HTML 页面实现用户输入提示词并生成图片的交互功能。
1.2 实验环境
开发环境:
- 操作系统:Windows
- 编程语言:Python
- 后端框架:Flask
- 前端技术:
- HTML
- CSS
- JavaScript
使用工具:
- Visual Studio Code
- Hugging Face账号
- Python 3.12
1.3 Hugging Face账号注册及API获取
首先在 Hugging Face 官网注册个人账号。
进入:
Settings → Access Tokens
创建 API Token。
生成 Token 后,将其配置到 Python 程序中,用于身份验证。
二、模型选择
本次实验使用模型:
XLabs-AI/flux-RealismLora
模型地址:
https://huggingface.co/XLabs-AI/flux-RealismLora
该模型主要用于生成具有真实摄影效果的图片。
选择该模型的原因:
- Flux模型具有较强的文本理解能力;
- RealismLora增强了图片真实感;
- 可以生成接近现实照片风格的图像。
三、API调用实现
3.1 后端代码
后端使用 Python 编写,通过 Hugging Face API 接收用户输入的提示词,并返回生成图片。
核心流程:
- 用户在网页输入 Prompt;
- 前端发送请求;
- Flask 接收请求;
- 调用 Hugging Face API;
- 返回生成图片;
- 页面显示结果。
代码:
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from gradio_client import Client
import shutil
import os
import time
app = FastAPI()
HF_SPACE = "DamarJati/FLUX.1-RealismLora"
client = None
def get_client():
global client
if client is None:
print("正在连接 Flux...")
client = Client(
HF_SPACE
)
print(client.view_api())
print("Flux连接成功")
return client
class Prompt(BaseModel):
text:str
@app.post("/generate")
def generate_image(data:Prompt):
prompt = data.text
print("====================")
print("收到提示词:")
print(prompt)
c = get_client()
print("开始生成...")
try:
result = c.predict(
prompt,
3.2,
32,
True,
3981632454,
1152,
896,
0.85,
api_name="/run_lora"
)
except Exception as e:
print("Flux调用失败:")
print(e)
return {
"success":False,
"error":str(e)
}
print("====================")
print("返回类型:")
print(type(result))
print("返回内容:")
print(result)
image_path = None
if isinstance(result, tuple):
image_path = result[0]
elif isinstance(result, list):
image_path = result[0]
elif isinstance(result, str):
image_path = result
elif isinstance(result, dict):
if "image" in result:
image_path = result["image"]
if image_path is None:
return {
"success":False,
"error":
"无法解析Flux返回",
"raw":
str(result)
}
print("图片路径:")
print(image_path)
os.makedirs(
"static",
exist_ok=True
)
save_path = "static/generated.png"
shutil.copy(
image_path,
save_path
)
print("保存成功")
return {
"success":True,
"image":
"/generated.png"
}
app.mount(
"/",
StaticFiles(
directory="static",
html=True
),
name="static"
)
四、前端交互设计
为了实现用户交互,本实验增加了简单网页界面。
页面主要包含:
-
输入框:
用户输入图片描述 -
生成按钮:
点击后发送请求 -
图片显示区域:
展示AI生成结果
页面截图:

五、API调用成功记录
运行 Python 程序:

说明 Flask 服务启动成功。
API调用截图:

六、Prompt设计过程
第一次提示词
A realisetic photo of a mountain lake
生成效果:

问题:
生成图片比较简单,缺少细节。
第二次优化
修改为:
A realistic city street in the evening,
people walking on the road,
cinematic lighting,
high detail,
photography style
优化原因:
增加:
- 时间
- 场景
- 人物
- 光照
- 风格描述
生成效果:

最终Prompt
A realistic photograph of a modern city street,
people walking,
trees and buildings,
natural sunlight,
high resolution,
cinematic photography style,
8k detailed最终效果:

七、生成效果分析
通过多次调整 Prompt 后,生成图片的真实性明显提高。
主要优化方向:
- 增加具体场景描述;
- 添加光照信息;
- 添加摄影风格关键词;
- 使用高清细节描述。
最终生成图片具有:
- 更自然的人物比例;
- 更真实的光影效果;
- 更接近现实照片的视觉效果。
八、实验过程中遇到的问题
1. API调用失败
问题:
Token配置错误导致无法访问模型。
解决方法:
重新检查:
- Token是否正确;
- API请求格式;
- 网络连接情况。
2. 图片生成速度较慢
原因:
AI图像生成需要较大的计算资源。
解决方法:
- 减少请求次数;
- 优化Prompt;
- 使用云端推理服务。
九、实验总结与心得
通过本次实验,我学习了如何使用 Hugging Face 平台提供的 API 调用人工智能模型,并完成了从后端接口开发到前端页面展示的完整流程。
在实验过程中,我认识到 Prompt 的设计会直接影响生成结果。简单描述通常无法获得理想图片,需要不断增加场景、细节、光照以及风格等信息。
同时,通过结合 Flask 和网页前端,实现了用户输入提示词即可生成图片的交互功能,提高了对 AI 应用开发流程的理解。
未来希望继续学习:
- 深度学习基础知识;
- 大语言模型应用开发;
- AI Agent技术;
- 前后端综合开发能力。
十、后台博文编辑页面


浙公网安备 33010602011771号