Spaces:
Sleeping
Sleeping
File size: 22,380 Bytes
c5fed00 dd7df46 c5fed00 4bc565f c5fed00 4bc565f c5fed00 be30fa9 c5fed00 be30fa9 c5fed00 1af5fea c5fed00 be30fa9 c5fed00 be30fa9 c5fed00 4bc565f c5fed00 4bc565f c5fed00 dd7df46 c5fed00 dd7df46 c5fed00 dd7df46 c5fed00 dd7df46 c5fed00 dd7df46 c5fed00 dd7df46 c5fed00 dd7df46 c5fed00 be30fa9 c5fed00 be30fa9 c5fed00 be30fa9 dd7df46 be30fa9 c5fed00 be30fa9 c5fed00 be30fa9 dd7df46 be30fa9 dd7df46 be30fa9 c5fed00 be30fa9 c5fed00 be30fa9 c5fed00 8e3b19a 1af5fea 8e3b19a dd7df46 8e3b19a dd7df46 8e3b19a dd7df46 8e3b19a dd7df46 8e3b19a dd7df46 8e3b19a c5fed00 8e3b19a |
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 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 |
from datetime import datetime, timezone
import gradio as gr
import pandas as pd
from datasets import Dataset, load_dataset
from constants import (
COUNTRIES,
DATASET_TYPES,
DOMAINS,
LANGUAGES,
TASKS,
format_dataframe_for_display,
format_dataframe_for_html_display,
)
# Dataset configuration
DATASET_NAME = "somosnlp/recursos-pln-es"
CONFIG_NAME = "datasets"
RESOURCE_TYPE = "datasets"
RESOURCE_TITLE = "Datasets"
def load_data() -> pd.DataFrame:
"""Load data from HuggingFace dataset or return empty DataFrame."""
try:
dataset = load_dataset(DATASET_NAME, CONFIG_NAME, split="train")
return dataset.to_pandas()
except Exception as e:
print(f"Could not load {RESOURCE_TYPE} dataset: {e}")
# Return empty DataFrame with required columns
return pd.DataFrame(
columns=[
"name",
"github_url",
"huggingface_url",
"zenodo_url",
"paper_url",
"dataset_type",
"task",
"domain",
"website_url",
"countries",
"languages",
"submitted_by",
"date_submitted",
]
)
def search_and_filter_data(df: pd.DataFrame, search_query: str) -> pd.DataFrame:
"""Filter dataframe based on search query."""
if search_query == "":
return df
else:
filtered_df = df[
df.apply(
lambda row: row.astype(str)
.str.contains(search_query, case=False)
.any(),
axis=1,
)
]
return filtered_df
def validate_url(url: str) -> bool:
"""Validate if a string is a valid URL."""
if not url:
return True # Empty URLs are allowed for optional fields
return url.startswith(("http://", "https://"))
def submit_resource(
name: str,
github_url: str,
huggingface_url: str,
zenodo_url: str,
paper_url: str,
dataset_type: str,
task: list,
domain: list,
website_url: str,
countries: list,
languages: list,
profile: gr.OAuthProfile | None,
):
"""Submit a new resource to the corresponding dataset."""
# Login required
if profile is None:
return "β Error: You need to be logged in to submit a resource."
# Validate required fields
if not name:
return "β Error: Name is required."
if not dataset_type:
return "β Error: Dataset type is required."
# Validate that at least one URL is provided
if not any([github_url, huggingface_url, zenodo_url]):
return "β Error: At least one of GitHub URL, Hugging Face URL, or Zenodo URL must be provided."
# Validate URLs
urls_to_check = [
("GitHub URL", github_url),
("Hugging Face URL", huggingface_url),
("Zenodo URL", zenodo_url),
("Paper URL", paper_url),
("Website URL", website_url),
]
for url_name, url_value in urls_to_check:
if url_value and not validate_url(url_value):
return f"β Error: {url_name} must be a valid URL starting with http:// or https://"
try:
username = profile.username
current_time = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
# Create new row data
new_data = {
"name": name,
"github_url": github_url,
"huggingface_url": huggingface_url,
"zenodo_url": zenodo_url,
"paper_url": paper_url,
"dataset_type": dataset_type,
"task": ", ".join(task) if task else "",
"domain": ", ".join(domain) if domain else "",
"website_url": website_url,
"countries": ", ".join(countries) if countries else "",
"languages": ", ".join(languages) if languages else "",
"submitted_by": username,
"date_submitted": current_time,
}
# Try to load existing dataset, or create new one
try:
existing_dataset = load_dataset(DATASET_NAME, CONFIG_NAME, split="train")
existing_df = existing_dataset.to_pandas()
# Add new row
updated_df = pd.concat(
[existing_df, pd.DataFrame([new_data])], ignore_index=True
)
except:
# Create new dataset if it doesn't exist
updated_df = pd.DataFrame([new_data])
# Convert back to Dataset and push to hub
updated_dataset = Dataset.from_pandas(updated_df)
updated_dataset.push_to_hub(
DATASET_NAME,
config_name=CONFIG_NAME,
commit_message=f"Add {name} by {username}",
token=True, # Use the user's token
)
return f"β
Success: {name} has been submitted successfully!"
except Exception as e:
return f"β Error: Failed to submit resource. {str(e)}"
def create_all_tab():
"""Create the 'All' tab for this resource type."""
with gr.TabItem("π All", id=f"{RESOURCE_TYPE}_all"):
gr.Markdown(f"### All {RESOURCE_TITLE}")
search_box = gr.Textbox(
placeholder=f"Search {RESOURCE_TYPE}...",
label="Filter the table",
show_label=False,
)
# Load and format initial data with clickable links
def get_formatted_data():
df = load_data()
return format_dataframe_for_display(
df,
url_columns=[
"github_url",
"huggingface_url",
"zenodo_url",
"paper_url",
"website_url",
],
hide_columns=["date_submitted"],
)
# Use Dataframe component with HTML rendering enabled
table = gr.Dataframe(
value=get_formatted_data(),
label=RESOURCE_TITLE,
show_label=False,
interactive=False,
wrap=False, # Disable wrapping to show full text in single lines
datatype="markdown", # Enable HTML rendering
)
# Connect search functionality
def search_and_format(query):
initial_df = load_data()
filtered_df = search_and_filter_data(initial_df, query)
return format_dataframe_for_display(
filtered_df,
url_columns=[
"github_url",
"huggingface_url",
"zenodo_url",
"paper_url",
"website_url",
],
hide_columns=["date_submitted"],
)
search_box.change(
fn=search_and_format,
inputs=search_box,
outputs=table,
)
# Refresh button to reload data
refresh_btn = gr.Button("π Refresh Data", variant="secondary")
refresh_btn.click(fn=get_formatted_data, outputs=table)
return table
def create_contribute_tab():
"""Create the 'Contribute' tab for this resource type."""
with gr.TabItem("β Contribute", id=f"{RESOURCE_TYPE}_contribute"):
gr.Markdown(f"### Contribute a New {RESOURCE_TITLE[:-1]}")
# Login section
gr.Markdown("Please log in to contribute resources:")
login_button = gr.LoginButton(elem_id=f"{RESOURCE_TYPE}-oauth-button")
gr.Markdown("Please fill in the information below to add a new dataset:")
with gr.Column():
# Required fields
name_input = gr.Textbox(
label="Name *",
placeholder="Enter the name of the dataset",
info="The name or title of the dataset (required)",
)
dataset_type_input = gr.Dropdown(
label="Dataset Type *",
choices=DATASET_TYPES,
info="Type of dataset (required)",
multiselect=False,
)
# URL fields (at least one required)
gr.Markdown("**URLs** (at least one required)")
with gr.Row():
github_url_input = gr.Textbox(
label="GitHub URL",
placeholder="https://github.com/...",
info="GitHub repository URL",
)
huggingface_url_input = gr.Textbox(
label="Hugging Face URL",
placeholder="https://huggingface.co/datasets/...",
info="Hugging Face dataset URL",
)
zenodo_url_input = gr.Textbox(
label="Zenodo URL",
placeholder="https://zenodo.org/...",
info="Zenodo repository URL",
)
# Optional fields
gr.Markdown("**Optional Information**")
paper_url_input = gr.Textbox(
label="Paper URL",
placeholder="https://...",
info="Link to associated research paper",
)
website_url_input = gr.Textbox(
label="Website URL",
placeholder="https://...",
info="Project or dataset website",
)
# Multi-select fields
task_input = gr.CheckboxGroup(
label="Tasks",
choices=TASKS,
info="What tasks is this dataset suitable for?",
)
domain_input = gr.CheckboxGroup(
label="Domain",
choices=DOMAINS,
info="Specific domains covered by the dataset",
)
countries_input = gr.CheckboxGroup(
label="Countries",
choices=[
"Spain",
"Mexico",
"Argentina",
"Colombia",
"Peru",
"Venezuela",
"Chile",
"Ecuador",
"Guatemala",
"Cuba",
"Bolivia",
"Dominican Republic",
"Honduras",
"Paraguay",
"El Salvador",
"Nicaragua",
"Costa Rica",
"Panama",
"Uruguay",
"Puerto Rico",
"Brazil",
"Portugal",
],
info="Countries where Spanish or Portuguese are spoken",
)
languages_input = gr.CheckboxGroup(
label="Languages",
choices=[
"spanish",
"portuguese",
"basque",
"catalan",
"galician",
"guarani",
"quechua",
],
info="Languages included in the dataset",
)
submit_btn = gr.Button(f"Submit {RESOURCE_TITLE[:-1]}", variant="primary")
result_msg = gr.Markdown()
# Submit function
submit_btn.click(
fn=submit_resource,
inputs=[
name_input,
github_url_input,
huggingface_url_input,
zenodo_url_input,
paper_url_input,
dataset_type_input,
task_input,
domain_input,
website_url_input,
countries_input,
languages_input,
],
outputs=[result_msg],
)
return (
name_input,
github_url_input,
huggingface_url_input,
zenodo_url_input,
paper_url_input,
dataset_type_input,
task_input,
domain_input,
website_url_input,
countries_input,
languages_input,
submit_btn,
result_msg,
)
def search_entries(query: str) -> pd.DataFrame:
"""Search for entries by name or URL."""
if not query.strip():
return pd.DataFrame()
df = load_data()
if df.empty:
return df
# Search in name, github_url, huggingface_url, and zenodo_url columns
mask = (
df["name"].str.contains(query, case=False, na=False)
| df["github_url"].str.contains(query, case=False, na=False)
| df["huggingface_url"].str.contains(query, case=False, na=False)
| df["zenodo_url"].str.contains(query, case=False, na=False)
)
return df[mask]
def load_entry_for_edit(selected_entry: str) -> tuple:
"""Load a specific entry for editing."""
if not selected_entry:
return ("",) * 11 # Return empty values for all fields
df = load_data()
if df.empty:
return ("",) * 11
# Find the entry by name
entry = df[df["name"] == selected_entry].iloc[0]
# Convert comma-separated strings back to lists for multi-select components
task_list = [t.strip() for t in entry["task"].split(",")] if entry["task"] else []
domain_list = (
[d.strip() for d in entry["domain"].split(",")] if entry["domain"] else []
)
countries_list = (
[c.strip() for c in entry["countries"].split(",")] if entry["countries"] else []
)
languages_list = (
[l.strip() for l in entry["languages"].split(",")] if entry["languages"] else []
)
return (
entry["name"],
entry["github_url"],
entry["huggingface_url"],
entry["zenodo_url"],
entry["paper_url"],
entry["dataset_type"],
task_list,
domain_list,
entry["website_url"],
countries_list,
languages_list,
)
def update_entry(
original_name: str,
name: str,
github_url: str,
huggingface_url: str,
zenodo_url: str,
paper_url: str,
dataset_type: str,
task: list,
domain: list,
website_url: str,
countries: list,
languages: list,
profile: gr.OAuthProfile | None,
):
"""Update an existing entry."""
# Login required
if profile is None:
return "β Error: You need to be logged in to edit entries."
username = profile.username
if not username:
return "β Could not get username from profile."
if not original_name:
return "β No entry selected to edit."
if not name.strip():
return "β Name is required."
# Validate that at least one URL is provided
urls = [github_url.strip(), huggingface_url.strip(), zenodo_url.strip()]
if not any(urls):
return "β At least one URL (GitHub, Hugging Face, or Zenodo) is required."
# Validate URLs
for url_field, url_value in [
("GitHub URL", github_url),
("Hugging Face URL", huggingface_url),
("Zenodo URL", zenodo_url),
("Paper URL", paper_url),
("Website URL", website_url),
]:
if url_value.strip() and not validate_url(url_value):
return f"β Invalid {url_field}. Please provide a valid URL."
try:
# Load existing dataset
existing_dataset = load_dataset(DATASET_NAME, CONFIG_NAME, split="train")
existing_df = existing_dataset.to_pandas()
# Find and update the entry
mask = existing_df["name"] == original_name
if not mask.any():
return f"β Entry '{original_name}' not found."
# Update the entry
current_time = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
existing_df.loc[mask, "name"] = name
existing_df.loc[mask, "github_url"] = github_url
existing_df.loc[mask, "huggingface_url"] = huggingface_url
existing_df.loc[mask, "zenodo_url"] = zenodo_url
existing_df.loc[mask, "paper_url"] = paper_url
existing_df.loc[mask, "dataset_type"] = dataset_type
existing_df.loc[mask, "task"] = ", ".join(task) if task else ""
existing_df.loc[mask, "domain"] = ", ".join(domain) if domain else ""
existing_df.loc[mask, "website_url"] = website_url
existing_df.loc[mask, "countries"] = ", ".join(countries) if countries else ""
existing_df.loc[mask, "languages"] = ", ".join(languages) if languages else ""
existing_df.loc[mask, "date_submitted"] = current_time
# Convert back to Dataset and push to hub
updated_dataset = Dataset.from_pandas(existing_df)
updated_dataset.push_to_hub(
DATASET_NAME,
config_name=CONFIG_NAME,
commit_message=f"Update dataset entry: {name} (edited by {username})",
)
return f"β
Successfully updated '{name}'!"
except Exception as e:
return f"β Error updating entry: {str(e)}"
def create_edit_tab():
"""Create the edit tab for modifying existing entries."""
with gr.TabItem("βοΈ Edit", id=f"{RESOURCE_TYPE}_edit"):
gr.Markdown(f"### Edit Existing {RESOURCE_TITLE}")
gr.Markdown("Please log in to edit entries:")
login_button = gr.LoginButton(elem_id=f"{RESOURCE_TYPE}-edit-oauth-button")
gr.Markdown("Search for an entry to edit:")
with gr.Row():
search_input = gr.Textbox(
label="Search by name or URL",
placeholder="Enter dataset name or URL to search...",
scale=3,
)
search_btn = gr.Button("π Search", scale=1)
search_results = gr.Dropdown(
label="Select entry to edit", choices=[], interactive=True
)
gr.Markdown("---")
gr.Markdown("**Edit the selected entry:**")
with gr.Column(visible=False) as edit_form:
name_input = gr.Textbox(label="Name *", placeholder="Dataset name")
dataset_type_input = gr.Dropdown(
label="Dataset Type *",
choices=DATASET_TYPES,
value="benchmark",
)
gr.Markdown("**URLs** (at least one required)")
with gr.Row():
github_url_input = gr.Textbox(
label="GitHub URL", placeholder="https://github.com/..."
)
huggingface_url_input = gr.Textbox(
label="Hugging Face URL",
placeholder="https://huggingface.co/datasets/...",
)
zenodo_url_input = gr.Textbox(
label="Zenodo URL", placeholder="https://zenodo.org/..."
)
gr.Markdown("**Optional Information**")
paper_url_input = gr.Textbox(
label="Paper URL", placeholder="https://arxiv.org/..."
)
website_url_input = gr.Textbox(
label="Website URL", placeholder="https://..."
)
task_input = gr.CheckboxGroup(
label="Tasks",
choices=TASKS,
)
domain_input = gr.CheckboxGroup(
label="Domain",
choices=DOMAINS,
)
countries_input = gr.CheckboxGroup(
label="Countries",
choices=COUNTRIES,
)
languages_input = gr.CheckboxGroup(
label="Languages",
choices=LANGUAGES,
)
update_btn = gr.Button("πΎ Update Entry", variant="primary")
result_msg = gr.Markdown()
# Store the original name for updating
original_name_state = gr.State("")
def search_and_update_dropdown(query):
results_df = search_entries(query)
if results_df.empty:
return gr.Dropdown(choices=[], value=None)
else:
choices = results_df["name"].tolist()
return gr.Dropdown(choices=choices, value=None)
def load_entry_and_show_form(selected_entry):
if not selected_entry:
return (gr.Column(visible=False), "", *[("",) * 11])
entry_data = load_entry_for_edit(selected_entry)
return (gr.Column(visible=True), selected_entry, *entry_data)
# Event handlers
search_btn.click(
fn=search_and_update_dropdown,
inputs=[search_input],
outputs=[search_results],
)
search_results.change(
fn=load_entry_and_show_form,
inputs=[search_results],
outputs=[
edit_form,
original_name_state,
name_input,
github_url_input,
huggingface_url_input,
zenodo_url_input,
paper_url_input,
dataset_type_input,
task_input,
domain_input,
website_url_input,
countries_input,
languages_input,
],
)
update_btn.click(
fn=update_entry,
inputs=[
original_name_state,
name_input,
github_url_input,
huggingface_url_input,
zenodo_url_input,
paper_url_input,
dataset_type_input,
task_input,
domain_input,
website_url_input,
countries_input,
languages_input,
],
outputs=[result_msg],
)
return (
search_input,
search_btn,
search_results,
edit_form,
name_input,
dataset_type_input,
github_url_input,
huggingface_url_input,
zenodo_url_input,
paper_url_input,
website_url_input,
task_input,
domain_input,
countries_input,
languages_input,
update_btn,
result_msg,
)
def create_tab():
"""Create the complete tab for this resource type."""
with gr.TabItem(f"π {RESOURCE_TITLE}", id=RESOURCE_TYPE):
with gr.Tabs():
table = create_all_tab()
inputs = create_contribute_tab()
edit_components = create_edit_tab()
return table, inputs, edit_components
|