Spaces:
Runtime error
Runtime error
Reverted to docs way for dataset upload
Browse files50 unmodified lines5152535455565758596061626364656667686970717273747576772 unmodified lines80818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531 unmodified line15515615715815916016150 unmodified linesreturn f"Error using Sonar Websearch tool '{arg1} {arg2}': {str(e)}"def Dataset_Creator_Function(dataset_name: str, username: str, conversation_data: str) -> str:"""Creates and pushes a dataset to Hugging Face with the conversation history.Args:dataset_name: Name for the datasetusername: Default is "Misfits-and-Machines"conversation_data: String representing the conversation dataReturns:URL of the created dataset or error message"""try:import tempfileimport pathlibfrom datasets import Dataset, DatasetDictimport pandas as pd# Get API key from environment variablesapi_key = os.getenv("HF_API_KEY")if not api_key:return "Error: No Hugging Face API key found in environment variables. Please set HF_API_KEY or HUGGINGFACE_API_KEY."# Initialize Hugging Face APIhf_api = HfApi(token=api_key)2 unmodified linessafe_dataset_name = dataset_name.replace(" ", "_").lower()repo_id = f"{username}/{safe_dataset_name}"print(f"Creating dataset repository: {repo_id}")# Create a temporary directory to store the dataset fileswith tempfile.TemporaryDirectory() as tmp_dir:# Convert data to DataFrame and save as CSVdf = pd.DataFrame({"text": [conversation_data],"timestamp": [datetime.datetime.now().isoformat()],"dataset_id": [str(uuid.uuid4())]})# Save CSV in the temp directorycsv_path = pathlib.Path(tmp_dir) / "train.csv"df.to_csv(csv_path, index=False)print(f"Data saved to temporary CSV file: {csv_path}")# Load from CSV to ensure proper dataset structuretrain_dataset = Dataset.from_pandas(df)# Create a DatasetDict with a train splitdataset_dict = DatasetDict({"train": train_dataset})print(f"Created dataset with {len(train_dataset)} rows")# Create the repository explicitly if it doesn't existtry:if not hf_api.repo_exists(repo_id=repo_id, repo_type="dataset"):hf_api.create_repo(repo_id=repo_id, repo_type="dataset")print(f"Repository {repo_id} created")else:print(f"Repository {repo_id} already exists")except Exception as repo_error:print(f"Repository creation error: {str(repo_error)}")# Push to Hugging Face Hubprint(f"Pushing dataset to {repo_id}")# Use the DatasetDict push_to_hub methoddataset_dict.push_to_hub(repo_id=repo_id,token=api_key,private=False)dataset_url = f"https://huggingface.co/datasets/{repo_id}"print(f"Dataset successfully pushed to: {dataset_url}")# Double-check that the repo existsif hf_api.repo_exists(repo_id=repo_id, repo_type="dataset"):print(f"Verified: Repository {repo_id} exists")else:print(f"Warning: Repository {repo_id} not found after push")return f"Successfully created dataset at {dataset_url}"except Exception as e:import tracebackerror_trace = traceback.format_exc()print(f"Dataset creation error: {str(e)}\n{error_trace}")return f"Error creating dataset: {str(e)}\n\nTo troubleshoot:\n1. Verify API key is valid\n2. Try with a different dataset name"@tooldef Dataset_Creator_Tool(dataset_name: str, username: str, conversation_data: str) -> str:"""A tool that posts a new dataset of the current conversation to Hugging Face.Args:dataset_name: Name for the datasetusername: (Default should be 'Misfits-and-Machines/')conversation_data: String content to save to the dataset (no JSON conversion needed)Returns:Link to the created dataset or error message with troubleshooting steps1 unmodified linetry:print(f"Creating dataset '{dataset_name}' with {len(conversation_data)} characters of data")print(f"Dataset will be created at Misfits-and-Machines/{dataset_name.replace(' ', '_').lower()}")result = Dataset_Creator_Function(dataset_name, username, conversation_data)print(f"Dataset creation result: {result}")return resultexcept Exception as e:50 unmodified lines5152535455565758596061626364656667686970717273742 unmodified lines77787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191 unmodified line12112212312412512612750 unmodified linesreturn f"Error using Sonar Websearch tool '{arg1} {arg2}': {str(e)}"def Dataset_Creator_Function(dataset_name: str, conversation_data: str) -> str:"""Creates and pushes a dataset to Hugging Face with the conversation history.Args:dataset_name: Name for the dataset (will be prefixed with username)conversation_data: String representing the conversation dataReturns:URL of the created dataset or error message"""try:# Get API key from environment variablesapi_key = os.getenv("HF_API_KEY") or os.getenv("HUGGINGFACE_API_KEY")if not api_key:return "Error: No Hugging Face API key found in environment variables"# Set fixed username for dataset organizationusername = "Misfits-and-Machines"# Initialize Hugging Face APIhf_api = HfApi(token=api_key)2 unmodified linessafe_dataset_name = dataset_name.replace(" ", "_").lower()repo_id = f"{username}/{safe_dataset_name}"print(f"Creating dataset: {repo_id}")# Create a simple dataset from a dictionarydata = {"text": [conversation_data],"timestamp": [datetime.datetime.now().isoformat()],"id": [str(uuid.uuid4())]}# Create the dataset directlydataset = Dataset.from_dict(data)# Push to Hugging Face Hub using the simpler method from documentationdataset.push_to_hub(repo_id=repo_id, # Include username in repo_idtoken=api_key, # Pass token explicitlyprivate=False # Make it public)# Generate the URL for the datasetdataset_url = f"https://huggingface.co/datasets/{repo_id}"print(f"Dataset successfully pushed to: {dataset_url}")return f"Successfully created dataset at {dataset_url}"except Exception as e:import tracebackerror_trace = traceback.format_exc()print(f"Dataset creation error: {str(e)}\n{error_trace}")return f"Error creating dataset: {str(e)}\n\nTroubleshooting tips:\n1. Verify your HF_API_KEY is valid\n2. Try a simpler dataset name with only letters and underscores\n3. Check your permissions for the Misfits-and-Machines organization"@tooldef Dataset_Creator_Tool(dataset_name: str, conversation_data: str) -> str:"""A tool that posts a new dataset of the current conversation to Hugging Face.Args:dataset_name: Name for the dataset (will be prefixed with 'Misfits-and-Machines/')conversation_data: String content to save to the datasetReturns:Link to the created dataset or error message with troubleshooting steps1 unmodified linetry:print(f"Creating dataset '{dataset_name}' with {len(conversation_data)} characters of data")print(f"Dataset will be created at Misfits-and-Machines/{dataset_name.replace(' ', '_').lower()}")result = Dataset_Creator_Function(dataset_name, conversation_data)print(f"Dataset creation result: {result}")return resultexcept Exception as e:
app.py+35-69