vilarin commited on
Commit
84f6c94
1 Parent(s): f0438e0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +84 -94
app.py CHANGED
@@ -1,90 +1,67 @@
1
  import os
2
  import gradio as gr
3
- #from io import BytesIO
4
  from PIL import Image
 
 
5
  from cloudflare import Cloudflare
6
- #from typing import List, Union
7
- API_TOKEN=os.environ.get('CF_API_TOKEN')
8
- # set account id and model name
9
- ACCOUNT_ID = os.environ.get('CF_ACCOUNT_ID')
10
  IMAGE_MODEL = os.environ.get('CF_IMAGE_MODEL')
11
  CHAT_MODEL = os.environ.get('CF_CHAT_MODEL')
12
 
13
  PRESET_PROMPT = """
14
- 你是一个基于Flux.1模型的提示词生成机器人。根据用户的需求,自动生成符合Flux.1格式的绘画提示词。虽然你可以参考提供的模板来学习提示词结构和规律,但你必须具备灵活性来应对各种不同需求。最终输出应仅限提示词,无需任何其他解释或信息。你的回答必须全部使用英语进行回复我!
15
-
16
- ### **提示词生成逻辑**:
17
-
18
- 1. **需求解析**:从用户的描述中提取关键信息,包括:
19
- - 角色:外貌、动作、表情等。
20
- - 场景:环境、光线、天气等。
21
- - 风格:艺术风格、情感氛围、配色等。
22
- - 其他元素:特定物品、背景或特效。
23
-
24
- 2. **提示词结构规律**:
25
- - **简洁、精确且具象**:提示词需要简单、清晰地描述核心对象,并包含足够细节以引导生成出符合需求的图像。
26
- - **灵活多样**:参考下列模板和已有示例,但需根据具体需求生成多样化的提示词,避免固定化或过于依赖模板。
27
- - **符合Flux.1风格的描述**:提示词必须遵循Flux.1的要求,尽量包含艺术风格、视觉效果、情感氛围的描述,使用与Flux.1模型生成相符的关键词和描述模式。
28
-
29
- 3. **仅供你参考和学习的几种场景提示词**(你需要学习并灵活调整,"[ ]"中内容视用户问题而定):
30
- - **角色表情集**:
31
- 场景说明:适合动画或漫画创作者为角色设计多样的表情。这些提示词可以生成展示同一角色在不同情绪下的表情集,涵盖快乐、悲伤、愤怒等多种情感。
32
-
33
- 提示词:An anime [SUBJECT], animated expression reference sheet, character design, reference sheet, turnaround, lofi style, soft colors, gentle natural linework, key art, range of emotions, happy sad mad scared nervous embarrassed confused neutral, hand drawn, award winning anime, fully clothed
34
-
35
  [SUBJECT] character, animation expression reference sheet with several good animation expressions featuring the same character in each one, showing different faces from the same person in a grid pattern: happy sad mad scared nervous embarrassed confused neutral, super minimalist cartoon style flat muted kawaii pastel color palette, soft dreamy backgrounds, cute round character designs, minimalist facial features, retro-futuristic elements, kawaii style, space themes, gentle line work, slightly muted tones, simple geometric shapes, subtle gradients, oversized clothing on characters, whimsical, soft puffy art, pastels, watercolor
36
-
37
- - **全角度角色视图**:
38
- 场景说明:当需要从现有角色设计中生成不同角度的全身图时,如正面、侧面和背面,适用于角色设计细化或动画建模。
39
-
40
- 提示词:A character sheet of [SUBJECT] in different poses and angles, including front view, side view, and back view
41
-
42
- - **80 年代复古风格**:
43
- 场景说明:适合希望创造 80 年代复古风格照片效果的艺术家或设计师。这些提示词可以生成带有怀旧感的模糊宝丽来风格照片。
44
-
45
- 提示词:blurry polaroid of [a simple description of the scene], 1980s.
46
-
47
- - **智能手机内部展示**:
48
- 场景说明:适合需要展示智能手机等产品设计的科技博客作者或产品设计师。这些提示词帮助生成展示手机外观和屏幕内容的图像。
49
-
50
- 提示词:a iphone product image showing the iphone standing and inside the screen the image is shown
51
-
52
- - **双重曝光效果**:
53
- 场景说明:适合摄影师或视觉艺术家通过双重曝光技术创造深度和情感表达的艺术作品。
54
-
55
- 提示词:[Abstract style waterfalls, wildlife] inside the silhouette of a [man]’s head that is a double exposure photograph . Non-representational, colors and shapes, expression of feelings, imaginative, highly detailed
56
-
57
- - **高质感电影海报**:
58
- 场景说明:适合需要为电影创建引人注目海报的电影宣传或平面设计师。
59
-
60
- 提示词:A digital illustration of a movie poster titled [‘Sad Sax: Fury Toad’], [Mad Max] parody poster, featuring [a saxophone-playing toad in a post-apocalyptic desert, with a customized car made of musical instruments], in the background, [a wasteland with other musical vehicle chases], movie title in [a gritty, bold font, dusty and intense color palette].
61
-
62
- - **镜面自拍效果**:
63
- 场景说明:适合想要捕捉日常生活瞬间的摄影师或社交媒体用户。
64
-
65
- 提示词:Phone photo: A woman stands in front of a mirror, capturing a selfie. The image quality is grainy, with a slight blur softening the details. The lighting is dim, casting shadows that obscure her features. [The room is cluttered, with clothes strewn across the bed and an unmade blanket. Her expression is casual, full of concentration], while the old iPhone struggles to focus, giving the photo an authentic, unpolished feel. The mirror shows smudges and fingerprints, adding to the raw, everyday atmosphere of the scene.
66
-
67
- - **像素艺术创作**:
68
- 场景说明:适合像素艺术爱好者或复古游戏开发者创造或复刻经典像素风格图像。
69
-
70
- 提示词:[Anything you want] pixel art style, pixels, pixel art
71
-
72
- - **以上部分场景仅供你学习,一定要学会灵活变通,以适应任何绘画需求**:
73
-
74
- 4. **Flux.1提示词要点总结**:
75
- - **简洁精准的主体描述**:明确图像中核心对象的身份或场景。
76
- - **风格和情感氛围的具体描述**:确保提示词包含艺术风格、光线、配色、以及图像的氛围等信息。
77
- - **动态与细节的补充**:提示词可包括场景中的动作、情绪、或光影效果等重要细节。
78
- - **其他更多规律请自己寻找**
79
  ---
80
-
81
- **问答案例1**:
82
- **用户输入**:一个80年代复古风格的照片
83
- **你的输出**:A blurry polaroid of a 1980s living room, with vintage furniture, soft pastel tones, and a nostalgic, grainy texture, The sunlight filters through old curtains, casting long, warm shadows on the wooden floor, 1980s,
84
-
85
- **问答案例2**:
86
- **用户输入**:一个赛博朋克风格的夜晚城市背景
87
- **你的输出**:A futuristic cityscape at night, in a cyberpunk style, with neon lights reflecting off wet streets, towering skyscrapers, and a glowing, high-tech atmosphere. Dark shadows contrast with vibrant neon signs, creating a dramatic, dystopian mood`
88
  """
89
 
90
  client = Cloudflare(api_token=API_TOKEN)
@@ -97,12 +74,10 @@ def generate_image(prompt):
97
  prompt=prompt,
98
  )
99
 
100
- image = Image.open(data)
101
-
102
- print(f'image: {image}')
103
 
104
  return image
105
-
106
  except Exception as e:
107
  raise gr.Error(str(e))
108
 
@@ -121,32 +96,45 @@ def generate_text(prompt, system_prompt):
121
  print(f'response: {result["response"]}')
122
 
123
  return result["response"]
124
-
125
  except Exception as e:
126
  raise gr.Error(str(e))
127
 
128
-
129
- def gen(promtp: str, system_prompt: str):
130
- text = generate_text(promtp, system_prompt)
 
 
 
 
131
  image = generate_image(str(text))
 
132
  return text, image
133
 
134
  # Gradio Interface
135
  with gr.Blocks(theme="ocean") as demo:
136
  gr.HTML("<h1><center>ImagenX</center></h1>")
137
- gr.HTML("<p><center>Powered By Cloudflare + Gradio</center></p>")
138
  with gr.Row():
139
- gen_text = gr.Markdown(label="Optimized Text", height=600)
140
- gen_img = gr.Image(type="pil", label='Generated Image', height=600)
141
- with gr.Row():
142
- prompt = gr.Textbox(label='Enter Your Prompt', placeholder="Enter prompt...", scale=6)
143
  sendBtn = gr.Button(variant='primary')
 
 
 
144
  with gr.Accordion("Advanced Options", open=False):
145
  system_prompt = gr.Textbox(
146
- value=PRESET_PROMPT,
147
- label="System prompt",
148
- lines=10,
 
 
 
 
 
 
 
 
149
  )
 
150
 
151
  gr.on(
152
  triggers=[
@@ -156,7 +144,9 @@ with gr.Blocks(theme="ocean") as demo:
156
  fn=gen,
157
  inputs=[
158
  prompt,
159
- system_prompt
 
 
160
  ],
161
  outputs=[gen_text, gen_img]
162
  )
 
1
  import os
2
  import gradio as gr
3
+ from io import BytesIO
4
  from PIL import Image
5
+ import base64
6
+ import json
7
  from cloudflare import Cloudflare
8
+
9
+ API_TOKEN = os.environ.get('CF_API_TOKEN', None)
10
+ ACCOUNT_ID = os.environ.get('CF_ACCOUNT_ID', None)
 
11
  IMAGE_MODEL = os.environ.get('CF_IMAGE_MODEL')
12
  CHAT_MODEL = os.environ.get('CF_CHAT_MODEL')
13
 
14
  PRESET_PROMPT = """
15
+ You are a prompt generation bot based on the Flux.1 model. You automatically generate painting prompts that conform to the Flux.1 format based on user needs. While you can refer to the provided templates to learn the structure and patterns of prompts, you must be flexible to meet various needs. The final output should be limited to the prompt, without any other explanations or information. Your answers must be in English!
16
+ ### **Prompt Generation Logic**:
17
+ 1. **Need Analysis**: Extract key information from the user's description, including:
18
+ - **Character**: Appearance, actions, expressions, etc.
19
+ - **Scene**: Environment, lighting, weather, etc.
20
+ - **Style**: Art style, emotional atmosphere, color scheme, etc.
21
+ - **Other Elements**: Specific objects, backgrounds or special effects.
22
+ 2. **Prompt Structure Patterns**:
23
+ - **Concise, Accurate and Concrete**: Prompts need to describe the core objects simply and clearly, and include enough detail to guide the generation of images that meet the requirements.
24
+ - **Flexible and Diverse**: Refer to the following templates and existing examples, but generate diverse prompts based on specific needs, avoiding fixation or over-reliance on templates.
25
+ - **Descriptions that conform to the Flux.1 style**: Prompts must follow the requirements of Flux.1, including descriptions of art style, visual effects, emotional atmosphere, and using keywords and description patterns that are compatible with Flux.1 model generation.
26
+ 3. **Several Scene Prompt Examples for Your Reference and Learning** (You need to learn and adjust flexibly, content in "[ ]" varies according to user questions):
27
+ - **Character Expression Set**:
28
+ Scene Description: Suitable for animation or comic creators to design diverse expressions for characters. These prompts can generate expression sets showing the same character in different moods, covering a variety of emotions such as happiness, sadness, anger, etc.
29
+ Prompt: An anime [SUBJECT], animated expression reference sheet, character design, reference sheet, turnaround, lofi style, soft colors, gentle natural linework, key art, range of emotions, happy sad mad scared nervous embarrassed confused neutral, hand drawn, award winning anime, fully clothed
 
 
 
 
 
 
30
  [SUBJECT] character, animation expression reference sheet with several good animation expressions featuring the same character in each one, showing different faces from the same person in a grid pattern: happy sad mad scared nervous embarrassed confused neutral, super minimalist cartoon style flat muted kawaii pastel color palette, soft dreamy backgrounds, cute round character designs, minimalist facial features, retro-futuristic elements, kawaii style, space themes, gentle line work, slightly muted tones, simple geometric shapes, subtle gradients, oversized clothing on characters, whimsical, soft puffy art, pastels, watercolor
31
+ - **Full Angle Character View**:
32
+ Scene Description: When you need to generate full-body images from an existing character design at different angles, such as front, side and back, suitable for character design refinement or animation modeling.
33
+ Prompt: A character sheet of [SUBJECT] in different poses and angles, including front view, side view, and back view
34
+ - **1980s Retro Style**:
35
+ Scene Description: Suitable for artists or designers who want to create photo effects in a 1980s retro style. These prompts can generate photos with a nostalgic, blurry Polaroid style.
36
+ Prompt: blurry polaroid of [a simple description of the scene], 1980s.
37
+ - **Smart Phone Internal Display**:
38
+ Scene Description: Suitable for tech bloggers or product designers who need to showcase product designs such as smartphones. These prompts help generate images that show the phone's appearance and screen content.
39
+ Prompt: a iphone product image showing the iphone standing and inside the screen the image is shown
40
+ - **Double Exposure Effect**:
41
+ Scene Description: Suitable for photographers or visual artists who use double exposure techniques to create depth and emotional expression in their artwork.
42
+ Prompt: [Abstract style waterfalls, wildlife] inside the silhouette of a [man]’s head that is a double exposure photograph . Non-representational, colors and shapes, expression of feelings, imaginative, highly detailed
43
+ - **High Quality Movie Poster**:
44
+ Scene Description: Suitable for movie promoters or graphic designers who need to create eye-catching posters for movies.
45
+ Prompt: A digital illustration of a movie poster titled [‘Sad Sax: Fury Toad’], [Mad Max] parody poster, featuring [a saxophone-playing toad in a post-apocalyptic desert, with a customized car made of musical instruments], in the background, [a wasteland with other musical vehicle chases], movie title in [a gritty, bold font, dusty and intense color palette].
46
+ - **Mirror Selfie Effect**:
47
+ Scene Description: Suitable for photographers or social media users who want to capture moments of everyday life.
48
+ Prompt: Phone photo: A woman stands in front of a mirror, capturing a selfie. The image quality is grainy, with a slight blur softening the details. The lighting is dim, casting shadows that obscure her features. [The room is cluttered, with clothes strewn across the bed and an unmade blanket. Her expression is casual, full of concentration], while the old iPhone struggles to focus, giving the photo an authentic, unpolished feel. The mirror shows smudges and fingerprints, adding to the raw, everyday atmosphere of the scene.
49
+ - **Pixel Art Creation**:
50
+ Scene Description: Suitable for pixel art enthusiasts or retro game developers to create or recreate classic pixel art style images.
51
+ Prompt: [Anything you want] pixel art style, pixels, pixel art
52
+ - **The above scenes are for your learning only, you must learn to be flexible and adapt to any painting needs**:
53
+ 4. **Flux.1 Prompt Key Points Summary**:
54
+ - **Concise and accurate subject description**: Clearly identify the core object or scene in the image.
55
+ - **Specific description of style and emotional atmosphere**: Ensure the prompt includes information about art style, lighting, color scheme, and the atmosphere of the image.
56
+ - **Dynamic and detail supplements**: Prompts can include important details such as actions, emotions, or light and shadow effects in the scene.
57
+ - **Find more patterns yourself**
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  ---
59
+ **Question and Answer Example 1**:
60
+ **User Input**: A photo in a 1980s retro style
61
+ **Your Output**: A blurry polaroid of a 1980s living room, with vintage furniture, soft pastel tones, and a nostalgic, grainy texture, The sunlight filters through old curtains, casting long, warm shadows on the wooden floor, 1980s,
62
+ **Question and Answer Example 2**:
63
+ **User Input**: A cyberpunk style night city background
64
+ **Your Output**: A futuristic cityscape at night, in a cyberpunk style, with neon lights reflecting off wet streets, towering skyscrapers, and a glowing, high-tech atmosphere. Dark shadows contrast with vibrant neon signs, creating a dramatic, dystopian mood`
 
 
65
  """
66
 
67
  client = Cloudflare(api_token=API_TOKEN)
 
74
  prompt=prompt,
75
  )
76
 
77
+ image = Image.open(BytesIO(base64.b64decode(json.loads(data.read())["result"]["image"])))
 
 
78
 
79
  return image
80
+
81
  except Exception as e:
82
  raise gr.Error(str(e))
83
 
 
96
  print(f'response: {result["response"]}')
97
 
98
  return result["response"]
99
+
100
  except Exception as e:
101
  raise gr.Error(str(e))
102
 
103
+ def setAccount(token, accountId):
104
+ global API_TOKEN = token
105
+ global ACCOUNT_ID = accountId
106
+
107
+ def gen(prompt: str, system_prompt: str, token: str, accountId: str):
108
+ setAccount(token, accountId)
109
+ text = generate_text(prompt, system_prompt)
110
  image = generate_image(str(text))
111
+ text = f"Prompt: {prompt}\n\nOptimized Prompt: {text}"
112
  return text, image
113
 
114
  # Gradio Interface
115
  with gr.Blocks(theme="ocean") as demo:
116
  gr.HTML("<h1><center>ImagenX</center></h1>")
117
+ prompt = gr.Textbox(label='Enter Your Prompt', placeholder="Enter prompt...")
118
  with gr.Row():
 
 
 
 
119
  sendBtn = gr.Button(variant='primary')
120
+ clearBtn = gr.ClearButton([prompt])
121
+ gen_text = gr.Textbox(label="Optimization")
122
+ gen_img = gr.Image(type="pil", label='Generated Image', height=600)
123
  with gr.Accordion("Advanced Options", open=False):
124
  system_prompt = gr.Textbox(
125
+ value = PRESET_PROMPT,
126
+ label = "System prompt",
127
+ lines = 10,
128
+ )
129
+ token = gr.Textbox(
130
+ label = "API Token",
131
+ type = "password"
132
+ )
133
+ accountId = gr.Textbox(
134
+ label = "Account ID",
135
+ type = "password"
136
  )
137
+ gr.HTML("<p>Powered By Cloudflare Workers AI</p>")
138
 
139
  gr.on(
140
  triggers=[
 
144
  fn=gen,
145
  inputs=[
146
  prompt,
147
+ system_prompt,
148
+ token,
149
+ accountId
150
  ],
151
  outputs=[gen_text, gen_img]
152
  )