Spaces:
Running
Running
Add app.py
Browse files
app.py
CHANGED
@@ -1,674 +1,674 @@
|
|
1 |
-
import argparse
|
2 |
-
import os
|
3 |
-
import random
|
4 |
-
import re
|
5 |
-
import sys
|
6 |
-
from datetime import datetime
|
7 |
-
from typing import Dict, List, Tuple, Any
|
8 |
-
|
9 |
-
import pandas as pd
|
10 |
-
from huggingface_hub import login
|
11 |
-
from transformers import pipeline
|
12 |
-
from datasets import load_dataset
|
13 |
-
|
14 |
-
import gradio as gr
|
15 |
-
|
16 |
-
from huggingface_hub import HfApi, HfFolder
|
17 |
-
|
18 |
-
|
19 |
-
def extract_label(input_string: str) -> Tuple[str, str]:
|
20 |
-
"""
|
21 |
-
Extracts the label and its description from a given input string.
|
22 |
-
|
23 |
-
Args:
|
24 |
-
input_string (str): The input string containing a label and its description, separated by a colon.
|
25 |
-
|
26 |
-
Returns:
|
27 |
-
Tuple[str, str]
|
28 |
-
|
29 |
-
Raises:
|
30 |
-
ValueError: If the input string does not contain a colon.
|
31 |
-
"""
|
32 |
-
if ":" not in input_string:
|
33 |
-
raise ValueError(
|
34 |
-
"Input string must contain a ':' separating the label and description."
|
35 |
-
)
|
36 |
-
parts = input_string.split(":", 1)
|
37 |
-
return parts[0].strip(), parts[1].strip()
|
38 |
-
|
39 |
-
|
40 |
-
def parse_string(input_string: str) -> Tuple[str, str]:
|
41 |
-
"""
|
42 |
-
Parses a string containing `OUTPUT:` and `REASONING:` sections and extracts their values.
|
43 |
-
|
44 |
-
Args:
|
45 |
-
input_string (str): The input string containing `OUTPUT:` and `REASONING:` labels.
|
46 |
-
|
47 |
-
Returns:
|
48 |
-
Tuple[str, str]: A tuple containing two strings:
|
49 |
-
- The content following `OUTPUT:`.
|
50 |
-
- The content following `REASONING:`.
|
51 |
-
|
52 |
-
Raises:
|
53 |
-
ValueError: If the input string does not match the expected format with both `OUTPUT:` and `REASONING:` sections.
|
54 |
-
|
55 |
-
Note:
|
56 |
-
- The function is case-sensitive and assumes `OUTPUT:` and `REASONING:` are correctly capitalized.
|
57 |
-
"""
|
58 |
-
# Use regular expressions to extract OUTPUT and REASONING
|
59 |
-
match = re.search(r"OUTPUT:\s*(.+?)\s*REASONING:\s*(.+)", input_string, re.DOTALL)
|
60 |
-
|
61 |
-
if not match:
|
62 |
-
raise ValueError(
|
63 |
-
"The generated response is not in the expected 'OUTPUT:... REASONING:...' format."
|
64 |
-
)
|
65 |
-
|
66 |
-
output = match.group(1).strip()
|
67 |
-
reasoning = match.group(2).strip()
|
68 |
-
|
69 |
-
return output, reasoning
|
70 |
-
|
71 |
-
|
72 |
-
def sdg(
|
73 |
-
sample_size: int,
|
74 |
-
labels: List[str],
|
75 |
-
label_descriptions: str,
|
76 |
-
categories_types: Dict[str, List[str]],
|
77 |
-
use_case: str,
|
78 |
-
prompt_examples: str,
|
79 |
-
model: str,
|
80 |
-
max_new_tokens: int,
|
81 |
-
batch_size: int,
|
82 |
-
output_dir: str,
|
83 |
-
save_reasoning: bool,
|
84 |
-
) -> Tuple[str, str, str]:
|
85 |
-
"""
|
86 |
-
Generates synthetic data based on specified categories and labels.
|
87 |
-
|
88 |
-
Args:
|
89 |
-
sample_size (int): The number of synthetic data samples to generate.
|
90 |
-
labels (List[str]): The labels used to classify the synthetic data.
|
91 |
-
label_descriptions (str): A description of the meaning of each label.
|
92 |
-
categories_types (Dict[str, List[str]]): The categories and their types for data generation and diversification.
|
93 |
-
use_case (str): The use case of the synthetic data to provide context for the language model.
|
94 |
-
prompt_examples (str): The examples used in the Few-Shot or Chain-of-Thought prompting.
|
95 |
-
model (str): The large language model used for generating the synthetic data.
|
96 |
-
max_new_tokens (int): The maximum number of new tokens to generate for each sample.
|
97 |
-
batch_size (int): The number of samples per batch to append to the output file.
|
98 |
-
output_dir (str): The directory path where the output file will be saved.
|
99 |
-
save_reasoning (bool): Whether to save the reasoning or explanation behind the generated data.
|
100 |
-
|
101 |
-
Returns:
|
102 |
-
Tuple[str, str, str]: A tuple containing:
|
103 |
-
- A status message indicating the save location of the synthetic data.
|
104 |
-
- The path to the output CSV file.
|
105 |
-
- The timestamp used in the filename.
|
106 |
-
"""
|
107 |
-
categories = list(categories_types.keys())
|
108 |
-
|
109 |
-
# Generate filename with current date and time
|
110 |
-
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
111 |
-
output_path = os.path.join(output_dir, f"{timestamp}.csv")
|
112 |
-
|
113 |
-
num_batches = (sample_size + batch_size - 1) // batch_size
|
114 |
-
|
115 |
-
for batch in range(num_batches):
|
116 |
-
start = batch * batch_size
|
117 |
-
end = min(start + batch_size, sample_size)
|
118 |
-
|
119 |
-
batch_data = []
|
120 |
-
|
121 |
-
batch_random_labels = random.choices(labels, k=batch_size)
|
122 |
-
batch_random_categories = random.choices(categories, k=batch_size)
|
123 |
-
|
124 |
-
for i in range(start, end):
|
125 |
-
random_type = random.choices(
|
126 |
-
categories_types[batch_random_categories[i - start]]
|
127 |
-
)
|
128 |
-
prompt = f"""You should create synthetic data for specified labels and categories.
|
129 |
-
This is especially useful for {use_case}.
|
130 |
-
|
131 |
-
*Label Descriptions*
|
132 |
-
{label_descriptions}
|
133 |
-
|
134 |
-
*Examples*
|
135 |
-
{prompt_examples}
|
136 |
-
|
137 |
-
####################
|
138 |
-
|
139 |
-
Generate one output for the classification below.
|
140 |
-
You may use the examples I have provided as a guide, but you cannot simply modify or rewrite them.
|
141 |
-
Only return the OUTPUT and REASONING. The first token in your response must be OUTPUT.
|
142 |
-
Do not return the LABEL, CATEGORY, or TYPE.
|
143 |
-
|
144 |
-
LABEL: {batch_random_labels[i - start]}
|
145 |
-
CATEGORY: {batch_random_categories[i - start]}
|
146 |
-
TYPE: {random_type}
|
147 |
-
OUTPUT:
|
148 |
-
REASONING:
|
149 |
-
"""
|
150 |
-
messages = [
|
151 |
-
{
|
152 |
-
"role": "system",
|
153 |
-
"content": f"You are a helpful assistant designed to generate synthetic data for {use_case} with labels {labels} in categories {categories}. The first token in your generated text must be OUTPUT: This must be followed by the token REASONING: as in the prompt examples.",
|
154 |
-
},
|
155 |
-
{"role": "user", "content": prompt},
|
156 |
-
]
|
157 |
-
generator = pipeline("text-generation", model=model)
|
158 |
-
result = generator(messages, max_new_tokens=max_new_tokens)[0][
|
159 |
-
"generated_text"
|
160 |
-
][-1]["content"]
|
161 |
-
|
162 |
-
text, reasoning = parse_string(result)
|
163 |
-
|
164 |
-
entry = {
|
165 |
-
"text": text,
|
166 |
-
"label": batch_random_labels[i - start],
|
167 |
-
"source": model,
|
168 |
-
}
|
169 |
-
|
170 |
-
if save_reasoning:
|
171 |
-
entry["reasoning"] = reasoning
|
172 |
-
|
173 |
-
batch_data.append(entry)
|
174 |
-
|
175 |
-
batch_df = pd.DataFrame(batch_data)
|
176 |
-
|
177 |
-
if batch == 0:
|
178 |
-
batch_df.to_csv(output_path, mode="w", index=False)
|
179 |
-
else:
|
180 |
-
batch_df.to_csv(output_path, mode="a", header=False, index=False)
|
181 |
-
|
182 |
-
return f"Synthetic data saved to {output_path}", output_path, timestamp
|
183 |
-
|
184 |
-
|
185 |
-
def main() -> None:
|
186 |
-
"""
|
187 |
-
Main entry point for running the synthetic data generator.
|
188 |
-
"""
|
189 |
-
|
190 |
-
def run_sdg(
|
191 |
-
sample_size: int,
|
192 |
-
model: str,
|
193 |
-
max_new_tokens: int,
|
194 |
-
save_reasoning: bool,
|
195 |
-
token: str,
|
196 |
-
state: Dict,
|
197 |
-
label_boxes: List[Dict[str, str]],
|
198 |
-
use_case: str,
|
199 |
-
prompt_examples: str,
|
200 |
-
category_boxes: List[Dict[str, str]],
|
201 |
-
) -> Tuple[str, Dict]:
|
202 |
-
"""
|
203 |
-
Runs the synthetic data generation process and updates the application state.
|
204 |
-
|
205 |
-
Args:
|
206 |
-
sample_size (int): The total number of synthetic data samples to generate.
|
207 |
-
model (str): The large language model used for generating the synthetic data.
|
208 |
-
max_new_tokens (int): The maximum number of new tokens to generate for each sample.
|
209 |
-
save_reasoning (bool): Whether to save the reasoning or explanation behind the generated data.
|
210 |
-
token (str): The Hugging Face token for authentication.
|
211 |
-
state (Dict): The application state to store the output path and timestamp.
|
212 |
-
label_boxes (List[Dict[str, str]]): A list of label description dictionaries.
|
213 |
-
use_case (str): A string for the use case description.
|
214 |
-
prompt_examples (str): A string for prompt examples.
|
215 |
-
category_boxes (List[Dict[str, str]]): A list of category and type dictionaries .
|
216 |
-
|
217 |
-
Returns:
|
218 |
-
Tuple[str, Dict]: A tuple containing:
|
219 |
-
- A status message indicating the result of the generation process.
|
220 |
-
- The updated application state with the output path and timestamp.
|
221 |
-
"""
|
222 |
-
try:
|
223 |
-
login(token)
|
224 |
-
except Exception as e:
|
225 |
-
return f"Error logging in with token: {e}", None, None
|
226 |
-
|
227 |
-
label_descriptions = ""
|
228 |
-
labels = []
|
229 |
-
for box in label_boxes:
|
230 |
-
label_descriptions += box["content"] + "\n"
|
231 |
-
label, _ = extract_label(box["content"])
|
232 |
-
labels.append(label)
|
233 |
-
|
234 |
-
categories_types = {}
|
235 |
-
for box in category_boxes:
|
236 |
-
category, types = extract_label(box["content"])
|
237 |
-
categories_types[category.strip()] = [t.strip() for t in types.split(",")]
|
238 |
-
|
239 |
-
status, output_path, timestamp = sdg(
|
240 |
-
sample_size=sample_size,
|
241 |
-
labels=labels,
|
242 |
-
label_descriptions=label_descriptions,
|
243 |
-
categories_types=categories_types,
|
244 |
-
use_case=use_case,
|
245 |
-
prompt_examples=prompt_examples,
|
246 |
-
model=model,
|
247 |
-
max_new_tokens=max_new_tokens,
|
248 |
-
batch_size=20,
|
249 |
-
output_dir="./",
|
250 |
-
save_reasoning=save_reasoning,
|
251 |
-
)
|
252 |
-
state["output_path"] = output_path
|
253 |
-
state["timestamp"] = timestamp
|
254 |
-
return status, state
|
255 |
-
|
256 |
-
with gr.Blocks(css_paths="styles.css") as demo:
|
257 |
-
gr.Markdown(
|
258 |
-
"# Synthetic Data Generator",
|
259 |
-
elem_id="header",
|
260 |
-
elem_classes="text-center",
|
261 |
-
)
|
262 |
-
gr.Markdown(
|
263 |
-
"**Use Language Models to Create Datasets for Specified Labels and Categories**",
|
264 |
-
elem_classes="text-center",
|
265 |
-
)
|
266 |
-
with gr.Tab("Data Generator"):
|
267 |
-
with gr.Row(): # A row for two columns
|
268 |
-
with gr.Column(): # First column
|
269 |
-
gr.Markdown(
|
270 |
-
"## Setup & Configure",
|
271 |
-
elem_classes="text-center",
|
272 |
-
)
|
273 |
-
gr.Markdown("### Use Case")
|
274 |
-
use_case = gr.Textbox(
|
275 |
-
show_label=False,
|
276 |
-
info="Example. customer service",
|
277 |
-
autofocus=True,
|
278 |
-
)
|
279 |
-
label_boxes = gr.State([])
|
280 |
-
gr.Markdown("### Labels")
|
281 |
-
with gr.Row():
|
282 |
-
new_label = gr.Textbox(
|
283 |
-
show_label=False,
|
284 |
-
info="Example. polite: Text is considerate and shows respect and good manners, often including courteous phrases and a friendly tone.",
|
285 |
-
placeholder="Use a colon to separate each label and its description.",
|
286 |
-
)
|
287 |
-
add_label_button = gr.Button("Add", elem_classes="btn", scale=0)
|
288 |
-
|
289 |
-
def add_item(
|
290 |
-
label_boxes: List[Dict[str, str]], new_content: str
|
291 |
-
) -> Tuple[List[Dict[str, str]], str]:
|
292 |
-
"""
|
293 |
-
Adds a new label or category to the list if the input is not empty.
|
294 |
-
|
295 |
-
Args:
|
296 |
-
label_boxes (List[Dict[str, str]]): A list containing dictionaries representing the current labels or categories.
|
297 |
-
new_content (str): The new label or category content to add.
|
298 |
-
|
299 |
-
Returns:
|
300 |
-
Tuple[List[Dict[str, str]], str]: A tuple containing the updated list of labels or categories and an empty string to clear the input field.
|
301 |
-
"""
|
302 |
-
if new_content.strip():
|
303 |
-
return (
|
304 |
-
label_boxes + [{"content": new_content.strip()}],
|
305 |
-
"",
|
306 |
-
)
|
307 |
-
return label_boxes, ""
|
308 |
-
|
309 |
-
add_label_button.click(
|
310 |
-
add_item, [label_boxes, new_label], [label_boxes, new_label]
|
311 |
-
)
|
312 |
-
|
313 |
-
@gr.render(inputs=label_boxes)
|
314 |
-
def render_boxes(box_list: List[Dict[str, str]]) -> None:
|
315 |
-
"""
|
316 |
-
Renders a list of labels in a Gradio interface.
|
317 |
-
|
318 |
-
Args:
|
319 |
-
box_list (List[Dict[str, str]]): A list containing dictionaries representing the categories to render.
|
320 |
-
"""
|
321 |
-
with gr.Accordion(
|
322 |
-
f"Number of Entered Labels ({len(box_list)})"
|
323 |
-
):
|
324 |
-
for box in box_list:
|
325 |
-
with gr.Row():
|
326 |
-
gr.Textbox(
|
327 |
-
box["content"],
|
328 |
-
show_label=False,
|
329 |
-
container=False,
|
330 |
-
)
|
331 |
-
delete_button = gr.Button(
|
332 |
-
"Delete", scale=0, variant="stop"
|
333 |
-
)
|
334 |
-
|
335 |
-
def delete(
|
336 |
-
box: Dict[str, str] = box,
|
337 |
-
) -> List[Dict[str, str]]:
|
338 |
-
"""
|
339 |
-
Deletes a specific box from the list of labels.
|
340 |
-
|
341 |
-
Args:
|
342 |
-
box (Dict[str, str]): The box to be removed from the list.
|
343 |
-
|
344 |
-
Returns:
|
345 |
-
List[Dict[str, str]]: The updated list of labels after the box is removed.
|
346 |
-
"""
|
347 |
-
box_list.remove(box)
|
348 |
-
return box_list
|
349 |
-
|
350 |
-
delete_button.click(delete, None, [label_boxes])
|
351 |
-
|
352 |
-
category_boxes = gr.State([])
|
353 |
-
gr.Markdown("### Categories")
|
354 |
-
with gr.Row():
|
355 |
-
new_category = gr.Textbox(
|
356 |
-
show_label=False,
|
357 |
-
info="Example. travel: hotel, airline, train",
|
358 |
-
placeholder="Use a colon to separate each category and its types.",
|
359 |
-
)
|
360 |
-
add_category_button = gr.Button(
|
361 |
-
"Add", elem_classes="btn", scale=0
|
362 |
-
)
|
363 |
-
add_category_button.click(
|
364 |
-
add_item,
|
365 |
-
[category_boxes, new_category],
|
366 |
-
[category_boxes, new_category],
|
367 |
-
)
|
368 |
-
|
369 |
-
@gr.render(inputs=category_boxes)
|
370 |
-
def render_boxes(box_list: List[Dict[str, str]]) -> None:
|
371 |
-
"""
|
372 |
-
Renders a list of categories in a Gradio interface.
|
373 |
-
|
374 |
-
Args:
|
375 |
-
box_list (List[Dict[str, str]]): A list containing dictionaries representing the categories to render.
|
376 |
-
"""
|
377 |
-
with gr.Accordion(
|
378 |
-
f"Number of Entered Categories ({len(box_list)})"
|
379 |
-
):
|
380 |
-
for box in box_list:
|
381 |
-
with gr.Row():
|
382 |
-
gr.Textbox(
|
383 |
-
box["content"],
|
384 |
-
show_label=False,
|
385 |
-
container=False,
|
386 |
-
)
|
387 |
-
delete_button = gr.Button(
|
388 |
-
"Delete", scale=0, variant="stop"
|
389 |
-
)
|
390 |
-
|
391 |
-
def delete(
|
392 |
-
box: Dict[str, str] = box,
|
393 |
-
) -> List[Dict[str, str]]:
|
394 |
-
"""
|
395 |
-
Deletes a specific box from the list of categories.
|
396 |
-
|
397 |
-
Args:
|
398 |
-
box (Dict[str, str]): The box to be removed from the list.
|
399 |
-
|
400 |
-
Returns:
|
401 |
-
List[Dict[str, str]]: The updated list of categories after the box is removed.
|
402 |
-
"""
|
403 |
-
box_list.remove(box)
|
404 |
-
return box_list
|
405 |
-
|
406 |
-
delete_button.click(delete, None, [category_boxes])
|
407 |
-
|
408 |
-
gr.Markdown(
|
409 |
-
"### Guiding Examples",
|
410 |
-
)
|
411 |
-
prompt_examples = gr.Textbox(
|
412 |
-
show_label=False,
|
413 |
-
info="""Example.
|
414 |
-
LABEL: polite
|
415 |
-
CATEGORY: food and drink
|
416 |
-
TYPE: cafe
|
417 |
-
OUTPUT: Thank you for visiting! While we prepare your coffee, feel free to relax or browse our selection of pastries. Let us know if we can make your day even better!
|
418 |
-
REASONING: This text is polite because it expresses gratitude and encourages the customer to feel at ease with a welcoming tone. Phrases like "Let us know if we can make your day even better" show warmth and consideration, enhancing the customer experience.""",
|
419 |
-
placeholder="Include all examples in this box. Use the format\n'LABEL: label_name\nCATEGORY: category_name\nTYPE: type_name\nOUTPUT: generated_output\nREASONING: reasoning'",
|
420 |
-
lines=6,
|
421 |
-
)
|
422 |
-
gr.Markdown("### Language Model")
|
423 |
-
model = gr.Dropdown(
|
424 |
-
label="Model",
|
425 |
-
choices=[
|
426 |
-
"google/gemma-3-1b-it",
|
427 |
-
"HuggingFaceTB/SmolLM2-1.7B-Instruct",
|
428 |
-
"meta-llama/Llama-3.2-3B-Instruct",
|
429 |
-
],
|
430 |
-
value="google/gemma-3-1b-it",
|
431 |
-
)
|
432 |
-
max_new_tokens = gr.Number(
|
433 |
-
label="Max New Tokens", value=256, minimum=64
|
434 |
-
)
|
435 |
-
token = gr.Textbox(
|
436 |
-
label="Hugging Face Token",
|
437 |
-
type="password",
|
438 |
-
info="Enter a 'Read' Hugging Face token to access gated language models, or a 'Write' token to push the generated data to Hugging Face.",
|
439 |
-
)
|
440 |
-
with gr.Column(): # Second column
|
441 |
-
gr.Markdown(
|
442 |
-
"## Generate & Export",
|
443 |
-
elem_classes="text-center",
|
444 |
-
)
|
445 |
-
gr.Markdown("### Status")
|
446 |
-
status = gr.Textbox(label="Status")
|
447 |
-
gr.Markdown("### Actions")
|
448 |
-
sample_size = gr.Number(label="Sample Size", value=1, minimum=1)
|
449 |
-
save_reasoning = gr.Checkbox(label="Save Reasoning", value=True)
|
450 |
-
generate_button = gr.Button(
|
451 |
-
"Generate!", interactive=False, elem_classes="btn"
|
452 |
-
)
|
453 |
-
download_button = gr.Button(
|
454 |
-
"Download CSV", interactive=False, elem_classes="btn"
|
455 |
-
)
|
456 |
-
file_output = gr.File(label="Download!", visible=False)
|
457 |
-
repo_id = gr.Textbox(
|
458 |
-
label="Hugging Face Repo ID",
|
459 |
-
placeholder="your-username/your-repo-name",
|
460 |
-
)
|
461 |
-
is_public_repo = gr.Checkbox(
|
462 |
-
label="Make Repository Public", value=False
|
463 |
-
)
|
464 |
-
push_button = gr.Button(
|
465 |
-
"Push to Hugging Face", interactive=False, elem_classes="btn"
|
466 |
-
)
|
467 |
-
gr.Markdown(
|
468 |
-
"### Sample Output",
|
469 |
-
)
|
470 |
-
dataset = (
|
471 |
-
load_dataset("Intel/polite-guard", split="validation")
|
472 |
-
.to_pandas()
|
473 |
-
.sample(n=5)
|
474 |
-
)
|
475 |
-
# df_demo = pd.read_csv("samples.csv").head()
|
476 |
-
dataframe = gr.Dataframe(value=dataset, show_label=False)
|
477 |
-
|
478 |
-
state = gr.State({"output_path": None, "timestamp": None})
|
479 |
-
|
480 |
-
def toggle_button(
|
481 |
-
token_value: str,
|
482 |
-
label_value: List[Dict[str, str]],
|
483 |
-
category_value: List[Dict[str, str]],
|
484 |
-
use_case_value: str,
|
485 |
-
example_value: str,
|
486 |
-
) -> Dict[str, Any]:
|
487 |
-
"""
|
488 |
-
Toggles the interactivity of the generate button based on input values.
|
489 |
-
|
490 |
-
Args:
|
491 |
-
token_value (str): The Hugging Face token value.
|
492 |
-
label_value (List[Dict[str, str]]): A list of label description dictionaries.
|
493 |
-
category_value (List[Dict[str, str]]): A list of category and type dictionaries.
|
494 |
-
use_case_value (str): A string for the use case description.
|
495 |
-
example_value (str): A string for prompt examples.
|
496 |
-
|
497 |
-
Returns:
|
498 |
-
Dict[str, Any]: A dictionary containing the updated interactivity state of the generate button.
|
499 |
-
"""
|
500 |
-
return gr.update(
|
501 |
-
interactive=all(
|
502 |
-
[
|
503 |
-
token_value,
|
504 |
-
label_value,
|
505 |
-
category_value,
|
506 |
-
use_case_value,
|
507 |
-
example_value,
|
508 |
-
]
|
509 |
-
)
|
510 |
-
)
|
511 |
-
|
512 |
-
token.change(
|
513 |
-
toggle_button,
|
514 |
-
inputs=[token, label_boxes, category_boxes, use_case, prompt_examples],
|
515 |
-
outputs=generate_button,
|
516 |
-
)
|
517 |
-
label_boxes.change(
|
518 |
-
toggle_button,
|
519 |
-
inputs=[token, label_boxes, category_boxes, use_case, prompt_examples],
|
520 |
-
outputs=generate_button,
|
521 |
-
)
|
522 |
-
category_boxes.change(
|
523 |
-
toggle_button,
|
524 |
-
inputs=[token, label_boxes, category_boxes, use_case, prompt_examples],
|
525 |
-
outputs=generate_button,
|
526 |
-
)
|
527 |
-
use_case.change(
|
528 |
-
toggle_button,
|
529 |
-
inputs=[token, label_boxes, category_boxes, use_case, prompt_examples],
|
530 |
-
outputs=generate_button,
|
531 |
-
)
|
532 |
-
prompt_examples.change(
|
533 |
-
toggle_button,
|
534 |
-
inputs=[token, label_boxes, category_boxes, use_case, prompt_examples],
|
535 |
-
outputs=generate_button,
|
536 |
-
)
|
537 |
-
|
538 |
-
def enable_buttons(state: Dict[str, Any]) -> List[Any]:
|
539 |
-
"""
|
540 |
-
Enables the interactivity of the download and push buttons and loads a preview of the generated data.
|
541 |
-
|
542 |
-
Args:
|
543 |
-
state (Dict[str, Any]): The application state containing the output file path.
|
544 |
-
|
545 |
-
Returns:
|
546 |
-
List[Any]: A list containing:
|
547 |
-
- An update to make the download button interactive.
|
548 |
-
- An update to make the push button interactive.
|
549 |
-
- A DataFrame preview of the generated data.
|
550 |
-
"""
|
551 |
-
df = pd.read_csv(state["output_path"]).head()
|
552 |
-
return [gr.update(interactive=True), gr.update(interactive=True), df]
|
553 |
-
|
554 |
-
generate_button.click(
|
555 |
-
run_sdg,
|
556 |
-
inputs=[
|
557 |
-
sample_size,
|
558 |
-
model,
|
559 |
-
max_new_tokens,
|
560 |
-
save_reasoning,
|
561 |
-
token,
|
562 |
-
state,
|
563 |
-
label_boxes,
|
564 |
-
use_case,
|
565 |
-
prompt_examples,
|
566 |
-
category_boxes,
|
567 |
-
],
|
568 |
-
outputs=[status, state],
|
569 |
-
).success(
|
570 |
-
enable_buttons,
|
571 |
-
inputs=[state],
|
572 |
-
outputs=[download_button, push_button, dataframe],
|
573 |
-
)
|
574 |
-
|
575 |
-
def download_csv(state: Dict) -> str:
|
576 |
-
"""
|
577 |
-
Generate the file path for downloading a CSV file.
|
578 |
-
|
579 |
-
Args:
|
580 |
-
state (Dict): The application state.
|
581 |
-
|
582 |
-
Returns:
|
583 |
-
str: The file path to the CSV file for download.
|
584 |
-
"""
|
585 |
-
return state[
|
586 |
-
"output_path"
|
587 |
-
] # Return the file path to trigger the download
|
588 |
-
|
589 |
-
def push_to_huggingface(
|
590 |
-
repo_id: str,
|
591 |
-
token_value: str,
|
592 |
-
is_public: bool,
|
593 |
-
state: Dict,
|
594 |
-
) -> str:
|
595 |
-
"""
|
596 |
-
Pushes the generated synthetic data file to the Hugging Face Hub.
|
597 |
-
|
598 |
-
Args:
|
599 |
-
repo_id (str): The ID of the Hugging Face repository (e.g., "username/repo-name").
|
600 |
-
token_value (str): The Hugging Face token for authentication.
|
601 |
-
is_public (bool): Whether to make the repository public.
|
602 |
-
state (Dict): The application state containing the output file path and timestamp.
|
603 |
-
|
604 |
-
Returns:
|
605 |
-
str: A message indicating the result of the upload process.
|
606 |
-
"""
|
607 |
-
try:
|
608 |
-
api = HfApi(token=token_value)
|
609 |
-
except Exception as e:
|
610 |
-
return f"Invalid token for writing to Hugging Face: {e}"
|
611 |
-
|
612 |
-
try:
|
613 |
-
# Ensure the repository exists, creating it if it doesn't
|
614 |
-
api.create_repo(
|
615 |
-
repo_id=repo_id,
|
616 |
-
repo_type="dataset",
|
617 |
-
exist_ok=True,
|
618 |
-
private=not is_public,
|
619 |
-
)
|
620 |
-
|
621 |
-
api.upload_file(
|
622 |
-
path_or_fileobj=state["output_path"],
|
623 |
-
path_in_repo=f"{state['timestamp']}.csv",
|
624 |
-
repo_id=repo_id,
|
625 |
-
repo_type="dataset",
|
626 |
-
)
|
627 |
-
except Exception as e:
|
628 |
-
return f"Error uploading file to Hugging Face: {e}"
|
629 |
-
visibility = "public" if is_public else "private"
|
630 |
-
return f"File pushed to {visibility} Hugging Face Hub at {repo_id}/{state['timestamp']}.csv"
|
631 |
-
|
632 |
-
download_button.click(download_csv, inputs=state, outputs=file_output).then(
|
633 |
-
lambda: gr.update(visible=True), outputs=file_output
|
634 |
-
)
|
635 |
-
|
636 |
-
push_button.click(
|
637 |
-
push_to_huggingface,
|
638 |
-
inputs=[repo_id, token, is_public_repo, state],
|
639 |
-
outputs=status,
|
640 |
-
)
|
641 |
-
|
642 |
-
with gr.Tab("About"):
|
643 |
-
with gr.Row():
|
644 |
-
with gr.Column(scale=1):
|
645 |
-
gr.Image(
|
646 |
-
"polite-guard.png",
|
647 |
-
show_download_button=False,
|
648 |
-
show_fullscreen_button=False,
|
649 |
-
show_label=False,
|
650 |
-
show_share_button=False,
|
651 |
-
container=False,
|
652 |
-
)
|
653 |
-
with gr.Column(scale=3):
|
654 |
-
gr.Markdown(
|
655 |
-
"""
|
656 |
-
This synthetic data generator, distributed with Intel's [Polite Guard](https://huggingface.co/Intel/polite-guard) project, uses a specified language model to generate synthetic data for a given use case.
|
657 |
-
If you find this project valuable, please consider giving it a ❤️ on Hugging Face and sharing it with your network.
|
658 |
-
Visit
|
659 |
-
- [Polite Guard GitHub repository](https://github.com/intel/polite-guard) for the source code that you can run through the command line,
|
660 |
-
- [Synthetic Data Generation with Language Models: A Practical Guide](https://medium.com/p/0ff98eb226a1) to learn more about the implementation of this data generator, and
|
661 |
-
- [Polite Guard Dataset](https://huggingface.co/datasets/Intel/polite-guard) for an example of a dataset generated using this data generator.
|
662 |
-
|
663 |
-
## Privacy Notice
|
664 |
-
Please note that this data generator uses AI technology and you are interacting with a chat model.
|
665 |
-
Prompts that are being used during the demo and your personal information will not be stored.
|
666 |
-
For information regarding the handling of personal data collected refer to the Global Privacy Notice (https://www.intel.com/content/www/us/en/privacy/intelprivacy-notice.html), which encompass our privacy practices.
|
667 |
-
"""
|
668 |
-
)
|
669 |
-
|
670 |
-
demo.launch(
|
671 |
-
|
672 |
-
|
673 |
-
if __name__ == "__main__":
|
674 |
-
main()
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
import random
|
4 |
+
import re
|
5 |
+
import sys
|
6 |
+
from datetime import datetime
|
7 |
+
from typing import Dict, List, Tuple, Any
|
8 |
+
|
9 |
+
import pandas as pd
|
10 |
+
from huggingface_hub import login
|
11 |
+
from transformers import pipeline
|
12 |
+
from datasets import load_dataset
|
13 |
+
|
14 |
+
import gradio as gr
|
15 |
+
|
16 |
+
from huggingface_hub import HfApi, HfFolder
|
17 |
+
|
18 |
+
|
19 |
+
def extract_label(input_string: str) -> Tuple[str, str]:
|
20 |
+
"""
|
21 |
+
Extracts the label and its description from a given input string.
|
22 |
+
|
23 |
+
Args:
|
24 |
+
input_string (str): The input string containing a label and its description, separated by a colon.
|
25 |
+
|
26 |
+
Returns:
|
27 |
+
Tuple[str, str]
|
28 |
+
|
29 |
+
Raises:
|
30 |
+
ValueError: If the input string does not contain a colon.
|
31 |
+
"""
|
32 |
+
if ":" not in input_string:
|
33 |
+
raise ValueError(
|
34 |
+
"Input string must contain a ':' separating the label and description."
|
35 |
+
)
|
36 |
+
parts = input_string.split(":", 1)
|
37 |
+
return parts[0].strip(), parts[1].strip()
|
38 |
+
|
39 |
+
|
40 |
+
def parse_string(input_string: str) -> Tuple[str, str]:
|
41 |
+
"""
|
42 |
+
Parses a string containing `OUTPUT:` and `REASONING:` sections and extracts their values.
|
43 |
+
|
44 |
+
Args:
|
45 |
+
input_string (str): The input string containing `OUTPUT:` and `REASONING:` labels.
|
46 |
+
|
47 |
+
Returns:
|
48 |
+
Tuple[str, str]: A tuple containing two strings:
|
49 |
+
- The content following `OUTPUT:`.
|
50 |
+
- The content following `REASONING:`.
|
51 |
+
|
52 |
+
Raises:
|
53 |
+
ValueError: If the input string does not match the expected format with both `OUTPUT:` and `REASONING:` sections.
|
54 |
+
|
55 |
+
Note:
|
56 |
+
- The function is case-sensitive and assumes `OUTPUT:` and `REASONING:` are correctly capitalized.
|
57 |
+
"""
|
58 |
+
# Use regular expressions to extract OUTPUT and REASONING
|
59 |
+
match = re.search(r"OUTPUT:\s*(.+?)\s*REASONING:\s*(.+)", input_string, re.DOTALL)
|
60 |
+
|
61 |
+
if not match:
|
62 |
+
raise ValueError(
|
63 |
+
"The generated response is not in the expected 'OUTPUT:... REASONING:...' format."
|
64 |
+
)
|
65 |
+
|
66 |
+
output = match.group(1).strip()
|
67 |
+
reasoning = match.group(2).strip()
|
68 |
+
|
69 |
+
return output, reasoning
|
70 |
+
|
71 |
+
|
72 |
+
def sdg(
|
73 |
+
sample_size: int,
|
74 |
+
labels: List[str],
|
75 |
+
label_descriptions: str,
|
76 |
+
categories_types: Dict[str, List[str]],
|
77 |
+
use_case: str,
|
78 |
+
prompt_examples: str,
|
79 |
+
model: str,
|
80 |
+
max_new_tokens: int,
|
81 |
+
batch_size: int,
|
82 |
+
output_dir: str,
|
83 |
+
save_reasoning: bool,
|
84 |
+
) -> Tuple[str, str, str]:
|
85 |
+
"""
|
86 |
+
Generates synthetic data based on specified categories and labels.
|
87 |
+
|
88 |
+
Args:
|
89 |
+
sample_size (int): The number of synthetic data samples to generate.
|
90 |
+
labels (List[str]): The labels used to classify the synthetic data.
|
91 |
+
label_descriptions (str): A description of the meaning of each label.
|
92 |
+
categories_types (Dict[str, List[str]]): The categories and their types for data generation and diversification.
|
93 |
+
use_case (str): The use case of the synthetic data to provide context for the language model.
|
94 |
+
prompt_examples (str): The examples used in the Few-Shot or Chain-of-Thought prompting.
|
95 |
+
model (str): The large language model used for generating the synthetic data.
|
96 |
+
max_new_tokens (int): The maximum number of new tokens to generate for each sample.
|
97 |
+
batch_size (int): The number of samples per batch to append to the output file.
|
98 |
+
output_dir (str): The directory path where the output file will be saved.
|
99 |
+
save_reasoning (bool): Whether to save the reasoning or explanation behind the generated data.
|
100 |
+
|
101 |
+
Returns:
|
102 |
+
Tuple[str, str, str]: A tuple containing:
|
103 |
+
- A status message indicating the save location of the synthetic data.
|
104 |
+
- The path to the output CSV file.
|
105 |
+
- The timestamp used in the filename.
|
106 |
+
"""
|
107 |
+
categories = list(categories_types.keys())
|
108 |
+
|
109 |
+
# Generate filename with current date and time
|
110 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
111 |
+
output_path = os.path.join(output_dir, f"{timestamp}.csv")
|
112 |
+
|
113 |
+
num_batches = (sample_size + batch_size - 1) // batch_size
|
114 |
+
|
115 |
+
for batch in range(num_batches):
|
116 |
+
start = batch * batch_size
|
117 |
+
end = min(start + batch_size, sample_size)
|
118 |
+
|
119 |
+
batch_data = []
|
120 |
+
|
121 |
+
batch_random_labels = random.choices(labels, k=batch_size)
|
122 |
+
batch_random_categories = random.choices(categories, k=batch_size)
|
123 |
+
|
124 |
+
for i in range(start, end):
|
125 |
+
random_type = random.choices(
|
126 |
+
categories_types[batch_random_categories[i - start]]
|
127 |
+
)
|
128 |
+
prompt = f"""You should create synthetic data for specified labels and categories.
|
129 |
+
This is especially useful for {use_case}.
|
130 |
+
|
131 |
+
*Label Descriptions*
|
132 |
+
{label_descriptions}
|
133 |
+
|
134 |
+
*Examples*
|
135 |
+
{prompt_examples}
|
136 |
+
|
137 |
+
####################
|
138 |
+
|
139 |
+
Generate one output for the classification below.
|
140 |
+
You may use the examples I have provided as a guide, but you cannot simply modify or rewrite them.
|
141 |
+
Only return the OUTPUT and REASONING. The first token in your response must be OUTPUT.
|
142 |
+
Do not return the LABEL, CATEGORY, or TYPE.
|
143 |
+
|
144 |
+
LABEL: {batch_random_labels[i - start]}
|
145 |
+
CATEGORY: {batch_random_categories[i - start]}
|
146 |
+
TYPE: {random_type}
|
147 |
+
OUTPUT:
|
148 |
+
REASONING:
|
149 |
+
"""
|
150 |
+
messages = [
|
151 |
+
{
|
152 |
+
"role": "system",
|
153 |
+
"content": f"You are a helpful assistant designed to generate synthetic data for {use_case} with labels {labels} in categories {categories}. The first token in your generated text must be OUTPUT: This must be followed by the token REASONING: as in the prompt examples.",
|
154 |
+
},
|
155 |
+
{"role": "user", "content": prompt},
|
156 |
+
]
|
157 |
+
generator = pipeline("text-generation", model=model)
|
158 |
+
result = generator(messages, max_new_tokens=max_new_tokens)[0][
|
159 |
+
"generated_text"
|
160 |
+
][-1]["content"]
|
161 |
+
|
162 |
+
text, reasoning = parse_string(result)
|
163 |
+
|
164 |
+
entry = {
|
165 |
+
"text": text,
|
166 |
+
"label": batch_random_labels[i - start],
|
167 |
+
"source": model,
|
168 |
+
}
|
169 |
+
|
170 |
+
if save_reasoning:
|
171 |
+
entry["reasoning"] = reasoning
|
172 |
+
|
173 |
+
batch_data.append(entry)
|
174 |
+
|
175 |
+
batch_df = pd.DataFrame(batch_data)
|
176 |
+
|
177 |
+
if batch == 0:
|
178 |
+
batch_df.to_csv(output_path, mode="w", index=False)
|
179 |
+
else:
|
180 |
+
batch_df.to_csv(output_path, mode="a", header=False, index=False)
|
181 |
+
|
182 |
+
return f"Synthetic data saved to {output_path}", output_path, timestamp
|
183 |
+
|
184 |
+
|
185 |
+
def main() -> None:
|
186 |
+
"""
|
187 |
+
Main entry point for running the synthetic data generator.
|
188 |
+
"""
|
189 |
+
|
190 |
+
def run_sdg(
|
191 |
+
sample_size: int,
|
192 |
+
model: str,
|
193 |
+
max_new_tokens: int,
|
194 |
+
save_reasoning: bool,
|
195 |
+
token: str,
|
196 |
+
state: Dict,
|
197 |
+
label_boxes: List[Dict[str, str]],
|
198 |
+
use_case: str,
|
199 |
+
prompt_examples: str,
|
200 |
+
category_boxes: List[Dict[str, str]],
|
201 |
+
) -> Tuple[str, Dict]:
|
202 |
+
"""
|
203 |
+
Runs the synthetic data generation process and updates the application state.
|
204 |
+
|
205 |
+
Args:
|
206 |
+
sample_size (int): The total number of synthetic data samples to generate.
|
207 |
+
model (str): The large language model used for generating the synthetic data.
|
208 |
+
max_new_tokens (int): The maximum number of new tokens to generate for each sample.
|
209 |
+
save_reasoning (bool): Whether to save the reasoning or explanation behind the generated data.
|
210 |
+
token (str): The Hugging Face token for authentication.
|
211 |
+
state (Dict): The application state to store the output path and timestamp.
|
212 |
+
label_boxes (List[Dict[str, str]]): A list of label description dictionaries.
|
213 |
+
use_case (str): A string for the use case description.
|
214 |
+
prompt_examples (str): A string for prompt examples.
|
215 |
+
category_boxes (List[Dict[str, str]]): A list of category and type dictionaries .
|
216 |
+
|
217 |
+
Returns:
|
218 |
+
Tuple[str, Dict]: A tuple containing:
|
219 |
+
- A status message indicating the result of the generation process.
|
220 |
+
- The updated application state with the output path and timestamp.
|
221 |
+
"""
|
222 |
+
try:
|
223 |
+
login(token)
|
224 |
+
except Exception as e:
|
225 |
+
return f"Error logging in with token: {e}", None, None
|
226 |
+
|
227 |
+
label_descriptions = ""
|
228 |
+
labels = []
|
229 |
+
for box in label_boxes:
|
230 |
+
label_descriptions += box["content"] + "\n"
|
231 |
+
label, _ = extract_label(box["content"])
|
232 |
+
labels.append(label)
|
233 |
+
|
234 |
+
categories_types = {}
|
235 |
+
for box in category_boxes:
|
236 |
+
category, types = extract_label(box["content"])
|
237 |
+
categories_types[category.strip()] = [t.strip() for t in types.split(",")]
|
238 |
+
|
239 |
+
status, output_path, timestamp = sdg(
|
240 |
+
sample_size=sample_size,
|
241 |
+
labels=labels,
|
242 |
+
label_descriptions=label_descriptions,
|
243 |
+
categories_types=categories_types,
|
244 |
+
use_case=use_case,
|
245 |
+
prompt_examples=prompt_examples,
|
246 |
+
model=model,
|
247 |
+
max_new_tokens=max_new_tokens,
|
248 |
+
batch_size=20,
|
249 |
+
output_dir="./",
|
250 |
+
save_reasoning=save_reasoning,
|
251 |
+
)
|
252 |
+
state["output_path"] = output_path
|
253 |
+
state["timestamp"] = timestamp
|
254 |
+
return status, state
|
255 |
+
|
256 |
+
with gr.Blocks(css_paths="styles.css") as demo:
|
257 |
+
gr.Markdown(
|
258 |
+
"# Synthetic Data Generator",
|
259 |
+
elem_id="header",
|
260 |
+
elem_classes="text-center",
|
261 |
+
)
|
262 |
+
gr.Markdown(
|
263 |
+
"**Use Language Models to Create Datasets for Specified Labels and Categories**",
|
264 |
+
elem_classes="text-center",
|
265 |
+
)
|
266 |
+
with gr.Tab("Data Generator"):
|
267 |
+
with gr.Row(): # A row for two columns
|
268 |
+
with gr.Column(): # First column
|
269 |
+
gr.Markdown(
|
270 |
+
"## Setup & Configure",
|
271 |
+
elem_classes="text-center",
|
272 |
+
)
|
273 |
+
gr.Markdown("### Use Case")
|
274 |
+
use_case = gr.Textbox(
|
275 |
+
show_label=False,
|
276 |
+
info="Example. customer service",
|
277 |
+
autofocus=True,
|
278 |
+
)
|
279 |
+
label_boxes = gr.State([])
|
280 |
+
gr.Markdown("### Labels")
|
281 |
+
with gr.Row():
|
282 |
+
new_label = gr.Textbox(
|
283 |
+
show_label=False,
|
284 |
+
info="Example. polite: Text is considerate and shows respect and good manners, often including courteous phrases and a friendly tone.",
|
285 |
+
placeholder="Use a colon to separate each label and its description.",
|
286 |
+
)
|
287 |
+
add_label_button = gr.Button("Add", elem_classes="btn", scale=0)
|
288 |
+
|
289 |
+
def add_item(
|
290 |
+
label_boxes: List[Dict[str, str]], new_content: str
|
291 |
+
) -> Tuple[List[Dict[str, str]], str]:
|
292 |
+
"""
|
293 |
+
Adds a new label or category to the list if the input is not empty.
|
294 |
+
|
295 |
+
Args:
|
296 |
+
label_boxes (List[Dict[str, str]]): A list containing dictionaries representing the current labels or categories.
|
297 |
+
new_content (str): The new label or category content to add.
|
298 |
+
|
299 |
+
Returns:
|
300 |
+
Tuple[List[Dict[str, str]], str]: A tuple containing the updated list of labels or categories and an empty string to clear the input field.
|
301 |
+
"""
|
302 |
+
if new_content.strip():
|
303 |
+
return (
|
304 |
+
label_boxes + [{"content": new_content.strip()}],
|
305 |
+
"",
|
306 |
+
)
|
307 |
+
return label_boxes, ""
|
308 |
+
|
309 |
+
add_label_button.click(
|
310 |
+
add_item, [label_boxes, new_label], [label_boxes, new_label]
|
311 |
+
)
|
312 |
+
|
313 |
+
@gr.render(inputs=label_boxes)
|
314 |
+
def render_boxes(box_list: List[Dict[str, str]]) -> None:
|
315 |
+
"""
|
316 |
+
Renders a list of labels in a Gradio interface.
|
317 |
+
|
318 |
+
Args:
|
319 |
+
box_list (List[Dict[str, str]]): A list containing dictionaries representing the categories to render.
|
320 |
+
"""
|
321 |
+
with gr.Accordion(
|
322 |
+
f"Number of Entered Labels ({len(box_list)})"
|
323 |
+
):
|
324 |
+
for box in box_list:
|
325 |
+
with gr.Row():
|
326 |
+
gr.Textbox(
|
327 |
+
box["content"],
|
328 |
+
show_label=False,
|
329 |
+
container=False,
|
330 |
+
)
|
331 |
+
delete_button = gr.Button(
|
332 |
+
"Delete", scale=0, variant="stop"
|
333 |
+
)
|
334 |
+
|
335 |
+
def delete(
|
336 |
+
box: Dict[str, str] = box,
|
337 |
+
) -> List[Dict[str, str]]:
|
338 |
+
"""
|
339 |
+
Deletes a specific box from the list of labels.
|
340 |
+
|
341 |
+
Args:
|
342 |
+
box (Dict[str, str]): The box to be removed from the list.
|
343 |
+
|
344 |
+
Returns:
|
345 |
+
List[Dict[str, str]]: The updated list of labels after the box is removed.
|
346 |
+
"""
|
347 |
+
box_list.remove(box)
|
348 |
+
return box_list
|
349 |
+
|
350 |
+
delete_button.click(delete, None, [label_boxes])
|
351 |
+
|
352 |
+
category_boxes = gr.State([])
|
353 |
+
gr.Markdown("### Categories")
|
354 |
+
with gr.Row():
|
355 |
+
new_category = gr.Textbox(
|
356 |
+
show_label=False,
|
357 |
+
info="Example. travel: hotel, airline, train",
|
358 |
+
placeholder="Use a colon to separate each category and its types.",
|
359 |
+
)
|
360 |
+
add_category_button = gr.Button(
|
361 |
+
"Add", elem_classes="btn", scale=0
|
362 |
+
)
|
363 |
+
add_category_button.click(
|
364 |
+
add_item,
|
365 |
+
[category_boxes, new_category],
|
366 |
+
[category_boxes, new_category],
|
367 |
+
)
|
368 |
+
|
369 |
+
@gr.render(inputs=category_boxes)
|
370 |
+
def render_boxes(box_list: List[Dict[str, str]]) -> None:
|
371 |
+
"""
|
372 |
+
Renders a list of categories in a Gradio interface.
|
373 |
+
|
374 |
+
Args:
|
375 |
+
box_list (List[Dict[str, str]]): A list containing dictionaries representing the categories to render.
|
376 |
+
"""
|
377 |
+
with gr.Accordion(
|
378 |
+
f"Number of Entered Categories ({len(box_list)})"
|
379 |
+
):
|
380 |
+
for box in box_list:
|
381 |
+
with gr.Row():
|
382 |
+
gr.Textbox(
|
383 |
+
box["content"],
|
384 |
+
show_label=False,
|
385 |
+
container=False,
|
386 |
+
)
|
387 |
+
delete_button = gr.Button(
|
388 |
+
"Delete", scale=0, variant="stop"
|
389 |
+
)
|
390 |
+
|
391 |
+
def delete(
|
392 |
+
box: Dict[str, str] = box,
|
393 |
+
) -> List[Dict[str, str]]:
|
394 |
+
"""
|
395 |
+
Deletes a specific box from the list of categories.
|
396 |
+
|
397 |
+
Args:
|
398 |
+
box (Dict[str, str]): The box to be removed from the list.
|
399 |
+
|
400 |
+
Returns:
|
401 |
+
List[Dict[str, str]]: The updated list of categories after the box is removed.
|
402 |
+
"""
|
403 |
+
box_list.remove(box)
|
404 |
+
return box_list
|
405 |
+
|
406 |
+
delete_button.click(delete, None, [category_boxes])
|
407 |
+
|
408 |
+
gr.Markdown(
|
409 |
+
"### Guiding Examples",
|
410 |
+
)
|
411 |
+
prompt_examples = gr.Textbox(
|
412 |
+
show_label=False,
|
413 |
+
info="""Example.
|
414 |
+
LABEL: polite
|
415 |
+
CATEGORY: food and drink
|
416 |
+
TYPE: cafe
|
417 |
+
OUTPUT: Thank you for visiting! While we prepare your coffee, feel free to relax or browse our selection of pastries. Let us know if we can make your day even better!
|
418 |
+
REASONING: This text is polite because it expresses gratitude and encourages the customer to feel at ease with a welcoming tone. Phrases like "Let us know if we can make your day even better" show warmth and consideration, enhancing the customer experience.""",
|
419 |
+
placeholder="Include all examples in this box. Use the format\n'LABEL: label_name\nCATEGORY: category_name\nTYPE: type_name\nOUTPUT: generated_output\nREASONING: reasoning'",
|
420 |
+
lines=6,
|
421 |
+
)
|
422 |
+
gr.Markdown("### Language Model")
|
423 |
+
model = gr.Dropdown(
|
424 |
+
label="Model",
|
425 |
+
choices=[
|
426 |
+
"google/gemma-3-1b-it",
|
427 |
+
"HuggingFaceTB/SmolLM2-1.7B-Instruct",
|
428 |
+
"meta-llama/Llama-3.2-3B-Instruct",
|
429 |
+
],
|
430 |
+
value="google/gemma-3-1b-it",
|
431 |
+
)
|
432 |
+
max_new_tokens = gr.Number(
|
433 |
+
label="Max New Tokens", value=256, minimum=64
|
434 |
+
)
|
435 |
+
token = gr.Textbox(
|
436 |
+
label="Hugging Face Token",
|
437 |
+
type="password",
|
438 |
+
info="Enter a 'Read' Hugging Face token to access gated language models, or a 'Write' token to push the generated data to Hugging Face.",
|
439 |
+
)
|
440 |
+
with gr.Column(): # Second column
|
441 |
+
gr.Markdown(
|
442 |
+
"## Generate & Export",
|
443 |
+
elem_classes="text-center",
|
444 |
+
)
|
445 |
+
gr.Markdown("### Status")
|
446 |
+
status = gr.Textbox(label="Status")
|
447 |
+
gr.Markdown("### Actions")
|
448 |
+
sample_size = gr.Number(label="Sample Size", value=1, minimum=1)
|
449 |
+
save_reasoning = gr.Checkbox(label="Save Reasoning", value=True)
|
450 |
+
generate_button = gr.Button(
|
451 |
+
"Generate!", interactive=False, elem_classes="btn"
|
452 |
+
)
|
453 |
+
download_button = gr.Button(
|
454 |
+
"Download CSV", interactive=False, elem_classes="btn"
|
455 |
+
)
|
456 |
+
file_output = gr.File(label="Download!", visible=False)
|
457 |
+
repo_id = gr.Textbox(
|
458 |
+
label="Hugging Face Repo ID",
|
459 |
+
placeholder="your-username/your-repo-name",
|
460 |
+
)
|
461 |
+
is_public_repo = gr.Checkbox(
|
462 |
+
label="Make Repository Public", value=False
|
463 |
+
)
|
464 |
+
push_button = gr.Button(
|
465 |
+
"Push to Hugging Face", interactive=False, elem_classes="btn"
|
466 |
+
)
|
467 |
+
gr.Markdown(
|
468 |
+
"### Sample Output",
|
469 |
+
)
|
470 |
+
dataset = (
|
471 |
+
load_dataset("Intel/polite-guard", split="validation")
|
472 |
+
.to_pandas()
|
473 |
+
.sample(n=5)
|
474 |
+
)
|
475 |
+
# df_demo = pd.read_csv("samples.csv").head()
|
476 |
+
dataframe = gr.Dataframe(value=dataset, show_label=False)
|
477 |
+
|
478 |
+
state = gr.State({"output_path": None, "timestamp": None})
|
479 |
+
|
480 |
+
def toggle_button(
|
481 |
+
token_value: str,
|
482 |
+
label_value: List[Dict[str, str]],
|
483 |
+
category_value: List[Dict[str, str]],
|
484 |
+
use_case_value: str,
|
485 |
+
example_value: str,
|
486 |
+
) -> Dict[str, Any]:
|
487 |
+
"""
|
488 |
+
Toggles the interactivity of the generate button based on input values.
|
489 |
+
|
490 |
+
Args:
|
491 |
+
token_value (str): The Hugging Face token value.
|
492 |
+
label_value (List[Dict[str, str]]): A list of label description dictionaries.
|
493 |
+
category_value (List[Dict[str, str]]): A list of category and type dictionaries.
|
494 |
+
use_case_value (str): A string for the use case description.
|
495 |
+
example_value (str): A string for prompt examples.
|
496 |
+
|
497 |
+
Returns:
|
498 |
+
Dict[str, Any]: A dictionary containing the updated interactivity state of the generate button.
|
499 |
+
"""
|
500 |
+
return gr.update(
|
501 |
+
interactive=all(
|
502 |
+
[
|
503 |
+
token_value,
|
504 |
+
label_value,
|
505 |
+
category_value,
|
506 |
+
use_case_value,
|
507 |
+
example_value,
|
508 |
+
]
|
509 |
+
)
|
510 |
+
)
|
511 |
+
|
512 |
+
token.change(
|
513 |
+
toggle_button,
|
514 |
+
inputs=[token, label_boxes, category_boxes, use_case, prompt_examples],
|
515 |
+
outputs=generate_button,
|
516 |
+
)
|
517 |
+
label_boxes.change(
|
518 |
+
toggle_button,
|
519 |
+
inputs=[token, label_boxes, category_boxes, use_case, prompt_examples],
|
520 |
+
outputs=generate_button,
|
521 |
+
)
|
522 |
+
category_boxes.change(
|
523 |
+
toggle_button,
|
524 |
+
inputs=[token, label_boxes, category_boxes, use_case, prompt_examples],
|
525 |
+
outputs=generate_button,
|
526 |
+
)
|
527 |
+
use_case.change(
|
528 |
+
toggle_button,
|
529 |
+
inputs=[token, label_boxes, category_boxes, use_case, prompt_examples],
|
530 |
+
outputs=generate_button,
|
531 |
+
)
|
532 |
+
prompt_examples.change(
|
533 |
+
toggle_button,
|
534 |
+
inputs=[token, label_boxes, category_boxes, use_case, prompt_examples],
|
535 |
+
outputs=generate_button,
|
536 |
+
)
|
537 |
+
|
538 |
+
def enable_buttons(state: Dict[str, Any]) -> List[Any]:
|
539 |
+
"""
|
540 |
+
Enables the interactivity of the download and push buttons and loads a preview of the generated data.
|
541 |
+
|
542 |
+
Args:
|
543 |
+
state (Dict[str, Any]): The application state containing the output file path.
|
544 |
+
|
545 |
+
Returns:
|
546 |
+
List[Any]: A list containing:
|
547 |
+
- An update to make the download button interactive.
|
548 |
+
- An update to make the push button interactive.
|
549 |
+
- A DataFrame preview of the generated data.
|
550 |
+
"""
|
551 |
+
df = pd.read_csv(state["output_path"]).head()
|
552 |
+
return [gr.update(interactive=True), gr.update(interactive=True), df]
|
553 |
+
|
554 |
+
generate_button.click(
|
555 |
+
run_sdg,
|
556 |
+
inputs=[
|
557 |
+
sample_size,
|
558 |
+
model,
|
559 |
+
max_new_tokens,
|
560 |
+
save_reasoning,
|
561 |
+
token,
|
562 |
+
state,
|
563 |
+
label_boxes,
|
564 |
+
use_case,
|
565 |
+
prompt_examples,
|
566 |
+
category_boxes,
|
567 |
+
],
|
568 |
+
outputs=[status, state],
|
569 |
+
).success(
|
570 |
+
enable_buttons,
|
571 |
+
inputs=[state],
|
572 |
+
outputs=[download_button, push_button, dataframe],
|
573 |
+
)
|
574 |
+
|
575 |
+
def download_csv(state: Dict) -> str:
|
576 |
+
"""
|
577 |
+
Generate the file path for downloading a CSV file.
|
578 |
+
|
579 |
+
Args:
|
580 |
+
state (Dict): The application state.
|
581 |
+
|
582 |
+
Returns:
|
583 |
+
str: The file path to the CSV file for download.
|
584 |
+
"""
|
585 |
+
return state[
|
586 |
+
"output_path"
|
587 |
+
] # Return the file path to trigger the download
|
588 |
+
|
589 |
+
def push_to_huggingface(
|
590 |
+
repo_id: str,
|
591 |
+
token_value: str,
|
592 |
+
is_public: bool,
|
593 |
+
state: Dict,
|
594 |
+
) -> str:
|
595 |
+
"""
|
596 |
+
Pushes the generated synthetic data file to the Hugging Face Hub.
|
597 |
+
|
598 |
+
Args:
|
599 |
+
repo_id (str): The ID of the Hugging Face repository (e.g., "username/repo-name").
|
600 |
+
token_value (str): The Hugging Face token for authentication.
|
601 |
+
is_public (bool): Whether to make the repository public.
|
602 |
+
state (Dict): The application state containing the output file path and timestamp.
|
603 |
+
|
604 |
+
Returns:
|
605 |
+
str: A message indicating the result of the upload process.
|
606 |
+
"""
|
607 |
+
try:
|
608 |
+
api = HfApi(token=token_value)
|
609 |
+
except Exception as e:
|
610 |
+
return f"Invalid token for writing to Hugging Face: {e}"
|
611 |
+
|
612 |
+
try:
|
613 |
+
# Ensure the repository exists, creating it if it doesn't
|
614 |
+
api.create_repo(
|
615 |
+
repo_id=repo_id,
|
616 |
+
repo_type="dataset",
|
617 |
+
exist_ok=True,
|
618 |
+
private=not is_public,
|
619 |
+
)
|
620 |
+
|
621 |
+
api.upload_file(
|
622 |
+
path_or_fileobj=state["output_path"],
|
623 |
+
path_in_repo=f"{state['timestamp']}.csv",
|
624 |
+
repo_id=repo_id,
|
625 |
+
repo_type="dataset",
|
626 |
+
)
|
627 |
+
except Exception as e:
|
628 |
+
return f"Error uploading file to Hugging Face: {e}"
|
629 |
+
visibility = "public" if is_public else "private"
|
630 |
+
return f"File pushed to {visibility} Hugging Face Hub at {repo_id}/{state['timestamp']}.csv"
|
631 |
+
|
632 |
+
download_button.click(download_csv, inputs=state, outputs=file_output).then(
|
633 |
+
lambda: gr.update(visible=True), outputs=file_output
|
634 |
+
)
|
635 |
+
|
636 |
+
push_button.click(
|
637 |
+
push_to_huggingface,
|
638 |
+
inputs=[repo_id, token, is_public_repo, state],
|
639 |
+
outputs=status,
|
640 |
+
)
|
641 |
+
|
642 |
+
with gr.Tab("About"):
|
643 |
+
with gr.Row():
|
644 |
+
with gr.Column(scale=1):
|
645 |
+
gr.Image(
|
646 |
+
"polite-guard.png",
|
647 |
+
show_download_button=False,
|
648 |
+
show_fullscreen_button=False,
|
649 |
+
show_label=False,
|
650 |
+
show_share_button=False,
|
651 |
+
container=False,
|
652 |
+
)
|
653 |
+
with gr.Column(scale=3):
|
654 |
+
gr.Markdown(
|
655 |
+
"""
|
656 |
+
This synthetic data generator, distributed with Intel's [Polite Guard](https://huggingface.co/Intel/polite-guard) project, uses a specified language model to generate synthetic data for a given use case.
|
657 |
+
If you find this project valuable, please consider giving it a ❤️ on Hugging Face and sharing it with your network.
|
658 |
+
Visit
|
659 |
+
- [Polite Guard GitHub repository](https://github.com/intel/polite-guard) for the source code that you can run through the command line,
|
660 |
+
- [Synthetic Data Generation with Language Models: A Practical Guide](https://medium.com/p/0ff98eb226a1) to learn more about the implementation of this data generator, and
|
661 |
+
- [Polite Guard Dataset](https://huggingface.co/datasets/Intel/polite-guard) for an example of a dataset generated using this data generator.
|
662 |
+
|
663 |
+
## Privacy Notice
|
664 |
+
Please note that this data generator uses AI technology and you are interacting with a chat model.
|
665 |
+
Prompts that are being used during the demo and your personal information will not be stored.
|
666 |
+
For information regarding the handling of personal data collected refer to the Global Privacy Notice (https://www.intel.com/content/www/us/en/privacy/intelprivacy-notice.html), which encompass our privacy practices.
|
667 |
+
"""
|
668 |
+
)
|
669 |
+
|
670 |
+
demo.launch()
|
671 |
+
|
672 |
+
|
673 |
+
if __name__ == "__main__":
|
674 |
+
main()
|