Spaces:
Sleeping
Sleeping
Create backup.py
Browse files
backup.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import requests
|
3 |
+
from bs4 import BeautifulSoup
|
4 |
+
import os
|
5 |
+
import urllib
|
6 |
+
import base64
|
7 |
+
|
8 |
+
def download_file(url, local_filename):
|
9 |
+
if url.startswith('http://') or url.startswith('https://'): # add this line
|
10 |
+
try:
|
11 |
+
with requests.get(url, stream=True) as r:
|
12 |
+
r.raise_for_status()
|
13 |
+
with open(local_filename, 'wb') as f:
|
14 |
+
for chunk in r.iter_content(chunk_size=8192):
|
15 |
+
f.write(chunk)
|
16 |
+
return local_filename
|
17 |
+
except requests.exceptions.HTTPError as err:
|
18 |
+
print(f"HTTP error occurred: {err}") # or use logging
|
19 |
+
|
20 |
+
|
21 |
+
def download_html_and_files(url):
|
22 |
+
html_content = requests.get(url).text
|
23 |
+
soup = BeautifulSoup(html_content, 'html.parser')
|
24 |
+
|
25 |
+
base_url = urllib.parse.urlunparse(urllib.parse.urlparse(url)._replace(path='', params='', query='', fragment=''))
|
26 |
+
|
27 |
+
for link in soup.find_all('a'):
|
28 |
+
file_url = urllib.parse.urljoin(base_url, link.get('href'))
|
29 |
+
local_filename = urllib.parse.urlparse(file_url).path.split('/')[-1]
|
30 |
+
if local_filename: # add this line
|
31 |
+
link['href'] = local_filename
|
32 |
+
download_file(file_url, local_filename)
|
33 |
+
|
34 |
+
with open("index.html", "w") as file:
|
35 |
+
file.write(str(soup))
|
36 |
+
|
37 |
+
|
38 |
+
def list_files(directory_path='.'):
|
39 |
+
return [f for f in os.listdir(directory_path) if os.path.isfile(os.path.join(directory_path, f))]
|
40 |
+
|
41 |
+
def main():
|
42 |
+
st.sidebar.title('Bulk Download Tool')
|
43 |
+
url = st.sidebar.text_input('Please enter a URL to bulk download text and files')
|
44 |
+
if st.sidebar.button('📥 Get All the Content'):
|
45 |
+
download_html_and_files(url)
|
46 |
+
st.sidebar.write('Download complete. Here are the files you can download:')
|
47 |
+
for file in list_files():
|
48 |
+
st.sidebar.markdown(get_download_link(file), unsafe_allow_html=True)
|
49 |
+
|
50 |
+
def get_download_link(file):
|
51 |
+
with open(file, "rb") as f:
|
52 |
+
bytes = f.read()
|
53 |
+
b64 = base64.b64encode(bytes).decode()
|
54 |
+
href = f'<a href="data:file/octet-stream;base64,{b64}" download=\'{file}\'>Click to download {file}</a>'
|
55 |
+
return href
|
56 |
+
|
57 |
+
if __name__ == "__main__":
|
58 |
+
main()
|