Strictly adhere to PEP-8 standards, ensuring code is clean, well-structured, and follows Python's style guide for readability.
Use appropriate modules like typing for type hints, ensuring code clarity, maintainability, and leveraging Python's standard libraries effectively.
Focus on time, space, robustness, scalability; write optimized, efficient code that can handle large datasets and scale seamlessly.
Implement comprehensive error handling, catching exceptions gracefully, providing meaningful error messages, and ensuring code robustness under unexpected conditions.
Ensure the developer agent writes advanced, maintainable Python code, balancing performance and readability while adhering to best practices.
TASK :using ploty module we have develop advanced code , row each content very long 1024 to 128k , but should visualization with first 300 words or 450 words user control , scatter plots , titele, legends, labels, coluring etc very professionaly look
import sys
from typing import List, Dict, Union, Optional
import pandas as pd
import plotly.express as px
from datasets import DatasetDict, Dataset
from plotly.graph_objs import Figure
def truncate_text(text: str, word_limit: int) -> str:
"""
Truncate the input text to the specified number of words.
Args:
text (str): The original text to be truncated.
word_limit (int): The maximum number of words to include in the truncated text.
Returns:
str: The truncated text.
"""
try:
words = text.split()
truncated = ' '.join(words[:word_limit])
return truncated
except Exception as e:
print(f"Error truncating text: {e}", file=sys.stderr)
return text # Return original text if error occurs
def prepare_dataframe(dataset_dict: DatasetDict, word_limit: int) -> pd.DataFrame:
"""
Prepare a Pandas DataFrame from the DatasetDict, truncating the 'prompt' text.
Args:
dataset_dict (DatasetDict): The dataset dictionary containing 'train' and 'test' datasets.
word_limit (int): The maximum number of words to include in the 'prompt' text.
Returns:
pd.DataFrame: The prepared DataFrame ready for visualization.
"""
try:
# Combine train and test datasets
combined_dataset = dataset_dict['train'].select(range(len(dataset_dict['train'])))
combined_dataset = combined_dataset.add_item(dataset_dict['test'])
# Convert to Pandas DataFrame
df = combined_dataset.to_pandas()
# Truncate 'prompt' text
df['truncated_prompt'] = df['prompt'].apply(lambda x: truncate_text(x, word_limit))
return df
except Exception as e:
print(f"Error preparing DataFrame: {e}", file=sys.stderr)
raise
def create_scatter_plot(df: pd.DataFrame) -> Figure:
"""
Create a scatter plot using Plotly from the provided DataFrame.
Args:
df (pd.DataFrame): The DataFrame containing the data to plot.
Returns:
plotly.graph_objs.Figure: The Plotly figure object.
"""
try:
fig = px.scatter(
df,
x='act',
y='truncated_prompt',
color='act',
title='Scatter Plot of Acts vs Truncated Prompts',
labels={
'act': 'Action',
'truncated_prompt': 'Truncated Prompt'
}
)
fig.update_layout(legend_title='Action Types')
return fig
except Exception as e:
print(f"Error creating scatter plot: {e}", file=sys.stderr)
raise
def visualize_dataset(
dataset_dict: DatasetDict,
word_limit: int = 300,
output_file: Optional[str] = None
) -> None:
"""
Visualize the dataset by creating a scatter plot of the 'act' vs the truncated 'prompt'.
Args:
dataset_dict (DatasetDict): The dataset dictionary containing 'train' and 'test' datasets.
word_limit (int, optional): The maximum number of words to include in the 'prompt' text. Defaults to 300.
output_file (Optional[str], optional): The path to save the plotly figure. If None, the plot is shown. Defaults to None.
"""
try:
df = prepare_dataframe(dataset_dict, word_limit)
fig = create_scatter_plot(df)
if output_file:
fig.write_html(output_file)
print(f"Scatter plot saved to {output_file}")
else:
fig.show()
except Exception as e:
print(f"Error visualizing dataset: {e}", file=sys.stderr)
if __name__ == '__main__':
# Example usage
try:
# Assuming 'dataset_dict' is provided as per the given output
dataset_dict = DatasetDict({
'train': Dataset.from_dict({
'act': ['action1'] * 170,
'prompt': [' '.join(['word'] * 1024)] * 170
}),
'test': Dataset.from_dict({
'act': ['action2'] * 170,
'prompt': [' '.join(['word'] * 1024)] * 170
})
})
# User can control the word limit here
word_limit_input = input("Enter the word limit for truncating prompts (e.g., 300 or 450): ")
word_limit = int(word_limit_input)
visualize_dataset(dataset_dict, word_limit)
except Exception as e:
print(f"An error occurred: {e}", file=sys.stderr)
This script performs the following steps:
Truncate the Text: The truncate_text function truncates each 'prompt' to the specified number of words (word_limit), ensuring that the visualization remains clear and manageable even with very long texts.
Prepare the DataFrame: The prepare_dataframe function combines the 'train' and 'test' datasets from the DatasetDict, applies the text truncation, and converts the data into a Pandas DataFrame for easier manipulation.
Create the Scatter Plot: The create_scatter_plot function generates a scatter plot using Plotly Express, with appropriate titles, legends, and labels for a professional appearance.
Visualization Function: The visualize_dataset function orchestrates the preparation and visualization steps, handling optional output saving.
Main Execution Block: The script includes a main execution block that allows for interactive input of the word limit and demonstrates how the functions can be combined.
Key Features of the Code:
PEP-8 Compliance: The code follows Python's style guide, ensuring readability and maintainability.
Type Hints: All functions include type hints using the typing module, aiding in code clarity and potential static analysis.
Error Handling: Comprehensive try-except blocks capture exceptions, providing meaningful error messages and preventing the script from crashing unexpectedly.
Scalability and Efficiency: By truncating texts and efficiently handling data with Pandas and Plotly, the code is designed to work smoothly even with large datasets.
User Control: The script allows users to specify the word limit for truncating texts, offering flexibility in how much content is displayed.
Instructions to Run the Script:
Ensure you have the required packages installed:
bash
pip install pandas plotly datasets
Run the script in an environment where you can display Plotly figures, such as Jupyter Notebook or a Python script with an interactive output.
When prompted, enter the desired word limit for truncating the 'prompt' text.
The scatter plot will be displayed, or you can modify the visualize_dataset function call to save the plot by providing an output_file path.
Note: Replace the placeholder data in the dataset_dict with your actual data as needed.
This code provides a solid foundation for visualizing large text datasets professionally while maintaining performance and readability standards.