File size: 1,928 Bytes
703e13b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from cProfile import label
from distutils.log import debug
from random import choices
import gradio as gr
import re
import requests
import os
import shutil
import gofile
import json
import time


try: os.mkdir('images')
except: print('images dir might already exist...')


def download_local(url):
    resp = requests.get(url, allow_redirects=True)    
    filename, file_extension = os.path.splitext(url)
    filename = os.path.basename(url)
    if file_extension == '':
        filename = filename+'.jpg'
        
    filename = 'images/{}_{}'.format(int(time.time()), filename)
    with open(filename, 'wb') as handler:
        handler.write(resp.content)
    return filename


def download(text, is_upload):
    pattern = '(?:(?:https?|ftp):\/\/)?[\w/\-?=%.]+\.[\w/\-&?=%.]+'
    print(text)
    print('upload?: ',is_upload)

    urls = re.findall(pattern, text)
    print(f'{len(urls)} urls')

    if len(urls) == 0 :
        return 'No Url Found'

    err_msgs = []

    #downloading all files 
    print('downloading...')    
    for i, url in enumerate(urls):
        try:
            download_local(url)
            if i % int(len(urls) * 0.1) == 0:
                print(f'>>> {i} files downloaded')
        except Exception as e :
            err_msgs.append(f'error downloading: {url} - {str(e)}')

    #zipping 
    print('zipping images...')
    shutil.make_archive('images', 'zip', 'images')    
    
    result =  '{} link found, {}'.format(len(urls), " ,\n ".join(err_msgs))

    if is_upload == 'yes':
        print('uploading...')
        download_links = gofile.Gofile().upload(["images.zip"])
        result += f'download link : {" ".join(download_links)}'

    return "images.zip", result

iface = gr.Interface(fn=download, 
                    inputs=["text",gr.Radio(choices=['yes','no'], label='Upload to Gofile? (slow process)')], 
                    outputs=["file", "text"])
iface.launch(debug=True)