wikipedia_articles_es / bin /visualizer.py
Chiquitin
Upload src + bin with data visualizer (visualizer.py)
d12f2e3
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
# #
# This file was created by: Alberto Palomo Alonso #
# Universidad de Alcalá - Escuela Politécnica Superior #
# #
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
"""
Gradio-based explorer for inspecting a segmented Wikipedia dataset.
Main features:
- Load a Hugging Face dataset from disk.
- Compute global statistics for paragraphs, words, and articles.
- Precompute histograms for dataset-level distributions.
- Provide an interactive Gradio UI to browse individual samples and
visualize global statistics.
Expected dataset fields:
- id
- text (list of paragraphs/segments)
- paragraphs
- words
- articles
- title
"""
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
# IMPORT STATEMENTS #
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
import gradio as gr
import matplotlib.pyplot as plt
import numpy as np
from datasets import load_from_disk
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
# STATISTICS UTILITIES #
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
def compute_stats(arr: np.ndarray) -> dict:
"""
Compute basic descriptive statistics for a numeric array.
Args:
arr (np.ndarray):
Input array of numeric values.
Returns:
dict:
Dictionary containing mean, median, standard deviation (sample),
minimum, and maximum values.
"""
return {
'mean': float(np.mean(arr)),
'median': float(np.median(arr)),
'std': float(np.std(arr, ddof=1)),
'min': int(np.min(arr)),
'max': int(np.max(arr))
}
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
# PLOTTING UTILITIES #
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
def make_histogram(arr: np.ndarray, title: str):
"""
Create a histogram plot for a numeric array.
Args:
arr (np.ndarray):
Input array of numeric values.
title (str):
Title label for the histogram (used in title and x-axis).
Returns:
matplotlib.figure.Figure:
Matplotlib figure object containing the histogram.
"""
fig, ax = plt.subplots()
ax.hist(arr, bins=30)
ax.set_title(f"Distribution of {title}")
ax.set_xlabel(title)
ax.set_ylabel("Count")
fig.tight_layout()
return fig
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
# MAIN #
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
if __name__ == '__main__':
"""
Script entry point.
Loads a dataset from disk, computes global statistics and histograms,
and launches a Gradio UI to interactively explore dataset samples.
"""
# Load dataset
dataset_path = input('Enter dataset path: ')
ds = load_from_disk(dataset_path)
# Extract numeric arrays
paragraphs_arr = np.array(ds['paragraphs'], dtype=int)
words_arr = np.array(ds['words'], dtype=int)
articles_arr = np.array(ds['articles'], dtype=int)
# Compute global statistics
stats = {
'paragraphs': compute_stats(paragraphs_arr),
'words': compute_stats(words_arr),
'articles': compute_stats(articles_arr)
}
# Precompute histogram figures
par_plot_obj = make_histogram(paragraphs_arr, 'Paragraphs')
words_plot_obj = make_histogram(words_arr, 'Words')
articles_plot_obj = make_histogram(articles_arr, 'Articles')
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
# GRADIO CALLBACK #
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
def show(idx: int):
"""
Retrieve and format a single dataset sample for display.
Args:
idx (int):
Index of the document in the dataset.
Returns:
tuple[str, str]:
- Formatted sample text and metadata.
- Formatted global statistics and current sample information.
"""
sample = ds[int(idx)]
texto = "\n\n".join(
[f"{i}: {p}" for i, p in enumerate(sample["text"])]
)
sample_info = (
f"Doc ID: {sample['id']}"
f"\n\n{texto}"
)
stats_text = (
"Global Dataset Statistics:\n"
f"Paragraphs \t- mean: {stats['paragraphs']['mean']:.2f}, "
f"std: {stats['paragraphs']['std']:.2f}, "
f"min: {stats['paragraphs']['min']}, "
f"max: {stats['paragraphs']['max']}\n"
f"Words \t- mean: {stats['words']['mean']:.2f}, "
f"std: {stats['words']['std']:.2f}, "
f"min: {stats['words']['min']}, "
f"max: {stats['words']['max']}\n"
f"Articles \t- mean: {stats['articles']['mean']:.2f}, "
f"std: {stats['articles']['std']:.2f}, "
f"min: {stats['articles']['min']}, "
f"max: {stats['articles']['max']}\n"
f"\nCurrent Sample Information:\n"
f"\t- Doc ID: {sample['id']}\n"
f"\t- Paragraphs: {sample['paragraphs']}\n"
f"\t- Words: {sample['words']}\n"
f"\t- Articles: {sample['articles']}\n"
f"\t- Titles: {sample['title']}"
)
return sample_info, stats_text
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
# GRADIO UI #
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
with gr.Blocks(title="Wikipedia Extractor Explorer") as demo:
gr.Markdown("## Wikipedia Segmentation Explorer")
idx_slider = gr.Slider(
0, len(ds) - 1, step=1, label="Document Index"
)
with gr.Row():
with gr.Column(scale=1):
sample_output = gr.Textbox(
label="Sample Info", lines=20
)
stats_output = gr.Textbox(
label="Global Statistics", lines=6
)
with gr.Column(scale=1):
gr.Plot(
label="Paragraphs Histogram",
value=par_plot_obj
)
gr.Plot(
label="Words Histogram",
value=words_plot_obj
)
gr.Plot(
label="Articles Histogram",
value=articles_plot_obj
)
idx_slider.change(
fn=show,
inputs=idx_slider,
outputs=[sample_output, stats_output]
)
demo.launch()
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #
# END OF FILE #
# - x - x - x - x - x - x - x - x - x - x - x - x - x - x - #