gui / app.py
Stereo0001's picture
Update app.py
814abf9
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 30 21:24:16 2023
@author: lizhenzhu
"""
import re
import gradio as gr
import requests
import os
import shutil
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) #只显示网页里面的文件名
filename = 'images/{}_{}'.format(int(time.time()), filename) #这里吧文件名字和文件夹名字链接起来
print('文件名字:',filename)
with open(filename, 'wb') as handler:
for chunk in resp.iter_content(chunk_size = 1024): # 1024 bytes
if chunk:
handler.write(chunk)
print('下载完毕!',filename)
return filename
def download(text):
pattern = '(?:(?:https?|ftp):\/\/)?[\w/\-?=%.]+\.[\w/\-&?=%.]+'
#print(text)
urls = re.findall(pattern, text)
print(f'{len(urls)} urls')
print('转换后的网址:',urls)
if len(urls) == 0 :
return 'No Url Found'
err_msgs = []
#downloading all files
print('downloading...')
for i in urls:
try:
download_local(i)
except Exception as e :
err_msgs.append(f'error downloading: {i} - {str(e)}')
#zipping
print('zipping ...')
shutil.make_archive('images', 'zip','images')
result = '{} link found, {}'.format(len(urls), " ,\n ".join(err_msgs))
#返回压缩好的文件夹名字,后面规定好是文件即可,还返回了一部分文字信息
return "images.zip", result
iface = gr.Interface(fn=download,
inputs=["text"],
outputs=["file", "text"])
iface.launch()