File size: 7,813 Bytes
d3c83b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import sys
import cv2
import uuid
from PIL import Image
import gradio as gr
from pathlib import Path 
from huggingface_hub import (create_repo,get_full_repo_name,upload_file,CommitOperationAdd,HfApi)

token_self = os.environ['HF_TOKEN']

 
def build_space(t_name,t_space,t_title,t_description,t_redirect,t_image=None,t_image_url=None,token=None):
    uid = uuid.uuid4()
    model_id=t_name
    #model_id="omnibus/fff"
    if token==None or token=="":
        token = token_self
    else:
        token = token
        pass
    api = HfApi(token=token)
    repo_name = get_full_repo_name(model_id=model_id, token=token)
    
    if t_redirect==None or t_redirect=="":
        t_redirect=t_space
    else:
        t_redirect=t_redirect
        pass
    
    try:
        print(t_space.rsplit('.hf', 1)[-1])
        if t_space.rsplit('.hf', 1)[-1] == ".space":        
            repo_url = api.create_repo(
                repo_id=model_id,
                repo_type="space",
                space_sdk="static",
                private=False,
            )
            print(f"""Space Built at {repo_name}""")
        else:
            model_id=None
            repo_name=None
            t_space=None
            t_image=None
            t_image_url=None
            api=None
            pass
            return gr.HTML.update(f"""Invalid Direct URL: must be a Huggingface Space<br>Be sure URL is in lowercase""")  
    except Exception as e:
        return gr.HTML.update(f"""{str(e)}""")
    
    if t_image_url != None and t_image_url != "" and t_image==None:
        t_image=t_image_url
        print(f"Using image URL {t_image}")
        pass
    elif t_image != None:
        img1 = Image.open(t_image)
        img1.thumbnail((500,500), Image.Resampling.LANCZOS)
        img1.save(f'tmpim-{uid}.png')
        output_pro=cv2.imread(f'tmpim-{uid}.png')

        cv2.imwrite(f"./img-{uid}.png",output_pro)
        try: 
            api.upload_file(
            path_or_fileobj=f"./img-{uid}.png",
            path_in_repo="card_im.png",
            repo_id=repo_name,
            token=token,
            repo_type="space",
            )
            t_image = f"https://{repo_name.replace('/','-').replace('_','-')}.hf.space/card_im.png"
            os.remove(f"./img-{uid}.png")

            print(f"Image Uploaded to: {t_image}")
        except Exception as e:
            return gr.HTML.update(f"""{str(e)}""")        
        pass 
    else: 
        print("Default Image")
        t_image="https://huggingface.co/spaces/portal/bin/resolve/main/ai_demo_card.png"
        pass
        
    try:
        api_url = f'https://huggingface.co/api/spaces/{model_id}'
        t_iframe = t_space
        t_link =  f"https://{repo_name.replace('/','-').replace('_','-')}.hf.space/ai.html"
        t_space = f"https://{repo_name.replace('/','-').replace('_','-')}.hf.space/back.html"

        with open("template/ai.html", "r") as f:
            app = f.read()
        app = app.replace("$space", t_space)
        app = app.replace("$title", t_title)
        app = app.replace("$description", t_description)
        app = app.replace("$image", t_image)
        app = app.replace("$redirect", t_redirect)

        with open("ai.html", "w") as f:
            f.write(app)

        api.upload_file(
            path_or_fileobj="ai.html",
            path_in_repo="ai.html",
            repo_id=repo_name,
            token=token,
            repo_type="space",
        )
        os.remove("ai.html")

        with open("template/front.html", "r") as f:
            app = f.read()
        app = app.replace("$iframe", t_iframe)

        with open("front.html", "w") as f:
            f.write(app)

        api.upload_file(
            path_or_fileobj="front.html",
            path_in_repo="index.html",
            repo_id=repo_name,
            token=token,
            repo_type="space",
        )
        os.remove("front.html")

        
        with open("template/back.html", "r") as f:
            app = f.read()
        app = app.replace("$iframe", t_iframe)
        # 3. save the new app.py file
        with open("back.html", "w") as f:
            f.write(app)

        api.upload_file(
            path_or_fileobj="back.html",
            path_in_repo="back.html",
            repo_id=repo_name,
            token=token,
            repo_type="space",
        )
        os.remove("back.html")
        return gr.HTML.update(f'''<center>Your Interactive Twitter Card Embed Link is:<br><a href="{t_link}" target="_blank">{t_link}</a><center><br>''')
    except Exception as e:
        return gr.HTML.update(f"""{str(e)}""")
def d_im():
    output="https://huggingface.co/spaces/portal/bin/resolve/main/ai_demo_card.png"
    return output

with gr.Blocks() as build_app:
    gr.Markdown("""<center><h1>Interactive Twitter Card Builder</h1></center>""")

    with gr.Row():
        gr.Column(scale=1)
        with gr.Column(scale=3):
            with gr.Accordion("Details",open=False):
                with gr.Tab("Description"):
                        gr.Markdown("""<h7>This space will build an Interactive Twitter Card<br>
                        where Twitter (and other) users can run your Gradio demo<br>
                        right on their Social Media feed.<br><br>
                        *Only works through browser, not Twitter App<br><br>
                        Enter the required information and paste the link that is returned<br>
                        as the only link, along with your message and tags, in your Tweet.<br>
                        When posted, the Interactive Twitter Card should have a Play button<br>
                        which will display the Space you provided.<br><br>
                        Twitter will remember this card associated with the link you post,<br>
                        so any changes will often require a differently named link.<br><br>
                        You can test your link first by omitting your Write token<br>
                        which will assign the default REPO: "portal"<br>(Link: portal-NAME.hf.space)<br><br>
                        This Space is a Demo, and is a Work in Progress<br>
                        No Warranties, Guarantees, or Permissions implied
                        """)
                with gr.Tab("Credits"):
                        gr.Markdown("""<h7><a href='https://huggingface.co/spaces/anzorq/sd-space-creator'>anzorq/sd-space-creator</a><br>""")
                

            with gr.Box():
                option_token = gr.Textbox(label="HF Write Token to write to your REPO", placeholder="Optional")
                t_name = gr.Textbox(label="NAME (Link will be: repo-NAME.hf.space)")                
                t_space = gr.Textbox(label="Direct URL to your Space (https://you-repo-you-space.hf.space)")
                t_title = gr.Textbox(label="Title for Twitter Card")
                t_description = gr.Textbox(label="Short Description for Twitter Card")
                t_redirect = gr.Textbox(label="Redirect URL for Twitter Card Click", placeholder="Optional Redirect URL")
                gr.Markdown("""Image for your Card (min: 300x300 [Square]""")
                t_image_url = gr.Textbox(label="Image URL", placeholder="Optional URL of Image")
                t_image = gr.Image(label="Twitter Card Image", type="filepath",interactive=True)
                with gr.Row():
                    input_button = gr.Button()
                    def_im = gr.Button("Load Default Image")
                output_html = gr.HTML("""""")
        gr.Column(scale=1)
    input_button.click(build_space,[t_name,t_space,t_title,t_description,t_redirect,t_image,t_image_url,option_token],output_html)
    def_im.click(d_im,None,t_image)
build_app.queue(concurrency_count=10).launch()