Spaces:
Runtime error
Runtime error
File size: 6,481 Bytes
1dfaf00 077ab50 1dfaf00 077ab50 1dfaf00 077ab50 50f02db 1dfaf00 077ab50 1dfaf00 077ab50 1dfaf00 1846423 1dfaf00 1846423 1dfaf00 beed103 1dfaf00 beed103 1dfaf00 077ab50 50f02db 077ab50 b04b9c4 17e8c6f b04b9c4 1dfaf00 077ab50 1dfaf00 077ab50 |
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 |
import logging
import shutil
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from tempfile import TemporaryDirectory
import requests
import streamlit as st
from huggingface_hub import Repository, create_repo, login, whoami
from huggingpics.data import get_image_urls_by_term
from requests.exceptions import HTTPError
from tqdm.auto import tqdm
logger = logging.getLogger(__name__)
def show_images_of_term(search_term, num_cols=5, num_rows=3):
# Get the image urls
# Arbitrarily adding 2 to make sure we have enough images in the event of a failed request
urls = get_image_urls_by_term(search_term, count=(num_rows * num_cols) + 2)
st.title(search_term)
for row_id in range(num_rows):
cols = st.columns(num_cols)
for col_id in range(num_cols):
cols[col_id].image(urls[row_id * num_cols + col_id], use_column_width=True)
def download_image(img_url, filename):
response = requests.get(img_url)
response.raise_for_status()
img_bytes = response.content
with open(filename, 'wb') as img_file:
img_file.write(img_bytes)
def make_huggingpics_imagefolder(data_dir, search_terms, count=150, overwrite=False, transform=None, resume=False):
data_dir = Path(data_dir)
if data_dir.exists():
if overwrite:
print(f"Deleting existing HuggingPics data directory to create new one: {data_dir}")
shutil.rmtree(data_dir)
else:
print(f"Using existing HuggingPics data directory: '{data_dir}'")
if not resume:
return
pbar = st.progress(0)
for search_term_idx, search_term in enumerate(search_terms):
search_term_dir = data_dir / search_term
search_term_dir.mkdir(exist_ok=True, parents=True)
is_term_dir_nonempty = any(Path(search_term_dir).iterdir())
if is_term_dir_nonempty:
print(f"Skipping search term '{search_term}' because it already has images in it.")
continue
urls = get_image_urls_by_term(search_term, count)
logger.info(f"Saving images of {search_term} to {str(search_term_dir)}...")
with ThreadPoolExecutor() as executor:
for i, url in enumerate(tqdm(urls)):
executor.submit(download_image, url, search_term_dir / f'{i}.jpg')
pbar.progress((search_term_idx + 1) / len(search_terms))
pbar.empty()
def create_dataset(terms):
msg_placeholder = st.empty()
for term in terms:
show_images_of_term(term)
with st.sidebar:
with st.form('Push to Hub'):
dataset_name = st.text_input('Dataset Name', value='huggingpics-data')
do_push = st.form_submit_button("Push to π€ Hub")
if do_push:
msg_placeholder.empty()
if not st.session_state.get('is_logged_in'):
msg_placeholder.error("You must login to push to the hub.")
return
else:
msg_placeholder.empty()
with st.sidebar:
repo_url = create_repo(dataset_name, st.session_state.token, exist_ok=True, repo_type='dataset')
hf_username = whoami(st.session_state.token)['name']
with TemporaryDirectory() as tmp_dir:
repo_owner, repo_name = hf_username, dataset_name
repo_namespace = f"{repo_owner}/{repo_name}"
repo_url = f'https://huggingface.co/datasets/{repo_namespace}'
repo = Repository(
tmp_dir,
clone_from=repo_url,
use_auth_token=st.session_state.token,
git_user=hf_username,
git_email=f'{hf_username}@users.noreply.huggingface.co',
repo_type='dataset',
)
with st.spinner(f"Uploading files to [{repo_namespace}]({repo_url})..."):
with repo.commit("Uploaded from HuggingPics Explorer"):
make_huggingpics_imagefolder(Path(tmp_dir) / 'images', terms, count=150)
st.success(f"View your dataset here π [{repo_namespace}]({repo_url})")
def huggingface_auth_form():
placeholder = st.empty()
is_logged_in = st.session_state.get('is_logged_in', False)
if is_logged_in:
token = st.session_state.token
with placeholder.container():
st.markdown(f"β
Logged in as {whoami(token)['name']}")
do_logout = st.button("Logout")
if do_logout:
st.session_state.token = None
st.session_state.is_logged_in = False
placeholder.empty()
huggingface_auth_form()
else:
with placeholder.container():
username = st.text_input('Username', value=st.session_state.get('username', ''))
password = st.text_input('Password', value="", type="password")
submit = st.button('Login')
if submit:
try:
st.session_state.token = login(username, password)
st.session_state.is_logged_in = True
placeholder.empty()
huggingface_auth_form()
except HTTPError as e:
st.session_state.token = None
st.session_state.is_logged_in = False
st.error("Invalid username or password.")
time.sleep(2)
# huggingface_auth_form() # ???
def main():
with st.sidebar:
st.markdown(
"""
<p align="center">
<h1>π€πΌ HuggingPics Explorer</h1>
<p/>
<p align="center">
<a href="https://github.com/nateraw/huggingpics-explorer" alt="Repo"><img src="https://img.shields.io/github/stars/nateraw/huggingpics-explorer?style=social" /></a>
</p>
""",
unsafe_allow_html=True,
)
term_1 = st.sidebar.text_input('Search Term 1', value='shiba inu')
term_2 = st.sidebar.text_input('Search Term 2', value='husky')
term_3 = st.sidebar.text_input('Search Term 3', value='')
term_4 = st.sidebar.text_input('Search Term 4', value='')
term_5 = st.sidebar.text_input('Search Term 5', value='')
terms = [t for t in [term_1, term_2, term_3, term_4, term_5] if t]
st.markdown('---')
huggingface_auth_form()
st.markdown('---')
_ = create_dataset(terms)
if __name__ == '__main__':
main()
|