2026秋软件工程个人作业(第一次)
| 这个作业属于哪个课程 | H202601软件工程与软件工程实践 |
|---|---|
| 这个作业要求在哪里 | 2026秋软件工程个人作业(第一次) |
| 这个作业的目标 | 调用hugging face api并生成图像,搭建个人GitHub主页,梳理个人能力,明确自身发展方向,提出对学习课程所希望的收获 |
| 学号 | 102401425 |
2026秋软件工程个人作业(第一次)
1. hugging face API的调用
1.1 API 调用流程
-
从hugging face Access Token界面获取token
![image]()
注意这里需要勾选Make calls to Inference Providers权限
-
本地新建.env文件用于存放该token,通过环境变量的方式在代码中调用该token
-
从界面中查询到api的调用方式,参照该代码写本地调用代码
import os from huggingface_hub import InferenceClient client = InferenceClient( provider="fal-ai", api_key=os.environ["HF_TOKEN"], ) # output is a PIL.Image object image = client.text_to_image( "Astronaut riding a horse", model="XLabs-AI/flux-RealismLora", ) -
这里我用gradio搭建一个简单的网页前端,还加入了一些其他功能:利用大模型辅助生成提示词
1.2 相关代码
image_generate.py
import os
import time
from pathlib import Path
from dotenv import load_dotenv
from huggingface_hub import InferenceClient
load_dotenv()
client = InferenceClient(provider="fal-ai", token=os.environ["HF_TOKEN"])
OUTPUT_DIR = Path("output")
def generate_image(prompt: str):
if not (prompt or "").strip():
raise ValueError("提示词为空:请先输入描述并点击「生成提示词」")
t0 = time.time()
image = client.text_to_image(prompt, model="XLabs-AI/flux-RealismLora")
OUTPUT_DIR.mkdir(exist_ok=True)
save_path = OUTPUT_DIR / (time.strftime("%Y%m%d-%H%M%S") + ".png")
image.save(save_path)
print(f"图像生成成功 | 耗时 {time.time() - t0:.1f}s | 已保存 {save_path}")
return image
prompt_generate.py
from openai import OpenAI
import uuid
import os
from dotenv import load_dotenv
load_dotenv()
client = OpenAI(
api_key=os.environ["OPENCODE_API_KEY"],
base_url="https://opencode.ai/zen/go/v1",
default_headers={
"User-Agent": "fzu-image-generator/0.1.0 (student-project; gradio)",
"x-opencode-session": str(uuid.uuid4()),
},
)
def prompt_generate(prompt: str, style: str) -> str:
if not prompt.strip():
raise ValueError("请输入文本")
resp = client.chat.completions.create(
model="mimo-v2.5",
messages=[
{
"role": "system",
"content": "把用户的中文描述扩写成适合文生图模型的英文提示词,200字左右,不需要标题",
},
{"role": "user", "content": str(prompt) + "风格: " + str(style)},
],
)
print(resp)
return resp.choices[0].message.content
style.py
STYLE_CHOICES = [
(
"写实摄影",
"超写实摄影风格,自然柔和的光影,浅景深虚化背景,85mm 定焦镜头质感,皮肤纹理与材质细节清晰,画面如单反直出",
),
(
"漫画风格",
"日式漫画插画风格,清晰流畅的线稿,赛璐璐平涂上色,色块明快干净,大眼睛动漫人物,阴影用高对比度色块表现",
),
(
"油画风格",
"古典油画风格,厚涂笔触明显,明暗过渡柔和细腻,暖金色调为主,带有画布肌理,整体庄重且有年代感",
),
(
"水彩风格",
"清新水彩画风格,透明感叠色,颜色轻盈明亮,边缘自然晕染,保留纸张纹理,画面通透有呼吸感",
),
(
"赛博朋克",
"赛博朋克风格,霓虹灯光反射在湿润地面,蓝紫与品红色调,雨夜未来都市,金属质感强烈,明暗反差极高",
),
(
"中国水墨",
"中国水墨画风格,大面积留白构图,墨色浓淡干湿层次丰富,线条写意流畅,宣纸质感,意境空灵悠远",
),
]
main.py
import gradio as gr
from prompt_generate import prompt_generate
from image_generate import generate_image
from style import STYLE_CHOICES
custom_css = """
#prompt-input textarea { height: 50vh !important; }
"""
def create_prompt(prompt, style):
try:
return prompt_generate(prompt=prompt, style=style)
except ValueError as e:
raise gr.Error(str(e))
def create_image(prompt_text):
try:
return generate_image(prompt_text)
except ValueError as e:
raise gr.Error(str(e))
except Exception as e:
raise gr.Error(f"图像生成失败:{e}")
with gr.Blocks(fill_width=True, fill_height=True) as demo:
with gr.Row(scale=1, equal_height=True):
with gr.Column():
prompt = gr.Text(label="描述你想生成的内容")
style_select = gr.Dropdown(
choices=STYLE_CHOICES,
value=STYLE_CHOICES[0][1],
label="风格选择",
interactive=True,
)
button1 = gr.Button(value="生成提示词", variant="primary")
detailed_prompt = gr.Text(
container=False, lines=22, show_label=False, elem_id="prompt-input"
)
run = gr.Button(value="生成图片", variant="primary")
with gr.Column(scale=3):
display = gr.Image(interactive=False, show_label=False, elem_id="image")
button1.click(
fn=create_prompt, inputs=[prompt, style_select], outputs=detailed_prompt
)
run.click(fn=create_image, inputs=detailed_prompt, outputs=display)
demo.launch(
footer_links=[],
css=custom_css,
theme=gr.Theme.from_hub("netomo/Acheulit-Theme1"),
)
1.3 API调用成功
第一次调用
这里我用大模型生成中文提示词: 输入一只橘猫坐在窗台上,让大模型给出中文提示词
一只毛色温暖的橘色猫咪慵懒地端坐在木质窗台上,身体微微侧转,一双圆润明亮的琥珀色眼睛望向窗外柔和的午后光线。橘白相间的毛发蓬松而富有层次感,每一根毛丝都清晰可辨,在自然光的照射下泛着细腻的金色光泽。耳朵微微竖起,胡须根根分明地向两侧舒展,鼻尖呈现微微的粉嫩色泽。窗台上散落着几片细碎的阳光光斑,窗帘轻轻随微风飘动,背景中窗外的绿植与街景化为柔美的圆形散景光斑,奶油般柔滑虚化。整体画面采用超写实摄影风格,自然柔和的漫射光线从侧面洒入,浅景深营造出梦幻的虚实对比,85mm定焦镜头特有的压缩感与空间透视使主体猫咪立体突出,皮肤与毛发纹理细节纤毫毕现,画质纯净通透,如同高端全画幅单反相机直出的原始影像,色调温暖舒适,氛围宁静治愈。一只毛色温暖的橘色猫咪慵懒地端坐在木质窗台上,身体微微侧转,一双圆润明亮的琥珀色眼睛望向窗外柔和的午后光线。橘白相间的毛发蓬松而富有层次感,每一根毛丝都清晰可辨,在自然光的照射下泛着细腻的金色光泽。耳朵微微竖起,胡须根根分明地向两侧舒展,鼻尖呈现微微的粉嫩色泽。窗台上散落着几片细碎的阳光光斑,窗帘轻轻随微风飘动,背景中窗外的绿植与街景化为柔美的圆形散景光斑,奶油般柔滑虚化。整体画面采用超写实摄影风格,自然柔和的漫射光线从侧面洒入,浅景深营造出梦幻的虚实对比,85mm定焦镜头特有的压缩感与空间透视使主体猫咪立体突出,皮肤与毛发纹理细节纤毫毕现,画质纯净通透,如同高端全画幅单反相机直出的原始影像,色调温暖舒适,氛围宁静治愈。
给我生成了一个二次元,这有人能绷得住吗
可以看到这个模型对中文的训练样本不足,用中文提示词并不能很好地生成出所描述的东西
第二次调用
还是相同的提示词,这次我让大模型输出英文的提示词
A fluffy orange tabby cat sits elegantly on a sunlit windowsill, its body turned slightly toward the camera with a calm and contemplative gaze. Soft, warm natural light streams through the window, casting gentle golden highlights across its thick, plush fur, revealing intricate details of every individual strand and the subtle tabby stripe patterns in shades of amber, ginger, and cream. The cat's bright green eyes glisten with reflected light, adding a soulful depth to its expression. Its paws are neatly tucked beneath its chest, with delicate whiskers fanning outward catching the ambient glow. The windowsill is made of aged white-painted wood with faint texture and slight wear marks. Behind the cat, the outdoor scene is rendered in a smooth, creamy bokeh blur, with hints of green foliage and soft daylight diffusing into the room. The shallow depth of field isolates the cat as the crisp focal point, with the 85mm f/1.8 lens compression creating a natural and flattering perspective. Skin-like fur texture, fine pore-level detail on the nose leather, and precise material rendering throughout. The overall mood is serene, warm, and intimate, shot in a hyper-realistic photography style reminiscent of a straight-out-of-camera DSLR image with no heavy post-processing.
可以看到效果很不错,英文的具体描述可以让该模型很好地生成想要的图片
额度不足
生成两张图片之后,额度就不够了,本来想手写prompt测试不同精细程度的提示词,但是现在无法继续测试prompt了

1.4 提示词设计思路与修改过程
我使用大模型辅助设计提示词,大模型生成的提示词其实效果非常不错,第一次使用中文作为提示词,模型完全无法理解,所以第二次改用英文,效果不错
可惜的是我的额度不足了,无法继续测试手写提示词的迭代了
1.5 API调用时的体验和心得
- 对于不同的模型,训练样本不同,所需要的输入分布也不同,比如这次调用的模型,只能使用英文作为提示词输入
- 要考虑可能发生的异常并对异常进行处理(如python的
try,except),比如考虑用户的空输入,考虑api抛出的异常 - 在当今ai的时代,api所需的token是必要的,token安全尤其重要,存在本地.env文件而不是直接硬编码在代码中是必要的(不要忘了把.env文件加入.gitignore中)
2. Github个人主页搭建
我这里先采用方案一进行个人主页搭建,方案二在等我用空余时间的时候再慢慢摸索尝试
- 我的个人主页: https://github.com/SuCylinder

3. 博客园随笔
按照要求,发布了一篇博客园随笔

4. 后台使用博客园markdown编辑器的截图








浙公网安备 33010602011771号