Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,351 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import subprocess
|
3 |
-
import signal
|
4 |
-
os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
|
5 |
-
import gradio as gr
|
6 |
-
import tempfile
|
7 |
-
import torch
|
8 |
-
from datasets import load_dataset
|
9 |
-
from tqdm.auto import tqdm
|
10 |
-
import re
|
11 |
-
import numpy as np
|
12 |
-
import gc
|
13 |
-
import unicodedata
|
14 |
-
from multiprocessing import cpu_count
|
15 |
-
from transformers import LlamaTokenizerFast
|
16 |
-
import fasttext
|
17 |
-
from typing import Tuple, Dict, List, Generator
|
18 |
-
import json
|
19 |
-
import matplotlib.pyplot as plt
|
20 |
-
import seaborn as sns
|
21 |
-
from datetime import datetime
|
22 |
-
import warnings
|
23 |
-
from huggingface_hub import HfApi, create_repo, upload_file, snapshot_download, whoami
|
24 |
-
from gradio_huggingfacehub_search import HuggingfaceHubSearch
|
25 |
-
from pathlib import Path
|
26 |
-
from textwrap import dedent
|
27 |
-
from scipy import stats
|
28 |
-
from apscheduler.schedulers.background import BackgroundScheduler
|
29 |
-
|
30 |
-
warnings.filterwarnings('ignore')
|
31 |
-
|
32 |
-
# Environment variables
|
33 |
-
HF_TOKEN = os.environ.get("HF_TOKEN")
|
34 |
-
|
35 |
-
# Global variables for model caching
|
36 |
-
MODEL_CACHE_DIR = Path.home() / ".cache" / "ultra_fineweb"
|
37 |
-
MODEL_CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
38 |
-
MODEL_LOADED = False
|
39 |
-
fasttext_model = None
|
40 |
-
tokenizer = None
|
41 |
-
|
42 |
-
# CSS
|
43 |
-
css = """
|
44 |
-
.gradio-container {overflow-y: auto;}
|
45 |
-
.gr-button-primary {
|
46 |
-
background-color: #ff6b00 !important;
|
47 |
-
border-color: #ff6b00 !important;
|
48 |
-
}
|
49 |
-
.gr-button-primary:hover {
|
50 |
-
background-color: #ff8534 !important;
|
51 |
-
border-color: #ff8534 !important;
|
52 |
-
}
|
53 |
-
"""
|
54 |
-
|
55 |
-
# HTML templates
|
56 |
-
TITLE = """
|
57 |
-
<div style="text-align: center; margin-bottom: 30px;">
|
58 |
-
<h1 style="font-size: 36px; margin-bottom: 10px;">Create your own Dataset Quality Scores, blazingly fast ⚡!</h1>
|
59 |
-
<p style="font-size: 16px; color: #666;">The space takes a HF dataset as input, scores it and provides statistics and quality distribution.</p>
|
60 |
-
</div>
|
61 |
-
"""
|
62 |
-
|
63 |
-
DESCRIPTION_MD = """
|
64 |
-
### 📋 How it works:
|
65 |
-
1. Choose a dataset from Hugging Face Hub.
|
66 |
-
2. The Ultra-FineWeb classifier will score each text sample.
|
67 |
-
3. View quality distribution and download the scored dataset.
|
68 |
-
4. Optionally, upload the results to a new repository on your Hugging Face account.
|
69 |
-
|
70 |
-
**Note:** The first run will download the model (~347MB), which may take a moment.
|
71 |
-
"""
|
72 |
-
|
73 |
-
# --- Helper Functions ---
|
74 |
-
def escape(s: str) -> str:
|
75 |
-
s = str(s)
|
76 |
-
s = s.replace("&", "&")
|
77 |
-
s = s.replace("<", "<")
|
78 |
-
s = s.replace(">", ">")
|
79 |
-
s = s.replace('"', """)
|
80 |
-
s = s.replace("\n", "<br/>")
|
81 |
-
return s
|
82 |
-
|
83 |
-
def fasttext_preprocess(content: str, tokenizer) -> str:
|
84 |
-
if not isinstance(content, str): return ""
|
85 |
-
content = re.sub(r'\n{3,}', '\n\n', content).lower()
|
86 |
-
content = ''.join(c for c in unicodedata.normalize('NFKD', content) if unicodedata.category(c) != 'Mn')
|
87 |
-
token_ids = tokenizer.encode(content, add_special_tokens=False)
|
88 |
-
content = ' '.join([tokenizer.decode([token_id]) for token_id in token_ids])
|
89 |
-
content = re.sub(r'\n', ' n ', content).replace('\r', '').replace('\t', ' ')
|
90 |
-
return re.sub(r' +', ' ', content).strip()
|
91 |
-
|
92 |
-
def fasttext_infer(norm_content: str, model) -> Tuple[str, float]:
|
93 |
-
try:
|
94 |
-
pred_label_arr, pred_prob_arr = model.predict(norm_content)
|
95 |
-
pred_label = pred_label_arr[0]
|
96 |
-
score = float(pred_prob_arr[0])
|
97 |
-
|
98 |
-
if pred_label == "__label__neg":
|
99 |
-
score = 1 - score
|
100 |
-
|
101 |
-
return pred_label, max(0.0, min(1.0, score))
|
102 |
-
except Exception as e:
|
103 |
-
print(f"Error in fasttext_infer: {e}")
|
104 |
-
return "__label__neg", 0.0
|
105 |
-
|
106 |
-
# ==============================================================================
|
107 |
-
# --- HATAYI GİDEREN KESİN VE NİHAİ DÜZELTME BURADA ---
|
108 |
-
# load_models artık sadece True veya False döndürerek kontrolü garantiliyor.
|
109 |
-
# ==============================================================================
|
110 |
-
def load_models():
|
111 |
-
"""Load models into global variables, returning True on success, False on failure."""
|
112 |
-
global MODEL_LOADED, fasttext_model, tokenizer
|
113 |
-
if MODEL_LOADED:
|
114 |
-
return True
|
115 |
-
|
116 |
-
try:
|
117 |
-
model_dir = MODEL_CACHE_DIR / "Ultra-FineWeb-classifier"
|
118 |
-
if not model_dir.exists():
|
119 |
-
print("Downloading model files...")
|
120 |
-
snapshot_download(repo_id="openbmb/Ultra-FineWeb-classifier", local_dir=str(model_dir), local_dir_use_symlinks=False)
|
121 |
-
|
122 |
-
tokenizer_path = model_dir / "local_tokenizer"
|
123 |
-
fasttext_path = model_dir / "classifiers" / "ultra_fineweb_en.bin"
|
124 |
-
|
125 |
-
print("Loading tokenizer and model...")
|
126 |
-
tokenizer = LlamaTokenizerFast.from_pretrained(str(tokenizer_path))
|
127 |
-
fasttext_model = fasttext.load_model(str(fasttext_path))
|
128 |
-
|
129 |
-
MODEL_LOADED = True
|
130 |
-
print("Models loaded successfully.")
|
131 |
-
return True
|
132 |
-
except Exception as e:
|
133 |
-
print(f"Error loading models: {e}")
|
134 |
-
gr.Warning(f"Failed to load models: {e}")
|
135 |
-
return False
|
136 |
-
|
137 |
-
def create_quality_plot(scores: List[float], dataset_name: str) -> str:
|
138 |
-
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmpfile:
|
139 |
-
output_path = tmpfile.name
|
140 |
-
plt.figure(figsize=(10, 6))
|
141 |
-
sns.histplot(scores, bins=50, kde=True, color='#6B7FD7', edgecolor='black')
|
142 |
-
mean_score, median_score = np.mean(scores), np.median(scores)
|
143 |
-
plt.axvline(mean_score, color='green', linestyle='--', linewidth=2, label=f'Mean: {mean_score:.3f}')
|
144 |
-
plt.axvline(median_score, color='orange', linestyle=':', linewidth=2, label=f'Median: {median_score:.3f}')
|
145 |
-
plt.xlabel('Quality Score'); plt.ylabel('Density')
|
146 |
-
plt.title(f'Quality Score Distribution - {dataset_name}', fontweight='bold')
|
147 |
-
plt.legend(); plt.grid(axis='y', alpha=0.3); plt.xlim(0, 1)
|
148 |
-
plt.tight_layout(); plt.savefig(output_path, dpi=150)
|
149 |
-
plt.close()
|
150 |
-
return output_path
|
151 |
-
|
152 |
-
def process_dataset(
|
153 |
-
model_id: str,
|
154 |
-
dataset_split: str,
|
155 |
-
text_column: str,
|
156 |
-
sample_size: int,
|
157 |
-
batch_size: int,
|
158 |
-
progress=gr.Progress(track_tqdm=True)
|
159 |
-
) -> Generator:
|
160 |
-
log_text = ""
|
161 |
-
def update_log(msg):
|
162 |
-
nonlocal log_text
|
163 |
-
timestamp = datetime.now().strftime('%H:%M:%S')
|
164 |
-
log_text += f"[{timestamp}] {msg}\n"
|
165 |
-
return (log_text, None, None, None, None, gr.update(visible=False), gr.update(visible=False))
|
166 |
-
|
167 |
-
try:
|
168 |
-
yield update_log("Starting process...")
|
169 |
-
yield update_log("Loading scoring models...")
|
170 |
-
# Düzeltilmiş kontrol mekanizması
|
171 |
-
if not load_models():
|
172 |
-
raise gr.Error("Failed to load scoring models. Please check logs.")
|
173 |
-
yield update_log("Models loaded successfully.")
|
174 |
-
|
175 |
-
yield update_log(f"Loading dataset '{model_id}' split '{dataset_split}'...")
|
176 |
-
dataset = load_dataset(model_id, split=dataset_split, streaming=False)
|
177 |
-
yield update_log("Dataset loaded.")
|
178 |
-
|
179 |
-
if text_column not in dataset.column_names:
|
180 |
-
raise gr.Error(f"Column '{text_column}' not found. Available: {', '.join(dataset.column_names)}")
|
181 |
-
|
182 |
-
actual_samples = min(sample_size, len(dataset))
|
183 |
-
dataset = dataset.select(range(actual_samples))
|
184 |
-
|
185 |
-
yield update_log(f"Starting to score {actual_samples:,} samples...")
|
186 |
-
scores, scored_data = [], []
|
187 |
-
for i in tqdm(range(0, actual_samples, batch_size), desc="Scoring batches"):
|
188 |
-
batch = dataset[i:min(i + batch_size, actual_samples)]
|
189 |
-
for text in batch[text_column]:
|
190 |
-
norm_content = fasttext_preprocess(text, tokenizer)
|
191 |
-
label, score = fasttext_infer(norm_content, fasttext_model) if norm_content else ("__label__neg", 0.0)
|
192 |
-
scores.append(score)
|
193 |
-
scored_data.append({'text': text, 'quality_score': score, 'predicted_label': label})
|
194 |
-
|
195 |
-
yield update_log("Scoring complete. Generating results and plot...")
|
196 |
-
stats_dict = {'dataset_id': model_id, 'processed_samples': actual_samples, 'statistics': {'mean': float(np.mean(scores)), 'median': float(np.median(scores))}}
|
197 |
-
|
198 |
-
plot_file = create_quality_plot(scores, model_id.split('/')[-1])
|
199 |
-
|
200 |
-
with tempfile.NamedTemporaryFile('w', suffix=".jsonl", delete=False, encoding='utf-8') as f:
|
201 |
-
output_file_path = f.name
|
202 |
-
for item in scored_data: f.write(json.dumps(item, ensure_ascii=False) + '\n')
|
203 |
-
|
204 |
-
with tempfile.NamedTemporaryFile('w', suffix=".json", delete=False, encoding='utf-8') as f:
|
205 |
-
stats_file_path = f.name
|
206 |
-
json.dump(stats_dict, f, indent=2)
|
207 |
-
|
208 |
-
summary_lines = [
|
209 |
-
"#### ✅ Scoring Completed!",
|
210 |
-
f"- **Dataset:** `{model_id}`",
|
211 |
-
f"- **Processed Samples:** `{actual_samples:,}`",
|
212 |
-
f"- **Mean Score:** `{stats_dict['statistics']['mean']:.3f}`",
|
213 |
-
f"- **Median Score:** `{stats_dict['statistics']['median']:.3f}`"
|
214 |
-
]
|
215 |
-
summary_md = "\n".join(summary_lines)
|
216 |
-
|
217 |
-
yield update_log("Process finished successfully!")
|
218 |
-
|
219 |
-
yield (log_text, summary_md, output_file_path, stats_file_path, plot_file, gr.update(visible=True), gr.update(visible=True))
|
220 |
-
|
221 |
-
except Exception as e:
|
222 |
-
error_log = update_log(f"ERROR: {e}")[0]
|
223 |
-
error_summary_md = f"### ❌ Error\n```\n{escape(str(e))}\n```"
|
224 |
-
yield (error_log, error_summary_md, None, None, None, gr.update(visible=True), gr.update(visible=False))
|
225 |
-
|
226 |
-
def upload_to_hub(
|
227 |
-
scored_file: str, stats_file: str, plot_file: str, new_dataset_id: str,
|
228 |
-
private: bool, hf_token: str, progress=gr.Progress(track_tqdm=True)
|
229 |
-
) -> str:
|
230 |
-
if not hf_token: return '❌ <span style="color: red;">Please provide your Hugging Face token.</span>'
|
231 |
-
if not all([scored_file, new_dataset_id]): return '❌ <span style="color: red;">Missing scored file or new dataset ID.</span>'
|
232 |
-
|
233 |
-
try:
|
234 |
-
progress(0.1, desc="Connecting to Hub...")
|
235 |
-
api = HfApi(token=hf_token)
|
236 |
-
username = whoami(token=hf_token)["name"]
|
237 |
-
repo_id = f"{username}/{new_dataset_id}" if "/" not in new_dataset_id else new_dataset_id
|
238 |
-
|
239 |
-
progress(0.2, desc=f"Creating repo: {repo_id}")
|
240 |
-
repo_url = create_repo(repo_id=repo_id, repo_type="dataset", exist_ok=True, private=private, token=hf_token).repo_url
|
241 |
-
|
242 |
-
progress(0.4, desc="Uploading files...")
|
243 |
-
upload_file(path_or_fileobj=scored_file, path_in_repo="data/scored_dataset.jsonl", repo_id=repo_id, repo_type="dataset", token=hf_token)
|
244 |
-
if stats_file and os.path.exists(stats_file):
|
245 |
-
upload_file(path_or_fileobj=stats_file, path_in_repo="statistics.json", repo_id=repo_id, repo_type="dataset", token=hf_token)
|
246 |
-
if plot_file and os.path.exists(plot_file):
|
247 |
-
upload_file(path_or_fileobj=plot_file, path_in_repo="quality_distribution.png", repo_id=repo_id, repo_type="dataset", token=hf_token)
|
248 |
-
|
249 |
-
readme_lines = [
|
250 |
-
"---",
|
251 |
-
"license: apache-2.0",
|
252 |
-
"---",
|
253 |
-
f"# Quality-Scored Dataset: {repo_id.split('/')[-1]}",
|
254 |
-
"This dataset was scored for quality using the [Dataset Quality Scorer Space](https://huggingface.co/spaces/ggml-org/dataset-quality-scorer).",
|
255 |
-
"",
|
256 |
-
"## Usage",
|
257 |
-
"```python",
|
258 |
-
"from datasets import load_dataset",
|
259 |
-
f'dataset = load_dataset("{repo_id}", split="train")',
|
260 |
-
"```"
|
261 |
-
]
|
262 |
-
readme_content = "\n".join(readme_lines)
|
263 |
-
|
264 |
-
upload_file(path_or_fileobj=readme_content.encode(), path_in_repo="README.md", repo_id=repo_id, repo_type="dataset", token=hf_token)
|
265 |
-
progress(1.0, "Done!")
|
266 |
-
return f'✅ <span style="color: green;">Successfully uploaded to <a href="{repo_url}" target="_blank">{repo_id}</a></span>'
|
267 |
-
|
268 |
-
except Exception as e:
|
269 |
-
return f'❌ <span style="color: red;">Upload failed: {escape(str(e))}</span>'
|
270 |
-
|
271 |
-
|
272 |
-
def create_demo():
|
273 |
-
with gr.Blocks(css=css, title="Dataset Quality Scorer") as demo:
|
274 |
-
gr.HTML(TITLE)
|
275 |
-
gr.Markdown(DESCRIPTION_MD)
|
276 |
-
|
277 |
-
with gr.Row():
|
278 |
-
with gr.Column(scale=3):
|
279 |
-
gr.Markdown("### 1. Configure Dataset")
|
280 |
-
dataset_search = HuggingfaceHubSearch(
|
281 |
-
label="Hugging Face Dataset ID",
|
282 |
-
search_type="dataset",
|
283 |
-
value="roneneldan/TinyStories"
|
284 |
-
)
|
285 |
-
text_column = gr.Textbox(label="Text Column Name", value="text")
|
286 |
-
with gr.Column(scale=2):
|
287 |
-
gr.Markdown("### 2. Configure Scoring")
|
288 |
-
dataset_split = gr.Dropdown(["train", "validation", "test"], label="Split", value="train")
|
289 |
-
with gr.Row():
|
290 |
-
sample_size = gr.Number(label="Sample Size", value=1000, minimum=100, step=100)
|
291 |
-
batch_size = gr.Number(label="Batch Size", value=32, minimum=1, step=1)
|
292 |
-
|
293 |
-
live_log = gr.Textbox(label="Live Log", interactive=False, lines=8, max_lines=20)
|
294 |
-
|
295 |
-
with gr.Row():
|
296 |
-
clear_btn = gr.Button("Clear", variant="secondary")
|
297 |
-
process_btn = gr.Button("🚀 Start Scoring", variant="primary", size="lg")
|
298 |
-
|
299 |
-
with gr.Group(visible=False) as results_group:
|
300 |
-
gr.Markdown("--- \n ### 3. Review Results")
|
301 |
-
with gr.Row():
|
302 |
-
with gr.Column(scale=1):
|
303 |
-
summary_output = gr.Markdown(label="Summary")
|
304 |
-
scored_file_output = gr.File(label="📄 Download Scored Dataset (.jsonl)", type="filepath")
|
305 |
-
stats_file_output = gr.File(label="📊 Download Statistics (.json)", type="filepath")
|
306 |
-
with gr.Column(scale=1):
|
307 |
-
plot_output = gr.Image(label="Quality Distribution", show_label=True)
|
308 |
-
|
309 |
-
with gr.Group(visible=False) as upload_group:
|
310 |
-
gr.Markdown("--- \n ### 4. (Optional) Upload to Hugging Face Hub")
|
311 |
-
hf_token_input = gr.Textbox(label="Hugging Face Token", type="password", placeholder="hf_...", value=HF_TOKEN or "")
|
312 |
-
new_dataset_id = gr.Textbox(label="New Dataset Name", placeholder="my-scored-dataset")
|
313 |
-
private_checkbox = gr.Checkbox(label="Make dataset private", value=False)
|
314 |
-
upload_btn = gr.Button("📤 Upload to Hub", variant="primary")
|
315 |
-
upload_status = gr.HTML()
|
316 |
-
|
317 |
-
def clear_form():
|
318 |
-
return "roneneldan/TinyStories", "train", "text", 1000, 32, "", None, None, None, None, gr.update(visible=False), gr.update(visible=False), ""
|
319 |
-
|
320 |
-
outputs_list = [
|
321 |
-
live_log, summary_output, scored_file_output, stats_file_output, plot_output,
|
322 |
-
results_group, upload_group
|
323 |
-
]
|
324 |
-
|
325 |
-
process_btn.click(
|
326 |
-
fn=process_dataset,
|
327 |
-
inputs=[dataset_search, dataset_split, text_column, sample_size, batch_size],
|
328 |
-
outputs=outputs_list
|
329 |
-
)
|
330 |
-
|
331 |
-
clear_btn.click(
|
332 |
-
fn=clear_form,
|
333 |
-
outputs=[
|
334 |
-
dataset_search, dataset_split, text_column, sample_size, batch_size,
|
335 |
-
live_log, summary_output, scored_file_output, stats_file_output, plot_output,
|
336 |
-
results_group, upload_group, upload_status
|
337 |
-
]
|
338 |
-
)
|
339 |
-
|
340 |
-
upload_btn.click(
|
341 |
-
fn=upload_to_hub,
|
342 |
-
inputs=[scored_file_output, stats_file_output, plot_output, new_dataset_id, private_checkbox, hf_token_input],
|
343 |
-
outputs=[upload_status]
|
344 |
-
)
|
345 |
-
return demo
|
346 |
-
|
347 |
-
# --- App Execution ---
|
348 |
-
demo = create_demo()
|
349 |
-
|
350 |
-
if __name__ == "__main__":
|
351 |
-
demo.queue().launch(debug=False, show_api=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|