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

Update app.py

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