File size: 11,760 Bytes
aa64e27
 
 
da5ac36
aa64e27
be37766
 
 
d50f546
 
 
 
 
 
 
 
 
 
 
 
 
aa64e27
d50f546
aa64e27
31e2d7f
 
aa64e27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97c8695
0f54052
97c8695
 
19fd718
b6214e2
a4ae764
b6214e2
a4ae764
b6214e2
a4ae764
 
b6214e2
a4ae764
489d2fc
9afb882
1331b43
fc0d126
8926bee
1bfef18
 
fe741c0
 
 
 
 
 
 
e18324c
 
 
1bfef18
 
fe741c0
 
 
 
1bfef18
ae34d2f
 
4d8c2e1
 
 
 
ae34d2f
e18324c
 
 
1bfef18
ae34d2f
 
86f8dc0
6c0bb9e
ae34d2f
2e3a636
fc0d126
d128919
e266cd7
 
 
 
 
 
f78561e
e266cd7
9cd9dba
16bbf43
a062596
d6ad11a
81e1810
d6ad11a
e266cd7
3b3c315
9cd9dba
d6ad11a
fe741c0
9ede230
d6ad11a
fe741c0
 
a062596
ae34d2f
16bbf43
fc0d126
1331b43
6a3f081
aa64e27
 
 
 
 
 
 
87b9775
 
aa64e27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87b9775
aa64e27
 
 
 
 
 
87b9775
 
 
 
 
 
 
aa64e27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3edcdca
be37766
 
 
 
 
 
8eb5696
be37766
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbf97cf
 
 
be37766
 
 
 
 
 
 
 
fbf97cf
be37766
 
 
 
 
 
 
 
 
fbf97cf
be37766
 
 
 
 
 
 
 
fbf97cf
be37766
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3edcdca
9cd9dba
65c3b15
9cd9dba
86f8dc0
 
6c0bb9e
b32c597
3edcdca
 
86f8dc0
 
 
 
 
 
 
4909e88
2bb7eb4
e8e3dea
 
c5161d6
2bb7eb4
e16df51
d323a65
a08278f
 
 
 
 
 
 
 
 
be37766
d323a65
 
 
 
 
 
 
 
 
 
 
a08278f
d323a65
aa64e27
 
97c8695
aa64e27
eaf1505
 
 
aa64e27
 
97c8695
92f57e2
6a3f081
 
 
 
 
 
 
4cb147f
6a3f081
 
 
 
6b0d06a
d323a65
4909e88
bfa310d
6a3f081
4909e88
 
0692207
6a3f081
86bcc35
6f4384d
4909e88
a08278f
4909e88
d7e0fa1
cec4f0d
4909e88
e16df51
a08278f
ee45413
aa64e27
6a3f081
6ef4c47
aa64e27
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import gradio as gr
import requests
from bs4 import BeautifulSoup
from huggingface_hub import HfApi,create_repo,upload_file,get_full_repo_name
import re
import os
token_self=os.environ.get("HF_TOKEN")
default_repo_name="collection"
'''
from selenium import webdriver
from bs4 import BeautifulSoup

url = 'https://www.wikipedia.org/'
driver = webdriver.Chrome()
driver.get(url)

html_page = driver.page_source
soup = BeautifulSoup(html_page, 'html.parser')
title = soup.title.string

print(title)

driver.quit()'''
def search_fn(query,count):
    if count>40:
        count = 40
    page = requests.get(f"https://www.google.com/search?q={query}&num={count}")
    soup = BeautifulSoup(page.content)
    #links = soup.findAll("a")
    
    links = soup.findAll("a")
    file = open("myfile.txt", "w")

    for link in soup.find_all("a",href=re.compile("(?<=/url\?q=)(htt.*://.*)")):
        out = (re.split(":(?=http)",link["href"].replace("/url?q=","").split("&sa",1)[0]))
        out = out[0]
        rr=requests.get(f"{out}")
        x_opt = (dict(rr.headers).get("x-frame-options"))
        if x_opt == None:
            frame_l=f'<div class="container-mee"><div class="put-on-top"><a target="_blank" href="{out}">{out}</a></div><iframe class="responsive-iframe-mee" src="{out}" frameborder="3"></iframe></div>'
            file.writelines(frame_l)
        else:
            pass
      
        #print(file1.read())
        print (out)
        print(dict(rr.headers).get("x-frame-options"))

    file.close()
        
    with open("myfile.txt", "r") as file1:
        html_out = file1.read()
    out = format_t(html_out)  
    return out
def details_fn(query):
    link_list=[]
    page = requests.get(f"{query}")
    #links = soup.findAll("a")
    soup = BeautifulSoup(page.content, 'html.parser')
    try:
        title = soup.title.string
    except Exception as e:
        title = query
    try:
        description = soup.find('meta', attrs={'name':'description'})
        description = description['content']
    except Exception as e:
        description = title
    out = f"""
    <center><h3>{title}</h3><br>{description}</center>"""
    try:
        image_out="""
        
        <style>
        .im_container{
            background: white;
            width: 100%;
            display: flex;
            flex-direction: row;
            flex-wrap: wrap;
            justify-content: space-evenly;
            align-items: center;
            align-content: flex-start;
            max-height: 500px;
            overflow-y: auto;
        }
        .im_each{
            background: blue;
            width: 20%;
            border-style: dashed;
            border-width: medium;
        }
        .main_box{
            display:flex;
            flex-direction: column;
        }
        #txt_box{
            visibility:hidden;
        }
        #im_up{
            max-height:500px;
        }
        </style>
        <div class='main_box'>
        <div>
        <div id='txt_box'></div>
        <div><img id='im_up' src=''></div>
        </div>
        <div class='im_container'>
        """
        images = soup.findAll('img')
        if query.startswith("https://"):
            q_beg="https://"
        if query.startswith("http://"):
            q_beg="http://"
        query_src=query.split("//",1)[1]
        if "/" in query_src:
            query_src=query_src.split("/",1)[0]
        query_comp=f'{q_beg}{query_src}'
        for i,img in enumerate(images):
            if not img['src'].startswith("data:"):
                print(query_comp)
                imga=img['src']
                print(imga)
                if imga.startswith("/"):
                    imga = f'{query_comp}{imga}'
                    print(imga)
                im_id = f'img_{i}'
                link_list.append(imga)
                image_out += f"""
                <div id="img_{i}" class='im_each'>
                <img onclick="func('{imga}','img_{i}')" src={imga}>
                </div>
                """
                #print (img['src'])
        format_out = f"""{image_out}</div></div>"""
    except Exception as e:
        format_out = "None"
        print (e)
    return out,format_out,title,description

def first():
    out = '''<h1>Loading'''
    return out

def test(out):
    return format_t(f'<div class="container-mee"><div class="put-on-top"><a target="_blank" href="{out}">{out}</a></div><iframe class="responsive-iframe-mee" src="{out}" frameborder="3"></iframe></div>')
def test_single(out):
    return format_t(f'<div class="container-single"><div class="put-on-top"><a target="_blank" href="{out}">{out}</a></div><iframe class="responsive-iframe-mee" src="{out}" frameborder="3"></iframe></div>')

def format_t(inp):

    style = '''
    .put-on-top{
    align-contents:center;
    border-style: solid;
    border-width: 3px;
    border-radius: 5px;
    background: none;
    padding: 0.5em;
    margin-top:1em;
    margin-bottom:0.3em;
    }
    .grid-mee {
	display: flex;
	flex-direction: row;
	flex-wrap: wrap;
	justify-content: space-evenly;
	align-items: stretch;
	align-content: space-evenly;
}
    
.container-mee {
  position: relative;
  overflow: hidden;
  width: 48%;
  height: 60em;
  margin-top:1em;
}
.container-single {
  position: relative;
  overflow: hidden;
  width: 100%;
  height: 60em;
  margin-top:1em;
}
.responsive-iframe-mee {
  position: relative;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  width: 100%;
  height: 100%;
    
}
  '''
    out = f'''<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <style>
  {style}
  </style>
  <body>
  <div class=grid-mee>
    {inp}
  </div>
  </body>
</html>'''
    return out


def build_space(file_content,file_name,repo_name=None,token=None):

    if repo_name==None or repo_name=="":
        model_id = default_repo_name
    else:
        model_id = repo_name
    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)

    try:
        repo_url = api.create_repo(
            repo_id=model_id,
            repo_type="space",
            space_sdk="static",
            exist_ok=True,
            private=False,
        )
        print(f"""Space Built at {repo_name}""")

    except Exception as e:
        return gr.HTML(f"""{str(e)}""")
  
        
    try:
        api_url = f'https://huggingface.co/api/spaces/{model_id}'
        t_link3= f"https://{repo_name.replace('/','-').replace('_','-')}.static.hf.space/{file_name}-masto.html"
        t_link2= f"https://{repo_name.replace('/','-').replace('_','-')}.static.hf.space/{file_name}-gab.html"
        t_link = f"https://{repo_name.replace('/','-').replace('_','-')}.static.hf.space/{file_name}-main.html"
        
########## norm 
        
        with open("main.html", "w") as f:
            f.write(file_content)

        api.upload_file(
            path_or_fileobj="main.html",
            path_in_repo=f"{file_name}-main.html",
            repo_id=repo_name,
            token=token,
            repo_type="space",
        )

######## gab

        api.upload_file(
            path_or_fileobj="main.html",
            path_in_repo=f"{file_name}-gab.html",
            repo_id=repo_name,
            token=token,
            repo_type="space",
        )
######## masto

        api.upload_file(
            path_or_fileobj="main.html",
            path_in_repo=f"{file_name}-masto.html",
            repo_id=repo_name,
            token=token,
            repo_type="space",
        )
    

        return gr.HTML(f'''<center>Your Interactive Twitter Card Embed Link is:<br><a href="{t_link}" target="_blank">{t_link}</a><br>
                                  Your Interactive Mastodon Card Embed Link is:<br><a href="{t_link3}" target="_blank">{t_link3}</a><br>
                                  Your Interactive Gab Card Embed Link is:<br><a href="{t_link2}" target="_blank">{t_link2}</a><br>
                                  <center><br>''')
    except Exception as e:
        return gr.HTML(f"""{str(e)}""")



load_js = """
    func = function(a,b) {
        console.log(a);
        console.log(b);
        var vv = document.getElementById("txt_box");
        vv.innerHTML=a;
        var ii = document.getElementById("im_up");
        ii.src=a;
        }
    """  
link_js="""
function() {
    const link_url = document.getElementById('txt_box').innerHTML;
    console.log(link_url);
    return [link_url];
}
"""
def preview_img(im):
    print (im)
    if not im.startswith("https:"):
        im = f'https:{im}'
    out = f"""<body><div><img src={im}></div></body>"""
    print(out)
    return out,im
def prepare_card(url,title,description,img):
    filename=url
    if "//" in filename:
        filename=url.split("//",1)[1]
    if "?" in filename:
        if len(filename) > 100:
            filename=filename.split("?",1)[0]
        else:
            filename=filename.replace("?","-").replace("=","-")
    filename = filename.replace(".","-").replace("/","-").replace("?","-").replace("=","-")   
    #filename = f'{filename}.html'
    with open("template.html", "r") as f:
        app = f.read()
    app = app.replace("$space", url)
    app = app.replace("$title", title)
    app = app.replace("$description", description)
    app = app.replace("$image", img)
    app = app.replace("$redirect", url)

    #with open("ai.html", "w") as f:
    #    f.write(app)
    #files.append("ai.html")    
    return(app,filename)

with gr.Blocks() as app:
    gr.HTML("""<h1>Interactive Social Media Card Maker</h1>""")
    gr.HTML("""<h3><b>Step 1:</b> Enter a URL with Iframe capability</h3>""")
    with gr.Row():
        search_box=gr.Textbox(label = "Enter a search topic here to find URL's",scale=2)
        num_return=gr.Number(label= "Number of URL's to return", value=20, scale=1)
        search_btn=gr.Button(value= "Search", scale=1)
    with gr.Row():
        input = gr.Textbox(label = "URL")
        btn = gr.Button("Preview")
    details = gr.HTML("""""")
    with gr.Accordion("Iframe"):
        output = gr.HTML("""""")
    gr.HTML("""<h3><b>Step 2:</b> Select the Image to use on the Card</h3>""")
    with gr.Accordion("Images"):
        images = gr.HTML("""""")
    gr.HTML("""<h3><b>Step 3:</b> Build the Card </h3>""")

    with gr.Row() as im_row:
        with gr.Column():
            title=gr.Textbox(label="Title")
            description=gr.Textbox(label="Description")
            link_list=gr.Textbox(label="Image URL")
            with gr.Accordion("Image Preview"):
                img_card=gr.HTML("""""")

            #img_card=gr.Image()
        with gr.Column():
            grab_im_url_btn=gr.Button("Load Image URL")
            preview_image_btn=gr.Button("Preview Image")
            prepare_btn=gr.Button("Prepare Card")
            bld_btn=gr.Button("Build Card")
            links_html=gr.HTML()
    filename_box = gr.Textbox(label="File Name")
    prepared_html = gr.Textbox(max_lines=50)
    #preview_html = gr.HTML("""""")
    
    app.load(None,None,link_list,js=load_js)
    app.load(None,None,link_list,js=link_js)
    grab_im_url_btn.click(None,None,[link_list],js=link_js)
    preview_image_btn.click(preview_img,link_list,[img_card,link_list])
    prepare_btn.click(prepare_card,[input,title,description,link_list],[prepared_html,filename_box])
    #images.change(update_im,None,link_list,trigger_mode="multiple",js=link_js)
    search_btn.click(search_fn,[search_box,num_return],output)
    btn.click(first,None,output).then(test_single,input,output).then(details_fn,input,[details,images,title,description])
    bld_btn.click(build_space,[prepared_html,filename_box],links_html)
app.launch()