File size: 6,435 Bytes
0430da2 4a4435c 0430da2 4a4435c 0430da2 4a4435c 0430da2 4a4435c 0430da2 4a4435c 0430da2 4a4435c 0430da2 4a4435c 0430da2 4a4435c 1c51cb8 4a4435c 0430da2 4a4435c 1c51cb8 4a4435c 1c51cb8 4a4435c 1c51cb8 0430da2 4a4435c 0430da2 4a4435c 0430da2 4a4435c 0430da2 4a4435c 0430da2 4a4435c 0430da2 4a4435c 0430da2 4a4435c 0430da2 4a4435c 0430da2 4a4435c 0430da2 |
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 |
import gradio as gr
import requests
import json
import re
from io import BytesIO
import matplotlib.pyplot as plt
from train_tokenizer import train_tokenizer
from datasets import load_dataset
from tokenizers import Tokenizer
import tempfile
import os
def fetch_splits(dataset_name):
try:
response = requests.get(
f"https://datasets-server.huggingface.co/splits?dataset={dataset_name}",
timeout=10
)
response.raise_for_status()
data = response.json()
splits_info = {}
for split in data['splits']:
config = split['config']
split_name = split['split']
if config not in splits_info:
splits_info[config] = []
splits_info[config].append(split_name)
return {
"splits": splits_info,
"viewer_template": f"https://huggingface.co/datasets/{dataset_name}/embed/viewer/{{config}}/{{split}}"
}
except Exception as e:
raise gr.Error(f"Σφάλμα κατάττην ανάκτηση splits: {str(e)}")
def update_components(dataset_name):
if not dataset_name:
return [gr.Dropdown.update(choices=[], value=None), gr.Dropdown.update(choices=[]), gr.HTML.update(value="")]
try:
splits_data = fetch_splits(dataset_name)
config_choices = list(splits_data['splits'].keys())
# Δημιουργία iframe preview για το πρώτο config
first_config = config_choices[0] if config_choices else None
iframe_html = f"""
<iframe
src="{splits_data['viewer_template'].format(config=first_config, split='train')}"
frameborder="0"
width="100%"
height="560px"
></iframe>
""" if first_config else "Δεν βρέθηκαν διαθέσιμα δεδομένα"
return [
gr.Dropdown.update(choices=config_choices, value=first_config),
gr.Dropdown.update(choices=splits_data['splits'].get(first_config, [])),
gr.HTML.update(value=iframe_html)
]
except Exception as e:
raise gr.Error(f"Σφάλμα: {str(e)}")
def update_split_choices(dataset_name, config):
if not dataset_name or not config:
return gr.Dropdown.update(choices=[])
try:
splits_data = fetch_splits(dataset_name)
return gr.Dropdown.update(choices=splits_data['splits'].get(config, []))
except:
return gr.Dropdown.update(choices=[])
def create_iterator(dataset_name, config, split):
try:
dataset = load_dataset(
dataset_name,
name=config,
split=split,
streaming=True
)
for example in dataset:
yield example.get('text', '')
except Exception as e:
raise gr.Error(f"Σφάλμα φόρτωσης dataset: {str(e)}")
def train_and_test(dataset_name, config, split, vocab_size, min_freq, test_text):
# Εκπαίδευση και validation logic
try:
iterator = create_iterator(dataset_name, config, split)
with gr.Progress() as progress:
progress(0.2, desc="Δημιουργία tokenizer...")
tokenizer = train_tokenizer(iterator, vocab_size, min_freq)
# Αποθήκευση και φόρτωση tokenizer
with tempfile.NamedTemporaryFile(delete=False, suffix=".json") as f:
tokenizer.save(f.name)
trained_tokenizer = Tokenizer.from_file(f.name)
os.unlink(f.name)
# Validation
encoded = trained_tokenizer.encode(test_text)
decoded = trained_tokenizer.decode(encoded.ids)
# Δημιουργία γραφήματος
token_lengths = [len(t) for t in encoded.tokens]
fig = plt.figure()
plt.hist(token_lengths, bins=20)
plt.xlabel('Μήκος Token')
plt.ylabel('Συχνότητα')
img_buffer = BytesIO()
plt.savefig(img_buffer, format='png')
plt.close()
return {
"Πρωτότυπο Κείμενο": test_text,
"Αποκωδικοποιημένο": decoded,
"Αριθμός Tokens": len(encoded.tokens),
"Αγνώστων Tokens": sum(1 for t in encoded.tokens if t == "<unk>")
}, img_buffer.getvalue()
except Exception as e:
raise gr.Error(f"Σφάλμα εκπαίδευσης: {str(e)}")
# Gradio Interface
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("## Wikipedia Tokenizer Trainer")
with gr.Row():
with gr.Column():
dataset_name = gr.Textbox(
label="Dataset Name",
value="wikimedia/wikipedia",
placeholder="π.χ. 'wikimedia/wikipedia'"
)
config = gr.Dropdown(
label="Config",
choices=[],
interactive=True
)
split = gr.Dropdown(
label="Split",
choices=[],
value="train"
)
vocab_size = gr.Slider(20000, 100000, value=50000, label="Μέγεθος Λεξιλογίου")
min_freq = gr.Slider(1, 100, value=3, label="Ελάχιστη Συχνότητα")
test_text = gr.Textbox(
value='Η Ακρόπολη είναι σύμβολο της αρχαίας ελληνικής πολιτισμικής κληρονομιάς.',
label="Test Text"
)
train_btn = gr.Button("Εκπαίδευση", variant="primary")
with gr.Column():
preview = gr.HTML(label="Dataset Preview")
results_json = gr.JSON(label="Αποτελέσματα")
results_plot = gr.Image(label="Κατανομή Μηκών Tokens")
# Event handlers
dataset_name.change(
fn=update_components,
inputs=dataset_name,
outputs=[config, split, preview]
)
config.change(
fn=update_split_choices,
inputs=[dataset_name, config],
outputs=split
)
train_btn.click(
fn=train_and_test,
inputs=[dataset_name, config, split, vocab_size, min_freq, test_text],
outputs=[results_json, results_plot]
)
if __name__ == "__main__":
demo.launch() |