C10X commited on
Commit
b41824a
·
verified ·
1 Parent(s): 56acf32

Update app.py

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