File size: 13,700 Bytes
6634db1
83300eb
42ec9a0
 
bc48fae
42a4c31
315b0c9
6f78e57
cd2eefa
d348f6f
33a83b0
1618e25
8fb0870
33a83b0
d40da37
 
d348f6f
e8d4785
 
1fbcc7d
39b2b54
500a5b0
8f4468f
 
1b8f2ad
8f4468f
a3d7998
d348f6f
 
 
 
 
 
 
 
e1e351c
1bef23c
2b8f5ae
1bef23c
 
914a5bf
1bef23c
 
 
 
 
a398064
6614cbc
182756c
42ec9a0
 
f3ec487
d3eae36
e1e351c
 
 
767bd4c
999e2d8
e1e351c
d40da37
e1e351c
 
 
b8f5b82
e1e351c
b8f5b82
e1e351c
b8f5b82
 
f3ec487
e1e351c
 
5099d1c
e1e351c
f3ec487
d3eae36
42a4c31
ae2da36
42a4c31
767bd4c
d40da37
bef3dd5
b08a5a6
4ff74c1
db79d67
3ccccfd
 
5099d1c
6d47bd1
 
d3eae36
6d47bd1
 
 
767bd4c
6d47bd1
 
 
 
 
 
 
5099d1c
83300eb
d3eae36
 
 
 
 
1fbcc7d
d348f6f
 
 
 
 
 
 
 
 
 
49cbb28
e8d4785
499ce6b
e8d4785
49cbb28
e8d4785
49cbb28
e8d4785
 
 
d3eae36
d348f6f
891fd88
e8d4785
 
 
 
 
8a1ba1b
1618e25
 
d3eae36
d348f6f
1618e25
 
 
 
 
 
8a1ba1b
1618e25
 
d3eae36
d348f6f
1618e25
 
 
 
 
 
68580e7
 
 
1b8f2ad
68580e7
 
 
 
 
 
 
 
 
 
1b8f2ad
cd28cca
68580e7
 
 
 
 
 
 
49cbb28
e8d4785
d348f6f
 
 
 
 
deda5ea
 
e8d4785
 
49cbb28
e8d4785
49cbb28
e8d4785
 
 
 
 
 
 
 
 
 
 
 
 
 
d348f6f
25fe461
 
01cf553
d348f6f
 
 
 
deda5ea
 
d348f6f
 
25fe461
d348f6f
25fe461
d348f6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dad35ac
a3d7998
 
7f21e85
a3d7998
 
 
3f6e10c
060e34b
a3d7998
 
 
 
7f21e85
 
a3d7998
 
 
 
 
a1d3fee
 
 
 
 
cc692b7
 
b320959
a1d3fee
5e830d0
9480c8d
aee6044
cc692b7
 
 
 
 
 
 
aee6044
cc692b7
 
 
 
 
aee6044
cc692b7
 
 
 
 
5e830d0
0a8f1b2
a1d3fee
 
 
 
07b415a
e8d4785
1b6a9cf
a9229d0
1798a3e
65eb0fc
1b6a9cf
07b415a
 
e8d4785
6614cbc
83300eb
 
c53d8dd
 
caa7b09
928004b
c53d8dd
 
 
caa7b09
928004b
6d47bd1
 
 
 
928004b
caa7b09
 
 
c53d8dd
837f49f
00aa878
a1d3fee
 
 
 
 
 
d348f6f
 
 
dad35ac
649dadd
 
d348f6f
a398064
649dadd
5b618f4
25fe461
d348f6f
a1d3fee
01cf553
1b6a9cf
d348f6f
d164092
 
a1d3fee
d348f6f
d3eae36
d164092
5099d1c
 
 
a3d7998
6d47bd1
f63b625
bdb8ded
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import gradio as gr
import diff
import os
from PIL import Image
import uuid
import random
import bg
from rembg import remove as rm
import datetime 
from huggingface_hub import (HfApi,file_exists)
import uuid
import json
import requests
uid=uuid.uuid4()
proc1=diff
proc2=diff 
this_url='https://omnibus-game-test.hf.space/'
save_data='https://huggingface.co/datasets/Omnibus/game-data-1/raw/main/'
token_self = os.environ['HF_TOKEN']
api=HfApi(token=token_self)

sky = "https://huggingface.co/spaces/Omnibus/game-test/resolve/main/assets/sky.png"
star = 'https://huggingface.co/spaces/Omnibus/game-test/resolve/main/assets/star.png'
bomb = 'https://huggingface.co/spaces/Omnibus/game-test/resolve/main/assets/bomb.png'
platform = 'https://huggingface.co/spaces/Omnibus/game-test/resolve/main/assets/platform.png'
dude = 'https://huggingface.co/spaces/Omnibus/game-test/resolve/main/assets/dude.png'

get_window_url_params = """
    function(text_input, url_params) {
        console.log(text_input, url_params);
        const params = new URLSearchParams(window.location.search);
        url_params = Object.fromEntries(params);
        return [text_input, url_params];
        }
    """     
def game_fn(sky=sky,star=star,bomb=bomb,platform=platform,dude=dude):
    html_mod=f"""
        <div id="my_game" style="height:600px;width:100%">
            <iframe
            id="myIframe"
            src="https://omnibus-game-test.hf.space/file=game.html?sky={sky}&platform={platform}&star={star}&bomb={bomb}&dude={dude}"        
        	frameborder="0"
        	width="100%"
            height="100%"
            ></iframe>
        </div>"""
    return gr.HTML.update(f'{html_mod}')

def update_game(inp):
    return game_fn(sky=sky)

def sky_fn(inp):
    uid=uuid.uuid4()
    rand = random.randint(1,200)
    for i in range(rand):
        inp+=" "
    #uid=uuid.uuid4()
    output=proc1.send_it(inp,5,1)
    print(output)
    outp=Image.open(output[0])
    width, height = outp.size
    rat = width/height
    if width > height:
        outrs = outp.resize((600*rat,600))
    elif width < height:
        outrs = outp.resize((800,800*rat))     
    else:
        outrs = outp.resize((800,536))
    outrs.save(f"{uid}_sky.png")
    out = os.path.abspath(f"{uid}_sky.png")
    #out = os.path.abspath(outp)
    out_url = f'https://omnibus-game-test.hf.space/file={out}'    
    return outp,out_url

def star_fn(inp):
    uid=uuid.uuid4()
    rand = random.randint(1,200)
    for i in range(rand):
        inp+=" "
    #uid=uuid.uuid4()
    output=proc2.send_it(inp,5,1)
    outp=Image.open(output[0])
    out=rm(outp)
    outrs = out.resize((36,36))
    outrs.save(f"{uid}_star.png")
    out_file = os.path.abspath(f"{uid}_star.png")
    out_url = f'https://omnibus-game-test.hf.space/file={out_file}'    
    return out,out_url

def enemy_fn(inp):
    uid=uuid.uuid4()
    rand = random.randint(1,200)
    for i in range(rand):
        inp+=" "
    #uid=uuid.uuid4()
    output=proc2.send_it(inp,5,1)
    outp=Image.open(output[0])
    out=rm(outp)
    outrs = out.resize((24,24))
    outrs.save(f"{uid}_enemy.png")
    out_file = os.path.abspath(f"{uid}_enemy.png")
    out_url = f'https://omnibus-game-test.hf.space/file={out_file}'    
    return out,out_url

def save_game(name,score,sky_im,star_im,enemy_im):
    sky_im=sky_im.split("app/",1)[1]
    star_im=star_im.split("app/",1)[1]
    #sky_im=sky_im.split("app/",1)[1]
    print(star_im)
    user_repo=save_data.split('datasets/',1)[1].split('/raw',1)[0]
    timestamp=str(datetime.datetime.now())
    timename=timestamp.replace(" ","--").replace(":","-").replace(".","-")    
    if name != "":
        if file_exists(f"{user_repo}", f"games/{name}.omnigame",repo_type="dataset"):
            return "Game Saved with this Name.  Choose a different Name."
        else:
            game=name
    else:
        game=timename
    
    #out_lod=[]
    try:
        r = requests.get(f'{save_data}game_data.json') 
        lod = json.loads(r.text)
        #out_lod.append(lod)
    except:
        lod=[]
        pass
    try: 
        api.upload_file(
        path_or_fileobj=sky_im,
        path_in_repo=f"{save_data.split('main/',1)[1]}/images/background/{game}-background_img.png",
        repo_id=save_data.split('datasets/',1)[1].split('/raw',1)[0],
        token=token_self,
        repo_type="dataset",
        )
    except Exception as e:
        print (e)
        pass 
    try: 
        api.upload_file(
        path_or_fileobj=star_im,
        path_in_repo=f"{save_data.split('main/',1)[1]}/images/star/{game}-star_img.png",
        repo_id=save_data.split('datasets/',1)[1].split('/raw',1)[0],
        token=token_self,
        repo_type="dataset",
        )
    except Exception as e:
        print (e)
        pass  
    try: 
        api.upload_file(
        path_or_fileobj=enemy_im.split("app/",1)[1],
        path_in_repo=f"{save_data.split('main/',1)[1]}/images/enemy/{game}-enemy_img.png",
        repo_id=save_data.split('datasets/',1)[1].split('/raw',1)[0],
        token=token_self,
        repo_type="dataset",
        )
    except Exception as e:
        print (e)
        pass  
    try: 
        api.upload_file(
        path_or_fileobj="assets/platform.png",
        path_in_repo=f"{save_data.split('main/',1)[1]}/images/platform/{game}-platform_img.png",
        repo_id=save_data.split('datasets/',1)[1].split('/raw',1)[0],
        token=token_self,
        repo_type="dataset",
        )
    except Exception as e:
        print (e)
        pass  
    try: 
        api.upload_file(
        path_or_fileobj="assets/dude.png",
        path_in_repo=f"{save_data.split('main/',1)[1]}/images/dude/{game}-dude_img.png",
        repo_id=save_data.split('datasets/',1)[1].split('/raw',1)[0],
        token=token_self,
        repo_type="dataset",
        )
    except Exception as e:
        print (e)
        pass          
    block = {'index': len(lod) + 1,
            'timestamp': timestamp,
            'game_name': game,
            'score': score, 
            'background_url': f'https://huggingface.co/datasets/{user_repo}/resolve/main/images/background/{game}-background_img.png',
            'star_url': f'https://huggingface.co/datasets/{user_repo}/resolve/main/images/star/{game}-star_img.png',
            'enemy_url': f'https://huggingface.co/datasets/{user_repo}/resolve/main/images/enemy/{game}-enemy_img.png',
            'platform_url': f'https://huggingface.co/datasets/{user_repo}/resolve/main/images/platform/{game}-platform_img.png',
            'dude_url': f'https://huggingface.co/datasets/{user_repo}/resolve/main/images/dude/{game}-dude_img.png',
            }
    print(block)
    lod.append(block)    
    
    json_object = json.dumps(lod, indent=4)
    with open("tmp1.json", "w") as outfile:
        outfile.write(json_object)
    try: 
        api.upload_file(
        path_or_fileobj="tmp1.json",
        path_in_repo=f"{save_data.split('main/',1)[1]}/game_data.json",
        repo_id=save_data.split('datasets/',1)[1].split('/raw',1)[0],
        token=token_self,
        repo_type="dataset",
        )
        os.remove("tmp1.json")
        print("success")
    except Exception as e:
        print (e)
        return f'Error Saving Game: {e}'
    game_box=[]
    block2 = {'game_name': game,
            'score':score,
            'timestamp': timestamp,
            'background_url': f'https://huggingface.co/datasets/{user_repo}/resolve/main/images/background/{game}-background_img.png',
            'star_url': f'https://huggingface.co/datasets/{user_repo}/resolve/main/images/star/{game}-star_img.png',
            'enemy_url': f'https://huggingface.co/datasets/{user_repo}/resolve/main/images/enemy/{game}-enemy_img.png',
            'platform_url': f'https://huggingface.co/datasets/{user_repo}/resolve/main/images/platform/{game}-platform_img.png',
            'dude_url': f'https://huggingface.co/datasets/{user_repo}/resolve/main/images/dude/{game}-dude_img.png',
            }
    print(block)
    game_box.append(block2)    
    
    json_object = json.dumps(game_box, indent=4)
    with open("tmp2.json", "w") as outfile:
        outfile.write(json_object)
    try: 
        api.upload_file(
        path_or_fileobj="tmp2.json",
        path_in_repo=f"{save_data.split('main/',1)[1]}/games/{game}.omnigame",
        repo_id=save_data.split('datasets/',1)[1].split('/raw',1)[0],
        token=token_self,
        repo_type="dataset",
        )
        os.remove("tmp2.json")
        print("success")
        game_url=f'{this_url}?game={game}'
    except Exception as e:
        print (e)
        return f'Error Saving Game: {e}'
    return f"Game Saved<br>URL: <a href={game_url}>{game_url}</a>"
def predict(text, url_params):
    load_game=url_params.get('game')
    print (f'load_game::{load_game}')
    if load_game != None:
        try:
            r = requests.get(f'{save_data}games/{load_game}.omnigame') 
            lod = json.loads(r.text)
            game_html=game_fn(lod[0]['background_url'],lod[0]['star_url'],lod[0]['enemy_url'])
            #out_lod.append(lod)
            print (lod)
            print (game_html)
            return "" + text + "",game_html
        except Exception as e:
            print(f"cannot load game.  Error::{e}")
            pass
        
    else:
       pass
    return ["" + text + "", ""]

def get_high_score():
    try:
        r = requests.get(f'{save_data}game_data.json') 
        lod = json.loads(r.text)
        high_score=[0,0,0]
        sort_score=[0,0,0]
        #print(sort_score)
        for ea in lod:
            try:
                if ea['score'] != "":
                    if int(ea['score']) >= int(sort_score[0]):
                        sort_score[2]=sort_score[1]
                        high_score[2]=high_score[1]
                        sort_score[1]=sort_score[0]
                        high_score[1]=high_score[0]
                        sort_score[0]=ea['score']
                        high_score[0]=(f"{ea['score']}<br>{ea['game_name']}<br><br>")
                        pass
                    elif int(ea['score']) >= int(sort_score[1]):
                        sort_score[2]=sort_score[1]
                        high_score[2]=high_score[1]
                        sort_score[1]=ea['score']
                        high_score[1]=(f"{ea['score']}<br>{ea['game_name']}<br><br>")
                        pass
                    elif int(ea['score']) >= int(sort_score[2]):
                        sort_score[2]=ea['score']
                        high_score[2]=(f"{ea['score']}<br>{ea['game_name']}<br><br>")
                        pass
            except Exception as e:
                print(e)
                pass
        return f"<h3><u>High Score</u></h3><br>{high_score[0]}<br>{high_score[1]}<br>{high_score[2]}<br>"
    except Exception as e:
        return e    


score_js="""

function(text_input) {
    console.log(text_input);
    const iframe = document.getElementById("myIframe").contentWindow.document.getElementById('my_score').innerHTML;
    console.log(iframe);
    return [iframe];
}
"""

with gr.Blocks() as app:
    with gr.Row():
        with gr.Column():
            prompt_sky=gr.Textbox(label="Background",value="beautiful landscape, real, 8k")
            btn_sky=gr.Button("Make")
            out_im_sky=gr.Image(type='filepath')
            out_sky_url=gr.Textbox(visible=True)
        with gr.Column():
            prompt_star=gr.Textbox(label="Star",value="Colorful Star, blank background")
            btn_star=gr.Button("Make")
            out_im_star=gr.Image(type='filepath')
            out_star_url=gr.Textbox(visible=True)
        with gr.Column():
            prompt_enemy=gr.Textbox(label="Enemy",value="Ball on fire, blank background")
            btn_enemy=gr.Button("Make")
            out_im_enemy=gr.Image(type='filepath')
            out_enemy_url=gr.Textbox(visible=True)
        gr.Column()
        gr.Column()
        
    with gr.Row():
        update_game=gr.Button("Load Game")
        #start_prompt=gr.Textbox(value="beautiful landscape, real, 8k",visible=False)
    
    with gr.Row():
        with gr.Column(scale=3):
            html_game = gr.HTML()
        with gr.Column(scale=1):
            score_html =gr.HTML()        
    with gr.Row():
        game_name=gr.Textbox(label="Name for Game (optional)")
        save_btn=gr.Button("Save")
        message=gr.HTML()
    with gr.Row(visible=False):
        get_score=gr.Button("Get Score")
        score=gr.Textbox()
        #url_params=gr.Textbox()
    with gr.Row(visible=False):
        text_input=gr.Textbox()
        url_params = gr.JSON({}, visible=True, label="")
        acc=gr.Textbox()

        get_high_score_btn=gr.Button()
    def return_score(text):
        return text
    def refresh_frame():
        return None
    get_high_score_btn.click(get_high_score,None,score_html)    
    get_score.click(return_score,score,[score],_js=score_js)
    save_btn.click(return_score,score,[score],_js=score_js).then(save_game,[game_name,score,out_sky_url,out_star_url,out_enemy_url],message)
    update_game.click(refresh_frame,None,html_game).then(game_fn,[out_sky_url,out_star_url,out_enemy_url],html_game).then(get_high_score,None,score_html)
    btn_sky.click(sky_fn,prompt_sky,[out_im_sky,out_sky_url])
    btn_star.click(star_fn,prompt_star,[out_im_star,out_star_url])
    btn_enemy.click(enemy_fn,prompt_enemy,[out_im_enemy,out_enemy_url])
    app.load(predict,[text_input,url_params],[text_input,html_game], _js=get_window_url_params) 

    #app.load(sky_fn,prompt_sky,[out_im_sky,out_sky_url]).then(game_fn,[out_sky_url],html_game)
app.queue(concurrency_count=10).launch()