File size: 7,213 Bytes
cf9e738
 
 
 
 
 
 
 
 
 
 
 
 
 
d8740b6
cf9e738
 
 
 
 
 
 
 
c908878
 
 
cf9e738
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b63e90
 
cf9e738
22bc19b
 
 
 
 
 
 
 
 
347a429
 
 
 
 
 
 
 
 
 
cf9e738
831acb3
9b63e90
9d6cb2f
 
4af011d
9d6cb2f
cf9e738
 
 
 
 
 
1a74be9
cf9e738
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2170c7e
 
cf9e738
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da4c613
 
cf9e738
 
 
 
da4c613
cf9e738
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22bc19b
cf9e738
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07dd490
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22bc19b
cf9e738
 
07dd490
 
48e0d06
 
347a429
cf9e738
 
 
 
 
48e0d06
 
 
 
 
cf9e738
48e0d06
cf9e738
 
 
028e149
cf9e738
347a429
cf9e738
2170c7e
da4c613
9b63e90
da4c613
b277758
 
da4c613
9b63e90
39e49d8
9b63e90
cf9e738
 
48e0d06
b277758
cf9e738
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import json
import requests
import gradio as gr
import random
import time
import os
import datetime
from datetime import datetime
from PIL import Image
from PIL import ImageOps
from PIL import Image, ImageDraw, ImageFont
from textwrap import wrap
import json
from io import BytesIO
import re

print('for update')

API_TOKEN = os.getenv("API_TOKEN")
HRA_TOKEN=os.getenv("HRA_TOKEN")


from huggingface_hub import InferenceApi
#inference = InferenceApi("bigscience/bloom",token=API_TOKEN)
inference = InferenceApi("bigscience/bloomz",token=API_TOKEN)


headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
url_hraprompts='https://us-central1-createinsightsproject.cloudfunctions.net/gethrahfprompts'

data={"prompt_type":'stable_diffusion_tee_shirt_text',"hra_token":HRA_TOKEN}
try:
    r = requests.post(url_hraprompts, data=json.dumps(data), headers=headers)
except requests.exceptions.ReadTimeout as e:
    print(e)
#print(r.content)


prompt_text=str(r.content, 'UTF-8')
print(prompt_text)
data={"prompt_type":'stable_diffusion_tee_shirt_image',"hra_token":HRA_TOKEN}
try:
    r = requests.post(url_hraprompts, data=json.dumps(data), headers=headers)
except requests.exceptions.ReadTimeout as e:
    print(e)
#print(r.content)

prompt_image=str(r.content, 'UTF-8')
print(prompt_image)

ENDPOINT_URL="https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-2-1" # url of your endpoint

HF_TOKEN=API_TOKEN

response_nsfw = requests.get('https://github.com/coffee-and-fun/google-profanity-words/raw/main/data/list.txt')
data_nsfw = response_nsfw.text
nsfwlist=data_nsfw.split('\n')
nsfwlowerlist=[]
for each in nsfwlist:
  if each!='':
    nsfwlowerlist.append(each.lower())
nsfwlowerlist.extend(['bra','gay','lesbian',])

data={"prompt_type":'stable_diffusion_negative_prompt',"hra_token":HRA_TOKEN}
try:
    r = requests.post(url_hraprompts, data=json.dumps(data), headers=headers)
except requests.exceptions.ReadTimeout as e:
    print(e)
#print(r.content)

neg_prompt=str(r.content, 'UTF-8')
print(neg_prompt)

def generate_image(prompt_SD:str):
    print(prompt_SD)
    payload = {"inputs": prompt_SD,"seed":random.randint(0,1000),"negative_prompt":neg_prompt,"parameters": {
    "width": 768,
    "height": 768,
    
  }}
    headers = {
        "Authorization": f"Bearer {HF_TOKEN}",
        "Content-Type": "application/json",
        "Accept": "image/png" # important to get an image back
    }
    response = requests.post(ENDPOINT_URL, headers=headers, json=payload)
    #print(response.content)
    img = Image.open(BytesIO(response.content))

    return img
    
def infer(prompt,
          max_length = 250,
          top_k = 0,
          num_beams = 0,
          no_repeat_ngram_size = 2,
          top_p = 0.9,
          seed=42,
          temperature=0.7,
          greedy_decoding = False,
          return_full_text = False):
    
    print('Empty input')
    print(prompt)
    top_k = None if top_k == 0 else top_k
    do_sample = False if num_beams > 0 else not greedy_decoding
    num_beams = None if (greedy_decoding or num_beams == 0) else num_beams
    no_repeat_ngram_size = None if num_beams is None else no_repeat_ngram_size
    top_p = None if num_beams else top_p
    early_stopping = None if num_beams is None else num_beams > 0

    params = {
        "max_new_tokens": max_length,
        "top_k": top_k,
        "top_p": top_p,
        "temperature": temperature,
        "do_sample": do_sample,
        "seed": seed,
        "early_stopping":early_stopping,
        "no_repeat_ngram_size":no_repeat_ngram_size,
        "num_beams":num_beams,
        "return_full_text":return_full_text,
        "raw_response":True
    }
    
    s = time.time()
    response = inference(prompt, params=params)
    print(response)
    proc_time = time.time()-s
    #print(f"Processing time was {proc_time} seconds")
    return response

def getadline(text_inp):
    print(text_inp)
    print(datetime.today().strftime("%d-%m-%Y"))
  
    text = prompt_text+"\nInput:"+text_inp + "\nOutput:"
    resp = infer(text,seed=random.randint(0,100))
    
    generated_text=resp[0]['generated_text']
    result = generated_text.replace(text,'').strip()
    result = result.replace("Output:","")
    parts = result.split("###")
    topic = parts[0].strip()
    topic="\n".join(topic.split('\n'))
    
    
    print(topic)
    mainstring=text_inp
    foundnsfw=0
    for each_word in nsfwlowerlist:
        raw_search_string = r"\b" + each_word + r"\b"
        match_output = re.search(raw_search_string, mainstring)
        no_match_was_found = ( match_output is None )
        if no_match_was_found:
          foundnsfw=0
        else:
          foundnsfw=1
          print(each_word)
          break
    if foundnsfw==1:
        topic="Unsafe content found. Please try again with different prompts."
        print(topic)
    return(topic)

def getadvertisement(topic):
    if topic!='':
        mainstring=topic
        foundnsfw=0
        for each_word in nsfwlowerlist:
            raw_search_string = r"\b" + each_word + r"\b"
            match_output = re.search(raw_search_string, mainstring)
            no_match_was_found = ( match_output is None )
            if no_match_was_found:
              foundnsfw=0
            else:
              foundnsfw=1
              print(each_word)
              break
        if foundnsfw==1:
            topic="Unsafe content found. Please try again with different prompts."
            print(topic)
        input_keyword=topic
    else:
        input_keyword=getadline(random.choice('abcdefghijklmnopqrstuvwxyz'))
    if 'Unsafe content found' in input_keyword:
        input_keyword='Abstract art with a splash of colors'
    print(input_keyword)
    print(datetime.today().strftime("%d-%m-%Y"))
    prompt_SD=input_keyword+' '+prompt_image
    # generate image
    image = generate_image(prompt_SD)
    
    # save to disk
    image.save("finalimage.png")

    image = generate_image(prompt_SD)
    
    # save to disk
    image.save("finalimage1.png")
    
    return 'finalimage.png',"finalimage1.png"


with gr.Blocks() as demo:
    gr.Markdown("<h1><center>T-Shirt Design Generator</center></h1>")
    gr.Markdown(
        """Enter a prompt  and get the t-shirt design. Use examples as a guide. \nImage generation via Stable Diffusion 2. When a prompt is not provided the powerful AI model bigscience/bloom is used to generate it.\nNote: If there is an error message just try after 30 secs"""
        )
    with gr.Row() as row:
        with gr.Column():
            textbox = gr.Textbox(placeholder="Enter prompt...", lines=1,label='Your prompt (Optional)')
            btn = gr.Button("Generate")    
            examples = gr.Examples(examples=['Batman in John Wick style','intricate skull concept art','heavy metal band album cover','abstract art of plants',],
                           inputs=[textbox])
        with gr.Column():
            output_image1 = gr.components.Image(label="Your t-shirt")
        with gr.Column():
            output_image2 = gr.components.Image(label="Your t-shirt")


    btn.click(getadvertisement,inputs=[textbox], outputs=[output_image1,output_image2])
    
    

demo.launch()