C10X commited on
Commit
7249053
Β·
verified Β·
1 Parent(s): 28558e6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +331 -0
app.py CHANGED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # ==============================================================================
75
+ # --- HATAYI GİDEREN DÜZELTME BURADA ---
76
+ # `escape` fonksiyonu doğru ve orijinal haline geri getirildi.
77
+ # ==============================================================================
78
+ def escape(s: str) -> str:
79
+ """Escape special characters for safe HTML display."""
80
+ s = str(s)
81
+ s = s.replace("&", "&")
82
+ s = s.replace("<", "<")
83
+ s = s.replace(">", ">")
84
+ s = s.replace('"', """)
85
+ s = s.replace("\n", "<br/>")
86
+ return s
87
+
88
+ def fasttext_preprocess(content: str, tokenizer) -> str:
89
+ if not isinstance(content, str): return ""
90
+ content = re.sub(r'\n{3,}', '\n\n', content).lower()
91
+ content = ''.join(c for c in unicodedata.normalize('NFKD', content) if unicodedata.category(c) != 'Mn')
92
+ token_ids = tokenizer.encode(content, add_special_tokens=False)
93
+ content = ' '.join([tokenizer.decode([token_id]) for token_id in token_ids])
94
+ content = re.sub(r'\n', ' n ', content).replace('\r', '').replace('\t', ' ')
95
+ return re.sub(r' +', ' ', content).strip()
96
+
97
+ def fasttext_infer(norm_content: str, model) -> Tuple[str, float]:
98
+ pred_label, pred_prob = model.predict(norm_content)
99
+ pred_label = pred_label[0]
100
+ _score = min(pred_prob.tolist()[0], 1.0)
101
+ if pred_label == "__label__neg":
102
+ _score = 1 - _score
103
+ return pred_label, _score
104
+
105
+ def load_models():
106
+ global MODEL_LOADED, fasttext_model, tokenizer
107
+ if MODEL_LOADED: return True
108
+ try:
109
+ model_dir = MODEL_CACHE_DIR / "Ultra-FineWeb-classifier"
110
+ if not model_dir.exists():
111
+ snapshot_download(repo_id="openbmb/Ultra-FineWeb-classifier", local_dir=str(model_dir), local_dir_use_symlinks=False)
112
+ fasttext_path = model_dir / "classifiers" / "ultra_fineweb_en.bin"
113
+ tokenizer_path = model_dir / "local_tokenizer"
114
+ fasttext_model = fasttext.load_model(str(fasttext_path))
115
+ tokenizer = LlamaTokenizerFast.from_pretrained(str(tokenizer_path) if tokenizer_path.exists() else "meta-llama/Llama-2-7b-hf")
116
+ MODEL_LOADED = True
117
+ return True
118
+ except Exception as e:
119
+ gr.Warning(f"Failed to load models: {e}")
120
+ return False
121
+
122
+ def create_quality_plot(scores: List[float], dataset_name: str) -> str:
123
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmpfile:
124
+ output_path = tmpfile.name
125
+ plt.figure(figsize=(10, 6))
126
+ sns.histplot(scores, bins=50, kde=True, color='#6B7FD7', edgecolor='black')
127
+ mean_score, median_score = np.mean(scores), np.median(scores)
128
+ plt.axvline(mean_score, color='green', linestyle='--', linewidth=2, label=f'Mean: {mean_score:.3f}')
129
+ plt.axvline(median_score, color='orange', linestyle=':', linewidth=2, label=f'Median: {median_score:.3f}')
130
+ plt.xlabel('Quality Score'); plt.ylabel('Density')
131
+ plt.title(f'Quality Score Distribution - {dataset_name}', fontweight='bold')
132
+ plt.legend(); plt.grid(axis='y', alpha=0.3); plt.xlim(0, 1)
133
+ plt.tight_layout(); plt.savefig(output_path, dpi=150)
134
+ plt.close()
135
+ return output_path
136
+
137
+ def process_dataset(
138
+ model_id: str,
139
+ dataset_split: str,
140
+ text_column: str,
141
+ sample_size: int,
142
+ batch_size: int,
143
+ progress=gr.Progress(track_tqdm=True)
144
+ ) -> Generator:
145
+ log_text = ""
146
+ def update_log(msg):
147
+ nonlocal log_text
148
+ timestamp = datetime.now().strftime('%H:%M:%S')
149
+ log_text += f"[{timestamp}] {msg}\n"
150
+ return (log_text, None, None, None, None, gr.update(visible=False), gr.update(visible=False))
151
+
152
+ try:
153
+ yield update_log("Starting process...")
154
+ yield update_log("Loading scoring models...")
155
+ if not load_models():
156
+ raise gr.Error("Failed to load scoring models. Please check logs.")
157
+ yield update_log("Models loaded successfully.")
158
+
159
+ yield update_log(f"Loading dataset '{model_id}' split '{dataset_split}'...")
160
+ dataset = load_dataset(model_id, split=dataset_split, streaming=False)
161
+ yield update_log("Dataset loaded.")
162
+
163
+ if text_column not in dataset.column_names:
164
+ raise gr.Error(f"Column '{text_column}' not found. Available: {', '.join(dataset.column_names)}")
165
+
166
+ actual_samples = min(sample_size, len(dataset))
167
+ dataset = dataset.select(range(actual_samples))
168
+
169
+ yield update_log(f"Starting to score {actual_samples:,} samples...")
170
+ scores, scored_data = [], []
171
+ for i in tqdm(range(0, actual_samples, batch_size), desc="Scoring batches"):
172
+ batch = dataset[i:min(i + batch_size, actual_samples)]
173
+ for text in batch[text_column]:
174
+ norm_content = fasttext_preprocess(text, tokenizer)
175
+ label, score = fasttext_infer(norm_content, fasttext_model) if norm_content else ("__label__neg", 0.0)
176
+ scores.append(score)
177
+ scored_data.append({'text': text, 'quality_score': score, 'predicted_label': label})
178
+
179
+ yield update_log("Scoring complete. Generating results and plot...")
180
+ stats_dict = {'dataset_id': model_id, 'processed_samples': actual_samples, 'statistics': {'mean': float(np.mean(scores)), 'median': float(np.median(scores))}}
181
+
182
+ plot_file = create_quality_plot(scores, model_id.split('/')[-1])
183
+
184
+ with tempfile.NamedTemporaryFile('w', suffix=".jsonl", delete=False, encoding='utf-8') as f:
185
+ output_file_path = f.name
186
+ for item in scored_data: f.write(json.dumps(item, ensure_ascii=False) + '\n')
187
+
188
+ with tempfile.NamedTemporaryFile('w', suffix=".json", delete=False, encoding='utf-8') as f:
189
+ stats_file_path = f.name
190
+ json.dump(stats_dict, f, indent=2)
191
+
192
+ summary_lines = [
193
+ "#### βœ… Scoring Completed!",
194
+ f"- **Dataset:** `{model_id}`",
195
+ f"- **Processed Samples:** `{actual_samples:,}`",
196
+ f"- **Mean Score:** `{stats_dict['statistics']['mean']:.3f}`",
197
+ f"- **Median Score:** `{stats_dict['statistics']['median']:.3f}`"
198
+ ]
199
+ summary_md = "\n".join(summary_lines)
200
+
201
+ yield update_log("Process finished successfully!")
202
+
203
+ yield (log_text, summary_md, output_file_path, stats_file_path, plot_file, gr.update(visible=True), gr.update(visible=True))
204
+
205
+ except Exception as e:
206
+ error_log = update_log(f"ERROR: {e}")[0]
207
+ error_summary_md = f"### ❌ Error\n```\n{escape(str(e))}\n```"
208
+ yield (error_log, error_summary_md, None, None, None, gr.update(visible=True), gr.update(visible=False))
209
+
210
+ def upload_to_hub(
211
+ scored_file: str, stats_file: str, plot_file: str, new_dataset_id: str,
212
+ private: bool, hf_token: str, progress=gr.Progress(track_tqdm=True)
213
+ ) -> str:
214
+ if not hf_token: return '❌ <span style="color: red;">Please provide your Hugging Face token.</span>'
215
+ if not all([scored_file, new_dataset_id]): return '❌ <span style="color: red;">Missing scored file or new dataset ID.</span>'
216
+
217
+ try:
218
+ progress(0.1, desc="Connecting to Hub...")
219
+ api = HfApi(token=hf_token)
220
+ username = whoami(token=hf_token)["name"]
221
+ repo_id = f"{username}/{new_dataset_id}" if "/" not in new_dataset_id else new_dataset_id
222
+
223
+ progress(0.2, desc=f"Creating repo: {repo_id}")
224
+ repo_url = create_repo(repo_id=repo_id, repo_type="dataset", exist_ok=True, private=private, token=hf_token).repo_url
225
+
226
+ progress(0.4, desc="Uploading files...")
227
+ upload_file(path_or_fileobj=scored_file, path_in_repo="data/scored_dataset.jsonl", repo_id=repo_id, repo_type="dataset", token=hf_token)
228
+ if stats_file and os.path.exists(stats_file):
229
+ upload_file(path_or_fileobj=stats_file, path_in_repo="statistics.json", repo_id=repo_id, repo_type="dataset", token=hf_token)
230
+ if plot_file and os.path.exists(plot_file):
231
+ upload_file(path_or_fileobj=plot_file, path_in_repo="quality_distribution.png", repo_id=repo_id, repo_type="dataset", token=hf_token)
232
+
233
+ readme_lines = [
234
+ "---",
235
+ "license: apache-2.0",
236
+ "---",
237
+ f"# Quality-Scored Dataset: {repo_id.split('/')[-1]}",
238
+ "This dataset was scored for quality using the [Dataset Quality Scorer Space](https://huggingface.co/spaces/ggml-org/dataset-quality-scorer).",
239
+ "![Quality Distribution](quality_distribution.png)",
240
+ "## Usage",
241
+ "```python",
242
+ "from datasets import load_dataset",
243
+ f'dataset = load_dataset("{repo_id}", split="train")',
244
+ "```"
245
+ ]
246
+ readme_content = "\n".join(readme_lines)
247
+
248
+ upload_file(path_or_fileobj=readme_content.encode(), path_in_repo="README.md", repo_id=repo_id, repo_type="dataset", token=hf_token)
249
+ progress(1.0, "Done!")
250
+ return f'βœ… <span style="color: green;">Successfully uploaded to <a href="{repo_url}" target="_blank">{repo_id}</a></span>'
251
+
252
+ except Exception as e:
253
+ return f'❌ <span style="color: red;">Upload failed: {escape(str(e))}</span>'
254
+
255
+
256
+ def create_demo():
257
+ with gr.Blocks(css=css, title="Dataset Quality Scorer") as demo:
258
+ gr.HTML(TITLE)
259
+ gr.Markdown(DESCRIPTION_MD)
260
+
261
+ with gr.Row():
262
+ with gr.Column(scale=3):
263
+ gr.Markdown("### 1. Configure Dataset")
264
+ dataset_search = HuggingfaceHubSearch(label="Hub Dataset ID", search_type="dataset", value="roneneldan/TinyStories")
265
+ text_column = gr.Textbox(label="Text Column Name", value="text")
266
+ with gr.Column(scale=2):
267
+ gr.Markdown("### 2. Configure Scoring")
268
+ dataset_split = gr.Dropdown(["train", "validation", "test"], label="Split", value="train")
269
+ with gr.Row():
270
+ sample_size = gr.Number(label="Sample Size", value=1000, minimum=100, step=100)
271
+ batch_size = gr.Number(label="Batch Size", value=32, minimum=1, step=1)
272
+
273
+ live_log = gr.Textbox(label="Live Log", interactive=False, lines=8, max_lines=20)
274
+
275
+ with gr.Row():
276
+ clear_btn = gr.Button("Clear", variant="secondary")
277
+ process_btn = gr.Button("πŸš€ Start Scoring", variant="primary", size="lg")
278
+
279
+ with gr.Group(visible=False) as results_group:
280
+ gr.Markdown("--- \n ### 3. Review Results")
281
+ with gr.Row():
282
+ with gr.Column(scale=1):
283
+ summary_output = gr.Markdown(label="Summary")
284
+ scored_file_output = gr.File(label="πŸ“„ Download Scored Dataset (.jsonl)", type="filepath")
285
+ stats_file_output = gr.File(label="πŸ“Š Download Statistics (.json)", type="filepath")
286
+ with gr.Column(scale=1):
287
+ plot_output = gr.Image(label="Quality Distribution", show_label=True)
288
+
289
+ with gr.Group(visible=False) as upload_group:
290
+ gr.Markdown("--- \n ### 4. (Optional) Upload to Hugging Face Hub")
291
+ hf_token_input = gr.Textbox(label="Hugging Face Token", type="password", placeholder="hf_...", value=HF_TOKEN or "")
292
+ new_dataset_id = gr.Textbox(label="New Dataset Name", placeholder="my-scored-dataset")
293
+ private_checkbox = gr.Checkbox(label="Make dataset private", value=False)
294
+ upload_btn = gr.Button("πŸ“€ Upload to Hub", variant="primary")
295
+ upload_status = gr.HTML()
296
+
297
+ def clear_form():
298
+ return "roneneldan/TinyStories", "train", "text", 1000, 32, "", None, None, None, None, gr.update(visible=False), gr.update(visible=False), ""
299
+
300
+ outputs_list = [
301
+ live_log, summary_output, scored_file_output, stats_file_output, plot_output,
302
+ results_group, upload_group
303
+ ]
304
+
305
+ process_btn.click(
306
+ fn=process_dataset,
307
+ inputs=[dataset_search, dataset_split, text_column, sample_size, batch_size],
308
+ outputs=outputs_list
309
+ )
310
+
311
+ clear_btn.click(
312
+ fn=clear_form,
313
+ outputs=[
314
+ dataset_search, dataset_split, text_column, sample_size, batch_size,
315
+ live_log, summary_output, scored_file_output, stats_file_output, plot_output,
316
+ results_group, upload_group, upload_status
317
+ ]
318
+ )
319
+
320
+ upload_btn.click(
321
+ fn=upload_to_hub,
322
+ inputs=[scored_file_output, stats_file_output, plot_output, new_dataset_id, private_checkbox, hf_token_input],
323
+ outputs=[upload_status]
324
+ )
325
+ return demo
326
+
327
+ # --- App Execution ---
328
+ demo = create_demo()
329
+
330
+ if __name__ == "__main__":
331
+ demo.queue().launch(debug=False, show_api=False)