treadon commited on
Commit
b27b5dc
1 Parent(s): bcb45fb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +132 -121
app.py CHANGED
@@ -1,121 +1,132 @@
1
-
2
- import gradio as gr
3
- #import peft
4
- import transformers
5
- import os
6
- import re
7
- import json
8
-
9
-
10
- device = "cpu"
11
- is_peft = False
12
- model_id = os.environ.get("MODEL_ID") or "treadon/prompt-fungineer-355M"
13
- auth_token = os.environ.get("HUB_TOKEN") or True
14
-
15
- print(f"Using model {model_id}.")
16
-
17
- if auth_token != True:
18
- print("Using auth token.")
19
-
20
- model = transformers.AutoModelForCausalLM.from_pretrained(model_id, low_cpu_mem_usage=True,use_auth_token=auth_token)
21
- tokenizer = transformers.AutoTokenizer.from_pretrained("gpt2")
22
-
23
-
24
- def format_prompt(prompt, enhancers=True, inspiration=False, negative_prompt=False):
25
- try:
26
- pattern = r"(BRF:|POS:|ENH:|INS:|NEG:) (.*?)(?= (BRF:|POS:|ENH:|INS:|NEG:)|$)"
27
- matches = re.findall(pattern, prompt)
28
- vals = {key: value.strip() for key, value,ex in matches}
29
- result = vals["POS:"]
30
- if enhancers:
31
- result += " " + vals["ENH:"]
32
- if inspiration:
33
- result += " " + vals["INS:"]
34
- if negative_prompt:
35
- result += "\n\n--no " + vals["NEG:"]
36
-
37
- return result
38
- except Exception as e:
39
- return "Failed to generate prompt."
40
-
41
-
42
- def generate_text(prompt, extra=False, top_k=100, top_p=0.95, temperature=0.85, enhancers = True, inpspiration = False , negative_prompt = False):
43
-
44
- if not prompt.startswith("BRF:"):
45
- prompt = "BRF: " + prompt
46
-
47
- if not extra:
48
- prompt = prompt + " POS:"
49
-
50
- model.eval()
51
- # SOFT SAMPLE
52
- inputs = tokenizer(prompt, return_tensors="pt").to(device)
53
- samples = []
54
- try:
55
- for i in range(1):
56
- outputs = model.generate(**inputs, max_length=256, do_sample=True, top_k=top_k, top_p=top_p, temperature=temperature, num_return_sequences=4, pad_token_id=tokenizer.eos_token_id)
57
- for output in outputs:
58
- sample = tokenizer.decode(output, skip_special_tokens=True)
59
- sample = format_prompt(sample, enhancers, inpspiration, negative_prompt)
60
- samples.append(sample)
61
- except Exception as e:
62
- print(e)
63
-
64
- return samples
65
-
66
-
67
- with gr.Blocks() as fungineer:
68
- with gr.Row():
69
- gr.Markdown("""# Midjourney / Dalle 2 / Stable Diffusion Prompt Generator
70
- This is the 355M parameter model. There is also a 7B parameter model that is much better but far slower (access coming soon).
71
- Just enter a basic prompt and the fungineering model will use its wildest imagination to expand the prompt in detail. You can then use this prompt to generate images with Midjourney, Dalle 2, Stable Diffusion, Bing Image Creator, or any other image generation model.""")
72
- with gr.Row():
73
- with gr.Column():
74
- base_prompt = gr.Textbox(lines=5, label="Base Prompt", placeholder="An astronaut in space", info="Enter a very simple prompt that will be fungineered into something exciting!")
75
- extra = gr.Checkbox(value=True, label="Extra Fungineer Imagination", info="If checked, the model will be allowed to go wild with its imagination.")
76
- with gr.Accordion("Advanced Generation Settings", open=False):
77
- top_k = gr.Slider( minimum=10, maximum=1000, value=100, label="Top K", info="Top K sampling")
78
- top_p = gr.Slider( minimum=0.1, maximum=1, value=0.95, step=0.01, label="Top P", info="Top P sampling")
79
- temperature = gr.Slider( minimum=0.1, maximum=1.2, value=0.85, step=0.01, label="Temperature", info="Temperature sampling. Higher values will make the model more creative")
80
-
81
- with gr.Accordion("Advanced Output Settings", open=False):
82
- enh = gr.Checkbox(value=True, label="Enhancers", info="Add image meta information such as lens type, shuffter speed, camera model, etc.")
83
- insp = gr.Checkbox(value=False, label="Inpsiration", info="Include inspirational photographers that are known for this type of photography. Sometimes random people will appear here, needs more training.")
84
- neg = gr.Checkbox(value=False, label="Negative Prompt", info="Include a negative prompt, more often used in Stable Diffusion. If you're a Stable Diffusion user, chances are you already have a better negative prompt you like to use.")
85
-
86
- with gr.Column():
87
- outputs = [
88
- gr.Textbox(lines=2, label="Fungineered Text 1"),
89
- gr.Textbox(lines=2, label="Fungineered Text 2"),
90
- gr.Textbox(lines=2, label="Fungineered Text 3"),
91
- gr.Textbox(lines=2, label="Fungineered Text 4"),
92
- ]
93
-
94
- inputs = [base_prompt, extra, top_k, top_p, temperature, enh, insp, neg]
95
-
96
-
97
- submit = gr.Button(label="Fungineer",variant="primary")
98
- submit.click(generate_text, inputs=inputs, outputs=outputs)
99
-
100
- examples = []
101
- with open("examples.json") as f:
102
- examples = json.load(f)
103
-
104
- for i, example in enumerate(examples):
105
- with gr.Tab(f"Example {i+1}"):
106
- with gr.Row():
107
- with gr.Column():
108
- gr.Markdown(f"### Base Prompt")
109
- gr.Image(value=f"{example['base']['src']}")
110
- gr.Markdown(f"{example['base']['prompt']}")
111
- with gr.Column():
112
- gr.Markdown(f"### 355M Prompt Fungineered")
113
- gr.Image(value=f"{example['355M']['src']}")
114
- gr.Markdown(f"{example['355M']['prompt']}")
115
- with gr.Column():
116
- gr.Markdown(f"### 7B Prompt Fungineered")
117
- gr.Markdown(f"Coming Soon!")
118
-
119
-
120
- fungineer.launch(enable_queue=True)
121
-
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ import transformers
4
+ import os
5
+ import re
6
+ import json
7
+
8
+
9
+ device = "cpu"
10
+
11
+ model = None
12
+ tokenizer = None
13
+
14
+ def init_model():
15
+ model_id = os.environ.get("MODEL_ID") or "treadon/prompt-fungineer-355M"
16
+ auth_token = os.environ.get("HUB_TOKEN") or True
17
+
18
+ print(f"Using model {model_id}.")
19
+
20
+ if auth_token != True:
21
+ print("Using auth token.")
22
+
23
+ model = transformers.AutoModelForCausalLM.from_pretrained(model_id, low_cpu_mem_usage=True,use_auth_token=auth_token)
24
+ tokenizer = transformers.AutoTokenizer.from_pretrained("gpt2")
25
+
26
+
27
+ def format_prompt(prompt, enhancers=True, inspiration=False, negative_prompt=False):
28
+ try:
29
+ pattern = r"(BRF:|POS:|ENH:|INS:|NEG:) (.*?)(?= (BRF:|POS:|ENH:|INS:|NEG:)|$)"
30
+ matches = re.findall(pattern, prompt)
31
+ vals = {key: value.strip() for key, value,ex in matches}
32
+ result = vals["POS:"]
33
+ if enhancers:
34
+ result += " " + vals["ENH:"]
35
+ if inspiration:
36
+ result += " " + vals["INS:"]
37
+ if negative_prompt:
38
+ result += "\n\n--no " + vals["NEG:"]
39
+
40
+ return result
41
+ except Exception as e:
42
+ return "Failed to generate prompt."
43
+
44
+
45
+ def generate_text(prompt, extra=False, top_k=100, top_p=0.95, temperature=0.85, enhancers = True, inpspiration = False , negative_prompt = False):
46
+ try:
47
+ if model is None:
48
+ init_model()
49
+ except:
50
+ pass
51
+
52
+ if model is None:
53
+ return ["Try Again"] * 4
54
+
55
+ if not prompt.startswith("BRF:"):
56
+ prompt = "BRF: " + prompt
57
+
58
+ if not extra:
59
+ prompt = prompt + " POS:"
60
+
61
+ model.eval()
62
+ # SOFT SAMPLE
63
+ inputs = tokenizer(prompt, return_tensors="pt").to(device)
64
+ samples = []
65
+ try:
66
+ for i in range(1):
67
+ outputs = model.generate(**inputs, max_length=256, do_sample=True, top_k=top_k, top_p=top_p, temperature=temperature, num_return_sequences=4, pad_token_id=tokenizer.eos_token_id)
68
+ for output in outputs:
69
+ sample = tokenizer.decode(output, skip_special_tokens=True)
70
+ sample = format_prompt(sample, enhancers, inpspiration, negative_prompt)
71
+ samples.append(sample)
72
+ except Exception as e:
73
+ print(e)
74
+
75
+ return samples
76
+
77
+
78
+ with gr.Blocks() as fungineer:
79
+ with gr.Row():
80
+ gr.Markdown("""# Midjourney / Dalle 2 / Stable Diffusion Prompt Generator
81
+ This is the 355M parameter model. There is also a 7B parameter model that is much better but far slower (access coming soon).
82
+ Just enter a basic prompt and the fungineering model will use its wildest imagination to expand the prompt in detail. You can then use this prompt to generate images with Midjourney, Dalle 2, Stable Diffusion, Bing Image Creator, or any other image generation model.""")
83
+ with gr.Row():
84
+ with gr.Column():
85
+ base_prompt = gr.Textbox(lines=5, label="Base Prompt", placeholder="An astronaut in space", info="Enter a very simple prompt that will be fungineered into something exciting!")
86
+ extra = gr.Checkbox(value=True, label="Extra Fungineer Imagination", info="If checked, the model will be allowed to go wild with its imagination.")
87
+ with gr.Accordion("Advanced Generation Settings", open=False):
88
+ top_k = gr.Slider( minimum=10, maximum=1000, value=100, label="Top K", info="Top K sampling")
89
+ top_p = gr.Slider( minimum=0.1, maximum=1, value=0.95, step=0.01, label="Top P", info="Top P sampling")
90
+ temperature = gr.Slider( minimum=0.1, maximum=1.2, value=0.85, step=0.01, label="Temperature", info="Temperature sampling. Higher values will make the model more creative")
91
+
92
+ with gr.Accordion("Advanced Output Settings", open=False):
93
+ enh = gr.Checkbox(value=True, label="Enhancers", info="Add image meta information such as lens type, shuffter speed, camera model, etc.")
94
+ insp = gr.Checkbox(value=False, label="Inpsiration", info="Include inspirational photographers that are known for this type of photography. Sometimes random people will appear here, needs more training.")
95
+ neg = gr.Checkbox(value=False, label="Negative Prompt", info="Include a negative prompt, more often used in Stable Diffusion. If you're a Stable Diffusion user, chances are you already have a better negative prompt you like to use.")
96
+
97
+ with gr.Column():
98
+ outputs = [
99
+ gr.Textbox(lines=2, label="Fungineered Text 1"),
100
+ gr.Textbox(lines=2, label="Fungineered Text 2"),
101
+ gr.Textbox(lines=2, label="Fungineered Text 3"),
102
+ gr.Textbox(lines=2, label="Fungineered Text 4"),
103
+ ]
104
+
105
+ inputs = [base_prompt, extra, top_k, top_p, temperature, enh, insp, neg]
106
+
107
+
108
+ submit = gr.Button(label="Fungineer",variant="primary")
109
+ submit.click(generate_text, inputs=inputs, outputs=outputs)
110
+
111
+ examples = []
112
+ with open("examples.json") as f:
113
+ examples = json.load(f)
114
+
115
+ for i, example in enumerate(examples):
116
+ with gr.Tab(f"Example {i+1}"):
117
+ with gr.Row():
118
+ with gr.Column():
119
+ gr.Markdown(f"### Base Prompt")
120
+ gr.Image(value=f"{example['base']['src']}")
121
+ gr.Markdown(f"{example['base']['prompt']}")
122
+ with gr.Column():
123
+ gr.Markdown(f"### 355M Prompt Fungineered")
124
+ gr.Image(value=f"{example['355M']['src']}")
125
+ gr.Markdown(f"{example['355M']['prompt']}")
126
+ with gr.Column():
127
+ gr.Markdown(f"### 7B Prompt Fungineered")
128
+ gr.Markdown(f"Coming Soon!")
129
+
130
+
131
+ fungineer.launch(enable_queue=True)
132
+