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pandas as pd
|
| 5 |
+
import requests
|
| 6 |
+
import io
|
| 7 |
+
import dask.dataframe as dd
|
| 8 |
+
from datasets import load_dataset, Image
|
| 9 |
+
from mlcroissant import Dataset as CroissantDataset
|
| 10 |
+
from huggingface_hub import get_token
|
| 11 |
+
import polars as pl
|
| 12 |
+
import warnings
|
| 13 |
+
import traceback
|
| 14 |
+
|
| 15 |
+
# π€« Let's ignore those pesky warnings, shall we?
|
| 16 |
+
warnings.filterwarnings("ignore")
|
| 17 |
+
|
| 18 |
+
# --- βοΈ Configuration & Constants ---
|
| 19 |
+
|
| 20 |
+
# π¨ Let's give our datasets some personality with emojis and names!
|
| 21 |
+
DATASET_CONFIG = {
|
| 22 |
+
"caselaw": {
|
| 23 |
+
"name": "common-pile/caselaw_access_project",
|
| 24 |
+
"emoji": "βοΈ",
|
| 25 |
+
"search_col": "text",
|
| 26 |
+
"methods": ["π¨ API (requests)", "π§ Dask", "π₯ Croissant"],
|
| 27 |
+
"is_public": True,
|
| 28 |
+
},
|
| 29 |
+
"prompts": {
|
| 30 |
+
"name": "fka/awesome-chatgpt-prompts",
|
| 31 |
+
"emoji": "π€",
|
| 32 |
+
"search_col": ["act", "prompt"],
|
| 33 |
+
"methods": ["πΌ Pandas", "π¨ API (requests)", "π₯ Croissant"],
|
| 34 |
+
"is_public": True,
|
| 35 |
+
},
|
| 36 |
+
"finance": {
|
| 37 |
+
"name": "snorkelai/agent-finance-reasoning",
|
| 38 |
+
"emoji": "π°",
|
| 39 |
+
"search_col": ["question", "answer"],
|
| 40 |
+
"methods": ["πΌ Pandas", "π§ Polars", "π¨ API (requests)", "π₯ Croissant"],
|
| 41 |
+
"is_public": False,
|
| 42 |
+
},
|
| 43 |
+
"medical": {
|
| 44 |
+
"name": "FreedomIntelligence/medical-o1-reasoning-SFT",
|
| 45 |
+
"emoji": "π©Ί",
|
| 46 |
+
"search_col": "conversations",
|
| 47 |
+
"methods": ["πΌ Pandas", "π§ Polars", "π¨ API (requests)", "π₯ Croissant"],
|
| 48 |
+
"is_public": False,
|
| 49 |
+
},
|
| 50 |
+
"inscene": {
|
| 51 |
+
"name": "peteromallet/InScene-Dataset",
|
| 52 |
+
"emoji": "πΌοΈ",
|
| 53 |
+
"search_col": "text",
|
| 54 |
+
"methods": ["π€ Datasets", "πΌ Pandas", "π§ Polars", "π¨ API (requests)", "π₯ Croissant"],
|
| 55 |
+
"is_public": False,
|
| 56 |
+
},
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
# --- ν¬ Helpers & Utility Functions ---
|
| 60 |
+
|
| 61 |
+
def get_auth_headers():
|
| 62 |
+
"""π Creates authorization headers if a Hugging Face token is available."""
|
| 63 |
+
token = get_token()
|
| 64 |
+
return {"Authorization": f"Bearer {token}"} if token else {}
|
| 65 |
+
|
| 66 |
+
def dataframe_to_outputs(df: pd.DataFrame):
|
| 67 |
+
"""
|
| 68 |
+
π Takes a DataFrame and magically transforms it into various formats for your viewing pleasure.
|
| 69 |
+
Like a data chameleon!
|
| 70 |
+
"""
|
| 71 |
+
if df.empty:
|
| 72 |
+
return "No results found. π€·", None, None, "No results to copy."
|
| 73 |
+
|
| 74 |
+
df_str = df.astype(str)
|
| 75 |
+
markdown_output = df_str.to_markdown(index=False)
|
| 76 |
+
|
| 77 |
+
csv_buffer = io.StringIO()
|
| 78 |
+
df.to_csv(csv_buffer, index=False)
|
| 79 |
+
csv_buffer.seek(0)
|
| 80 |
+
|
| 81 |
+
excel_buffer = io.BytesIO()
|
| 82 |
+
df.to_excel(excel_buffer, index=False, engine='openpyxl')
|
| 83 |
+
excel_buffer.seek(0)
|
| 84 |
+
|
| 85 |
+
tab_delimited_output = df.to_csv(sep='\t', index=False)
|
| 86 |
+
|
| 87 |
+
return markdown_output, gr.File.from_bytes(csv_buffer.getvalue(), "results.csv"), gr.File.from_bytes(excel_buffer.getvalue(), "results.xlsx"), tab_delimited_output
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def handle_error(e: Exception):
|
| 91 |
+
"""
|
| 92 |
+
π± Oh no! An error! This function catches it and displays it nicely.
|
| 93 |
+
Because even errors deserve to look good.
|
| 94 |
+
"""
|
| 95 |
+
error_message = f"π¨ An error occurred: {str(e)}\n\n"
|
| 96 |
+
auth_tip = "π For gated datasets, did you log in? Try `huggingface-cli login` in your terminal."
|
| 97 |
+
full_trace = traceback.format_exc()
|
| 98 |
+
print(full_trace)
|
| 99 |
+
|
| 100 |
+
if "401" in str(e) or "Gated" in str(e):
|
| 101 |
+
error_message += auth_tip
|
| 102 |
+
|
| 103 |
+
return (
|
| 104 |
+
pd.DataFrame(),
|
| 105 |
+
gr.Gallery(None, label="πΌοΈ Image Results"),
|
| 106 |
+
f"```\n{error_message}\n\n{full_trace}\n```",
|
| 107 |
+
None,
|
| 108 |
+
None,
|
| 109 |
+
error_message,
|
| 110 |
+
f"```python\n# π¨ Error during code generation:\n# {e}\n```"
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
# --- π£ Data Fetching & Processing Functions ---
|
| 114 |
+
|
| 115 |
+
def fetch_data(dataset_key: str, access_method: str, query: str):
|
| 116 |
+
"""
|
| 117 |
+
π The main mission control function! It fetches, searches, and formats data.
|
| 118 |
+
It's the brains of the operation.
|
| 119 |
+
"""
|
| 120 |
+
try:
|
| 121 |
+
config = DATASET_CONFIG[dataset_key]
|
| 122 |
+
repo_id = config["name"]
|
| 123 |
+
search_cols = [config["search_col"]] if isinstance(config["search_col"], str) else config["search_col"]
|
| 124 |
+
df = pd.DataFrame()
|
| 125 |
+
code_snippet = ""
|
| 126 |
+
|
| 127 |
+
if "API" in access_method:
|
| 128 |
+
url = f"https://datasets-server.huggingface.co/rows?dataset={repo_id}&config=default&split=train&offset=0&length=100"
|
| 129 |
+
headers = get_auth_headers() if not config["is_public"] else {}
|
| 130 |
+
response = requests.get(url, headers=headers)
|
| 131 |
+
response.raise_for_status()
|
| 132 |
+
data = response.json()
|
| 133 |
+
df = pd.json_normalize(data['rows'], record_path='row', meta=['row_idx', 'truncated_cells'])
|
| 134 |
+
df = df.drop(columns=['row_idx', 'truncated_cells'], errors='ignore')
|
| 135 |
+
|
| 136 |
+
code_snippet = f"""
|
| 137 |
+
# π» Generated Code: API (requests)
|
| 138 |
+
import requests
|
| 139 |
+
import pandas as pd
|
| 140 |
+
|
| 141 |
+
# For gated datasets, get your token from https://huggingface.co/settings/tokens
|
| 142 |
+
# Make sure to `huggingface-cli login` first.
|
| 143 |
+
headers = {{"Authorization": "Bearer YOUR_HF_TOKEN"}}
|
| 144 |
+
url = "{url}"
|
| 145 |
+
response = requests.get(url, headers=headers) # Pass headers for gated datasets
|
| 146 |
+
data = response.json()
|
| 147 |
+
df = pd.json_normalize(data['rows'], record_path='row')
|
| 148 |
+
print(df.head())
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
elif "Pandas" in access_method:
|
| 152 |
+
file_path = f"hf://datasets/{repo_id}/"
|
| 153 |
+
if repo_id == "fka/awesome-chatgpt-prompts":
|
| 154 |
+
file_path += "prompts.csv"
|
| 155 |
+
df = pd.read_csv(file_path)
|
| 156 |
+
else:
|
| 157 |
+
try:
|
| 158 |
+
df = pd.read_parquet(f"{file_path}data/train-00000-of-00001.parquet")
|
| 159 |
+
except:
|
| 160 |
+
try:
|
| 161 |
+
df = pd.read_parquet(f"{file_path}train.parquet")
|
| 162 |
+
except:
|
| 163 |
+
df = pd.read_json(f"{file_path}medical_o1_sft.json")
|
| 164 |
+
|
| 165 |
+
code_snippet = f"""
|
| 166 |
+
# π» Generated Code: Pandas
|
| 167 |
+
import pandas as pd
|
| 168 |
+
|
| 169 |
+
# Make sure to `huggingface-cli login` for gated datasets.
|
| 170 |
+
file_path = "{file_path}"
|
| 171 |
+
df = pd.{'read_csv' if '.csv' in file_path else ('read_json' if '.json' in file_path else 'read_parquet')}(file_path)
|
| 172 |
+
print(df.head())
|
| 173 |
+
"""
|
| 174 |
+
|
| 175 |
+
elif "Polars" in access_method:
|
| 176 |
+
file_path = f"hf://datasets/{repo_id}/"
|
| 177 |
+
try:
|
| 178 |
+
df = pl.read_parquet(f"{file_path}data/train-00000-of-00001.parquet").to_pandas()
|
| 179 |
+
except:
|
| 180 |
+
try:
|
| 181 |
+
df = pl.read_parquet(f"{file_path}train.parquet").to_pandas()
|
| 182 |
+
except:
|
| 183 |
+
df = pl.read_json(f"{file_path}medical_o1_sft.json").to_pandas()
|
| 184 |
+
|
| 185 |
+
code_snippet = f"""
|
| 186 |
+
# π» Generated Code: Polars
|
| 187 |
+
import polars as pl
|
| 188 |
+
|
| 189 |
+
# Make sure to `huggingface-cli login` for gated datasets.
|
| 190 |
+
file_path = "{'hf://datasets/' + repo_id + '/data/train-00000-of-00001.parquet'}"
|
| 191 |
+
df = pl.read_parquet(file_path)
|
| 192 |
+
print(df.head())
|
| 193 |
+
"""
|
| 194 |
+
|
| 195 |
+
elif "Datasets" in access_method:
|
| 196 |
+
ds = load_dataset(repo_id, split='train[:100]')
|
| 197 |
+
df = ds.to_pandas()
|
| 198 |
+
code_snippet = f"""
|
| 199 |
+
# π» Generated Code: Datasets
|
| 200 |
+
from datasets import load_dataset
|
| 201 |
+
|
| 202 |
+
# Make sure to `huggingface-cli login` for gated datasets.
|
| 203 |
+
ds = load_dataset("{repo_id}", split='train')
|
| 204 |
+
print(ds)
|
| 205 |
+
"""
|
| 206 |
+
|
| 207 |
+
elif "Dask" in access_method:
|
| 208 |
+
df = dd.read_json(f"hf://datasets/{repo_id}/**/*.jsonl.gz").head(100)
|
| 209 |
+
code_snippet = f"""
|
| 210 |
+
# π» Generated Code: Dask
|
| 211 |
+
import dask.dataframe as dd
|
| 212 |
+
|
| 213 |
+
# Make sure to `huggingface-cli login` for gated datasets.
|
| 214 |
+
ddf = dd.read_json("hf://datasets/{repo_id}/**/*.jsonl.gz")
|
| 215 |
+
print(ddf.head())
|
| 216 |
+
"""
|
| 217 |
+
|
| 218 |
+
elif "Croissant" in access_method:
|
| 219 |
+
headers = get_auth_headers() if not config["is_public"] else {}
|
| 220 |
+
jsonld_url = f"https://huggingface.co/api/datasets/{repo_id}/croissant"
|
| 221 |
+
jsonld = requests.get(jsonld_url, headers=headers).json()
|
| 222 |
+
ds = CroissantDataset(jsonld=jsonld)
|
| 223 |
+
records = ds.records("default")
|
| 224 |
+
data_rows = [row for _, row in zip(range(100), records)]
|
| 225 |
+
df = pd.DataFrame(data_rows)
|
| 226 |
+
code_snippet = f"""
|
| 227 |
+
# π» Generated Code: Croissant
|
| 228 |
+
import requests
|
| 229 |
+
from mlcroissant import Dataset as CroissantDataset
|
| 230 |
+
import pandas as pd
|
| 231 |
+
|
| 232 |
+
# For gated datasets, get your token from https://huggingface.co/settings/tokens
|
| 233 |
+
headers = {{"Authorization": "Bearer YOUR_HF_TOKEN"}}
|
| 234 |
+
jsonld_url = "{jsonld_url}"
|
| 235 |
+
jsonld = requests.get(jsonld_url, headers=headers).json()
|
| 236 |
+
ds = CroissantDataset(jsonld=jsonld)
|
| 237 |
+
records = ds.records("default") # This is a generator
|
| 238 |
+
|
| 239 |
+
# To preview data:
|
| 240 |
+
preview_rows = [row for _, row in zip(range(100), records)]
|
| 241 |
+
df = pd.DataFrame(preview_rows)
|
| 242 |
+
print(df.head())
|
| 243 |
+
"""
|
| 244 |
+
|
| 245 |
+
# --- π Universal Search Logic ---
|
| 246 |
+
if query and not df.empty:
|
| 247 |
+
if dataset_key == 'medical':
|
| 248 |
+
df = df[df['conversations'].apply(lambda x: isinstance(x, list) and len(x) > 1 and query.lower() in str(x[1].get('value', '')).lower())]
|
| 249 |
+
else:
|
| 250 |
+
combined_mask = pd.Series([False] * len(df))
|
| 251 |
+
for col in search_cols:
|
| 252 |
+
if col in df.columns and pd.api.types.is_string_dtype(df[col]):
|
| 253 |
+
combined_mask |= df[col].str.contains(query, case=False, na=False)
|
| 254 |
+
df = df[combined_mask]
|
| 255 |
+
|
| 256 |
+
# --- πΌοΈ Special Image Handling ---
|
| 257 |
+
gallery_output = None
|
| 258 |
+
if dataset_key == 'inscene' and not df.empty:
|
| 259 |
+
gallery_data = []
|
| 260 |
+
for _, row in df.iterrows():
|
| 261 |
+
if isinstance(row.get('image'), Image.Image):
|
| 262 |
+
gallery_data.append((row['image'], row.get('text', '')))
|
| 263 |
+
gallery_output = gr.Gallery(gallery_data, label="πΌοΈ Image Results", height=400)
|
| 264 |
+
|
| 265 |
+
md, csv, xlsx, tab = dataframe_to_outputs(df)
|
| 266 |
+
return df, gallery_output, md, csv, xlsx, tab, code_snippet
|
| 267 |
+
|
| 268 |
+
except Exception as e:
|
| 269 |
+
return handle_error(e)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
# --- πΌοΈ UI Generation ---
|
| 273 |
+
|
| 274 |
+
def create_dataset_tab(dataset_key: str):
|
| 275 |
+
"""
|
| 276 |
+
ποΈ This function builds a whole tab in our UI for a single dataset.
|
| 277 |
+
It's like a little construction worker for Gradio interfaces.
|
| 278 |
+
"""
|
| 279 |
+
config = DATASET_CONFIG[dataset_key]
|
| 280 |
+
|
| 281 |
+
with gr.Tab(f"{config['emoji']} {dataset_key.capitalize()}"):
|
| 282 |
+
gr.Markdown(f"## {config['emoji']} Query the `{config['name']}` Dataset")
|
| 283 |
+
if not config['is_public']:
|
| 284 |
+
gr.Markdown("**Note:** This is a gated dataset. Please log in via `huggingface-cli login` in your terminal first.")
|
| 285 |
+
|
| 286 |
+
with gr.Row():
|
| 287 |
+
access_method = gr.Radio(config['methods'], label="π Access Method", value=config['methods'][0])
|
| 288 |
+
query = gr.Textbox(label="π Search Query", placeholder="Enter a keyword to search...")
|
| 289 |
+
|
| 290 |
+
fetch_button = gr.Button("π Go Fetch!")
|
| 291 |
+
|
| 292 |
+
df_output = gr.DataFrame(label="π Results DataFrame", interactive=False, wrap=True)
|
| 293 |
+
gallery_output = gr.Gallery(visible=(dataset_key == 'inscene'), label="πΌοΈ Image Results")
|
| 294 |
+
|
| 295 |
+
with gr.Accordion("π View/Export Full Results", open=False):
|
| 296 |
+
markdown_output = gr.Markdown(label="π Markdown View")
|
| 297 |
+
with gr.Row():
|
| 298 |
+
csv_output = gr.File(label="β¬οΈ Download CSV")
|
| 299 |
+
xlsx_output = gr.File(label="β¬οΈ Download XLSX")
|
| 300 |
+
# CHANGED: Removed the language parameter entirely for maximum compatibility.
|
| 301 |
+
copy_output = gr.Code(label="π Copy-Paste (Tab-Delimited)")
|
| 302 |
+
|
| 303 |
+
code_output = gr.Code(label="π» Python Code Snippet", language="python")
|
| 304 |
+
|
| 305 |
+
fetch_button.click(
|
| 306 |
+
fn=fetch_data,
|
| 307 |
+
inputs=[gr.State(dataset_key), access_method, query],
|
| 308 |
+
outputs=[df_output, gallery_output, markdown_output, csv_output, xlsx_output, copy_output, code_output]
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
# --- π Main App ---
|
| 312 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="Hugging Face Dataset Explorer") as demo:
|
| 313 |
+
gr.Markdown("# π€ Hugging Face Dataset Explorer")
|
| 314 |
+
gr.Markdown(
|
| 315 |
+
"Select a dataset, choose an access method, type a query, and see the results instantly. "
|
| 316 |
+
"The app demonstrates various ways to access and search Hugging Face datasets and generates the code for you!"
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
with gr.Tabs():
|
| 320 |
+
for key in DATASET_CONFIG.keys():
|
| 321 |
+
create_dataset_tab(key)
|
| 322 |
+
|
| 323 |
+
if __name__ == "__main__":
|
| 324 |
+
demo.launch(debug=True)
|