staraaa commited on
Commit
14ccb66
·
verified ·
1 Parent(s): 28bc530

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -151
app.py CHANGED
@@ -3,200 +3,111 @@ import requests
3
  from PIL import Image
4
  import io
5
  import os
6
- import time
7
 
8
- # 使用环境变量获取 Token,确保安全
9
  HF_TOKEN = os.environ.get('HF_TOKEN')
10
  API_URL = "https://api-inference.huggingface.co/models/rupeshs/LCM-runwayml-stable-diffusion-v1-5"
11
  headers = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
12
 
13
- def query_huggingface(payload):
14
- """调用Hugging Face API生成图像"""
15
- if not HF_TOKEN:
16
- return None
17
 
18
- try:
19
- response = requests.post(API_URL, headers=headers, json=payload)
20
- response.raise_for_status()
21
- return response.content
22
- except Exception as e:
23
- print(f"API调用失败: {e}")
24
- return None
25
-
26
- def analyze_copyright_risk(prompt, style_option):
27
- """分析版权风险"""
28
- risky_artists = ["梵高", "毕加索", "莫奈", "达利", "达芬奇", "当代艺术家", "现代艺术家"]
29
- high_risk_indicators = []
30
- medium_risk_indicators = []
31
-
32
- # 检测高风险词汇
33
- for artist in risky_artists:
34
- if artist in prompt:
35
- high_risk_indicators.append(f"涉及特定艺术家: {artist}")
36
-
37
- # 检测风格模仿
38
- if "风格" in prompt and style_option != "原创风格":
39
- medium_risk_indicators.append("风格模仿可能涉及版权问题")
40
-
41
- # 生成风险报告
42
- if high_risk_indicators:
43
- risk_level = "🔴 高风险"
44
- suggestions = [
45
- "建议使用更通用的风格描述",
46
- "避免直接提及在世艺术家",
47
- "考虑使用已进入公共领域的古典大师风格"
48
- ]
49
- elif medium_risk_indicators:
50
- risk_level = "🟡 中风险"
51
- suggestions = [
52
- "建议注明'风格参考'",
53
- "避免商业用途",
54
- "考虑原创风格创作"
55
- ]
56
- else:
57
- risk_level = "🟢 低风险"
58
- suggestions = [
59
- "原创性较高,适合个人使用",
60
- "可考虑添加创作说明"
61
- ]
62
-
63
- return risk_level, high_risk_indicators + medium_risk_indicators, suggestions
64
-
65
- def generate_art_with_analysis(prompt, style_option):
66
- """生成艺术作品并分析伦理风险"""
67
 
68
- # 构建完整的提示词
69
- if style_option == "梵高风格":
70
- full_prompt = f"{prompt}, 梵高风格, 油画笔触, 星空效果"
71
- elif style_option == "水墨风格":
72
- full_prompt = f"{prompt}, 中国传统水墨风格, 黑白灰调, 留白"
73
- elif style_option == "数字艺术":
74
- full_prompt = f"{prompt}, 数字艺术, 未来感, 科技感"
75
- else: # 原创风格
76
- full_prompt = f"{prompt}, 原创数字艺术"
77
 
78
- # 分析版权风险
79
- risk_level, risk_indicators, suggestions = analyze_copyright_risk(prompt, style_option)
80
-
81
- # 尝试生成图像(仅在配置了Token时)
82
  image = None
83
- generation_status = "演示模式"
84
 
85
- # 如果有Token,尝试真实生成
86
  if HF_TOKEN:
87
- image_bytes = query_huggingface({"inputs": full_prompt})
88
- if image_bytes:
89
- image = Image.open(io.BytesIO(image_bytes))
90
- generation_status = "🟢 使用AI生成"
91
- else:
92
- generation_status = "⚠️ AI生成失败 - 使用演示模式"
93
-
94
- # 构建详细报告
95
- analysis_report = f"""
96
- ## 📊 伦理分析报告
97
-
98
- **风险等级**: {risk_level}
99
-
100
- ### 🔍 检测到的风险因素:
101
- {chr(10).join(['• ' + item for item in risk_indicators]) if risk_indicators else '• 未检测到明显风险因素'}
102
-
103
- ### 💡 建议措施:
104
- {chr(10).join(['• ' + item for item in suggestions])}
105
-
106
- ### 🎨 生成信息:
107
- - 提示词: {full_prompt}
108
- - 生成状态: {generation_status}
109
- - 风格选项: {style_option}
110
- - API状态: {'已配置' if HF_TOKEN else '未配置 - 使用演示模式'}
111
-
112
- > 💡 提示: {'已配置Hugging Face Token,可真实生成图像' if HF_TOKEN else '如需真实生成图像,请在Space设置中添加HF_TOKEN环境变量'}
113
- """
114
 
115
- return image, analysis_report
116
 
117
- # 创建Gradio界面
118
- with gr.Blocks(theme=gr.themes.Soft(), title="AI艺术生成与版权伦理探索") as demo:
119
  gr.Markdown("""
120
- # 🎨 AI艺术生成与版权伦理探索
121
-
122
  ## 技术之善 - AI项目制作与伦理探索
123
 
124
- 本演示展示AI艺术生成能力,同时深入分析相关的版权和伦理问题。
125
  """)
126
 
127
  with gr.Row():
128
- with gr.Column(scale=1):
129
- gr.Markdown("### 🎯 创作设置")
130
-
131
  prompt_input = gr.Textbox(
132
  label="创作描述",
133
- placeholder="例如:星空下城市、山水风景、未来科技...",
134
- lines=3,
135
- value="星空下的奇幻城市"
136
  )
137
 
138
- style_dropdown = gr.Dropdown(
139
- choices=["原创风格", "梵高风格", "水墨风格", "数字艺术"],
140
  label="艺术风格",
141
- value="原创风格",
142
- info="选择风格可能影响版权风险评估"
143
- )
144
-
145
- generate_btn = gr.Button(
146
- "🚀 生成并分析",
147
- variant="primary",
148
- size="lg"
149
  )
150
 
151
- gr.Markdown("""
152
- ### 💡 使用提示
153
- - 尽量使用原创描述而非特定艺术家名称
154
- - 高风险内容会触发详细伦理分析
155
- - 所有生成内容仅供教学演示使用
156
- """)
157
 
158
- with gr.Column(scale=1):
159
- gr.Markdown("### 🖼️ 生成结果")
160
  image_output = gr.Image(
161
- label="AI生成的艺术作品",
162
  height=400,
163
- format="png"
164
  )
165
 
166
- gr.Markdown("### 📋 伦理分析")
167
- analysis_output = gr.Markdown(
168
- label="版权风险评估",
169
- value="请先生成艺术作品以查看分析报告..."
 
 
 
 
170
  )
171
 
172
- # 示例
173
- gr.Markdown("## 🎪 快速示例")
174
  examples = gr.Examples(
175
  examples=[
176
  ["星空下的城市夜景", "梵高风格"],
177
- ["山水间的亭台楼阁", "水墨风格"],
178
  ["未来科技的都市景观", "数字艺术"],
179
- ["花朵盛开春日花园", "原创风格"]
180
  ],
181
- inputs=[prompt_input, style_dropdown],
182
- label="点击示例快速填充"
183
  )
184
 
185
- # 页脚状态显示
186
- status_text = "🔴 未配置API Token - 演示模式" if not HF_TOKEN else "🟢 API Token已配置 - 可真实生成图像"
187
- gr.Markdown(f"""
188
- ---
189
- **系统状态**: {status_text}
190
-
191
- *本项目为工程伦理课程演示,重点探讨AI艺术生成的版权伦理问题*
192
- *演示系统基于 Gradio + Hugging Face Spaces 构建*
193
- """)
194
 
195
  # 事件处理
196
  generate_btn.click(
197
- fn=generate_art_with_analysis,
198
- inputs=[prompt_input, style_dropdown],
199
- outputs=[image_output, analysis_output]
200
  )
201
 
202
  if __name__ == "__main__":
 
3
  from PIL import Image
4
  import io
5
  import os
6
+ import random
7
 
8
+ # 使用环境变量获取 Token
9
  HF_TOKEN = os.environ.get('HF_TOKEN')
10
  API_URL = "https://api-inference.huggingface.co/models/rupeshs/LCM-runwayml-stable-diffusion-v1-5"
11
  headers = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
12
 
13
+ def generate_image(prompt, style):
14
+ """专注于图像生成,简化界面"""
 
 
15
 
16
+ # 构建风格化提示词
17
+ style_prompts = {
18
+ "梵高风格": f"{prompt}, 梵高风格, 油画笔触, 浓烈色彩",
19
+ "水墨风格": f"{prompt}, 中国传统水墨风格, 黑白灰调, 留白意境",
20
+ "数字艺术": f"{prompt}, 数字艺术, 未来科技感, 赛博朋克",
21
+ "写实风格": f"{prompt}, 摄影风格, 真实感, 高细节"
22
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
+ full_prompt = style_prompts.get(style, prompt)
 
 
 
 
 
 
 
 
25
 
26
+ # 生成图像
 
 
 
27
  image = None
28
+ status = "等待生成..."
29
 
 
30
  if HF_TOKEN:
31
+ try:
32
+ response = requests.post(API_URL, headers=headers, json={"inputs": full_prompt})
33
+ if response.status_code == 200:
34
+ image = Image.open(io.BytesIO(response.content))
35
+ status = "✅ 生成成功!"
36
+ else:
37
+ status = f"❌ 生成失败: {response.status_code}"
38
+ except Exception as e:
39
+ status = f"❌ 错误: {str(e)}"
40
+ else:
41
+ status = "❌ 未配置API Token"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ return image, status, full_prompt
44
 
45
+ # 创建简洁的Gradio界面
46
+ with gr.Blocks(theme=gr.themes.Soft(), title="AI艺术生成演示") as demo:
47
  gr.Markdown("""
48
+ # 🎨 AI艺术生成演示
 
49
  ## 技术之善 - AI项目制作与伦理探索
50
 
51
+ **重点展示**: Stable Diffusion 图像生成能力
52
  """)
53
 
54
  with gr.Row():
55
+ with gr.Column():
 
 
56
  prompt_input = gr.Textbox(
57
  label="创作描述",
58
+ placeholder="描述你想要生成画面...",
59
+ value="星空下的城市夜景",
60
+ lines=2
61
  )
62
 
63
+ style_radio = gr.Radio(
64
+ choices=["梵高风格", "水墨风格", "数字艺术", "写实风格"],
65
  label="艺术风格",
66
+ value="梵高风格"
 
 
 
 
 
 
 
67
  )
68
 
69
+ generate_btn = gr.Button("生成图像", variant="primary", size="lg")
 
 
 
 
 
70
 
71
+ with gr.Column():
 
72
  image_output = gr.Image(
73
+ label="生成的艺术作品",
74
  height=400,
75
+ show_download_button=True
76
  )
77
 
78
+ status_output = gr.Textbox(
79
+ label="生成状态",
80
+ interactive=False
81
+ )
82
+
83
+ prompt_used = gr.Textbox(
84
+ label="实际使用的提示词",
85
+ interactive=False
86
  )
87
 
88
+ # 示例
89
+ gr.Markdown("### 💡 示例提示词")
90
  examples = gr.Examples(
91
  examples=[
92
  ["星空下的城市夜景", "梵高风格"],
93
+ ["山水间的古代亭台", "水墨风格"],
94
  ["未来科技的都市景观", "数字艺术"],
95
+ ["森林中小鹿", "写实风格"]
96
  ],
97
+ inputs=[prompt_input, style_radio]
 
98
  )
99
 
100
+ # 页脚
101
+ if HF_TOKEN:
102
+ gr.Markdown("---\n**系统状态**: 🟢 已配置API - 可真实生成图像")
103
+ else:
104
+ gr.Markdown("---\n**系统状态**: 🔴 演示模式 - 请在设置中配置HF_TOKEN环境变量")
 
 
 
 
105
 
106
  # 事件处理
107
  generate_btn.click(
108
+ fn=generate_image,
109
+ inputs=[prompt_input, style_radio],
110
+ outputs=[image_output, status_output, prompt_used]
111
  )
112
 
113
  if __name__ == "__main__":