Spaces:
Running
Running
File size: 13,010 Bytes
fb1a11c 939f6ae e62a0e5 939f6ae 7f6f34c e62a0e5 fb1a11c e62a0e5 aa1bdb0 ba1088f aa1bdb0 e62a0e5 4dc6cd8 e62a0e5 4dc6cd8 e62a0e5 aa1bdb0 e62a0e5 aa1bdb0 e62a0e5 4dc6cd8 e62a0e5 4dc6cd8 e62a0e5 4dc6cd8 e62a0e5 4dc6cd8 e62a0e5 4dc6cd8 e62a0e5 4dc6cd8 e62a0e5 939f6ae e62a0e5 4dc6cd8 939f6ae 4dc6cd8 939f6ae 4dc6cd8 939f6ae 4dc6cd8 939f6ae 4dc6cd8 e62a0e5 ba1088f 117da13 ba1088f 117da13 ba1088f e62a0e5 ba1088f e62a0e5 ba1088f d97974e 117da13 ba1088f 117da13 ba1088f e62a0e5 ba1088f 117da13 ba1088f e62a0e5 ba1088f e62a0e5 ba1088f e62a0e5 ba1088f 117da13 ba1088f 117da13 ba1088f e62a0e5 ba1088f e62a0e5 fb1a11c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 |
import os
import json
def replace_wildcards(
templates, wildcards, replacements, has_numeric_columns, has_categoric_columns
):
if len(wildcards) != len(replacements):
raise ValueError(
"The number of wildcards must match the number of replacements."
)
new_templates = []
for tmp in templates:
if "type" in tmp and tmp["type"] == "numeric" and not has_numeric_columns:
continue
if "type" in tmp and tmp["type"] == "categoric" and not has_categoric_columns:
continue
tmp_text = tmp["source"].strip()
for wildcard, replacement in zip(wildcards, replacements):
tmp_text = tmp_text.replace(wildcard, replacement)
new_templates.append({"cell_type": tmp["cell_type"], "source": tmp_text})
return new_templates
embeddings_cells = [
{
"cell_type": "markdown",
"source": """
---
# **Embeddings Notebook for {dataset_name} dataset**
---
""",
},
{
"cell_type": "markdown",
"source": "## 1. Setup necessary libraries and load the dataset",
},
{
"cell_type": "code",
"source": """
# Install and import necessary libraries.
!pip install pandas sentence-transformers faiss-cpu
""",
},
{
"cell_type": "code",
"source": """
import pandas as pd
from sentence_transformers import SentenceTransformer
import faiss
""",
},
{
"cell_type": "code",
"source": """
# Load the dataset as a DataFrame
{first_code}
""",
},
{
"cell_type": "code",
"source": """
# Specify the column name that contains the text data to generate embeddings
column_to_generate_embeddings = '{longest_col}'
""",
},
{
"cell_type": "markdown",
"source": "## 2. Loading embedding model and creating FAISS index",
},
{
"cell_type": "code",
"source": """
# Remove duplicate entries based on the specified column
df = df.drop_duplicates(subset=column_to_generate_embeddings)
""",
},
{
"cell_type": "code",
"source": """
# Convert the column data to a list of text entries
text_list = df[column_to_generate_embeddings].tolist()
""",
},
{
"cell_type": "code",
"source": """
# Specify the embedding model you want to use
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
""",
},
{
"cell_type": "code",
"source": """
vectors = model.encode(text_list)
vector_dimension = vectors.shape[1]
# Initialize the FAISS index with the appropriate dimension (384 for this model)
index = faiss.IndexFlatL2(vector_dimension)
# Encode the text list into embeddings and add them to the FAISS index
index.add(vectors)
""",
},
{
"cell_type": "markdown",
"source": "## 3. Perform a text search",
},
{
"cell_type": "code",
"source": """
# Specify the text you want to search for in the list
text_to_search = text_list[0]
print(f"Text to search: {text_to_search}")
""",
},
{
"cell_type": "code",
"source": """
# Generate the embedding for the search query
query_embedding = model.encode([text_to_search])
""",
},
{
"cell_type": "code",
"source": """
# Perform the search to find the 'k' nearest neighbors (adjust 'k' as needed)
D, I = index.search(query_embedding, k=10)
# Print the similar documents found
print(f"Similar documents: {[text_list[i] for i in I[0]]}")
""",
},
]
eda_cells = [
{
"cell_type": "markdown",
"source": """
---
# **Exploratory Data Analysis (EDA) Notebook for {dataset_name} dataset**
---
""",
},
{
"cell_type": "markdown",
"source": "## 1. Setup necessary libraries and load the dataset",
},
{
"cell_type": "code",
"source": """
# Install and import necessary libraries.
!pip install pandas matplotlib seaborn
""",
},
{
"cell_type": "code",
"source": """
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
""",
},
{
"cell_type": "code",
"source": """
# Load the dataset as a DataFrame
{first_code}
""",
},
{
"cell_type": "markdown",
"source": "## 2. Understanding the Dataset",
},
{
"cell_type": "code",
"source": """
# First rows of the dataset and info
print(df.head())
print(df.info())
""",
},
{
"cell_type": "code",
"source": """
# Check for missing values
print(df.isnull().sum())
""",
},
{
"cell_type": "code",
"source": """
# Identify data types of each column
print(df.dtypes)
""",
},
{
"cell_type": "code",
"source": """
# Detect duplicated rows
print(df.duplicated().sum())
""",
},
{
"cell_type": "code",
"source": """
# Generate descriptive statistics
print(df.describe())
""",
},
{
"type": "categoric",
"cell_type": "code",
"source": """
# Unique values in categorical columns
df.select_dtypes(include=['object']).nunique()
""",
},
{
"cell_type": "markdown",
"source": "## 3. Data Visualization",
},
{
"type": "numeric",
"cell_type": "code",
"source": """
# Correlation matrix for numerical columns
corr_matrix = df.corr(numeric_only=True)
plt.figure(figsize=(10, 8))
sns.heatmap(corr_matrix, annot=True, fmt='.2f', cmap='coolwarm', square=True)
plt.title('Correlation Matrix')
plt.show()
""",
},
{
"type": "numeric",
"cell_type": "code",
"source": """
# Distribution plots for numerical columns
for column in df.select_dtypes(include=['int64', 'float64']).columns:
plt.figure(figsize=(8, 4))
sns.histplot(df[column], kde=True)
plt.title(f'Distribution of {column}')
plt.xlabel(column)
plt.ylabel('Frequency')
plt.show()
""",
},
{
"type": "categoric",
"cell_type": "code",
"source": """
# Count plots for categorical columns
for column in df.select_dtypes(include=['object']).columns:
plt.figure(figsize=(8, 4))
sns.countplot(x=column, data=df)
plt.title(f'Count Plot of {column}')
plt.xlabel(column)
plt.ylabel('Count')
plt.show()
""",
},
{
"type": "numeric",
"cell_type": "code",
"source": """
# Box plots for detecting outliers in numerical columns
for column in df.select_dtypes(include=['int64', 'float64']).columns:
plt.figure(figsize=(8, 4))
sns.boxplot(df[column])
plt.title(f'Box Plot of {column}')
plt.xlabel(column)
plt.show()
""",
},
]
rag_cells = [
{
"cell_type": "markdown",
"source": """
---
# **Retrieval-Augmented Generation Notebook for {dataset_name} dataset**
---
""",
},
{
"cell_type": "markdown",
"source": "## 1. Setup necessary libraries and load the dataset",
},
{
"cell_type": "code",
"source": """
# Install and import necessary libraries.
!pip install pandas sentence-transformers faiss-cpu transformers torch huggingface_hub
""",
},
{
"cell_type": "code",
"source": """
from sentence_transformers import SentenceTransformer
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
from huggingface_hub import InferenceClient
import pandas as pd
import faiss
import torch
""",
},
{
"cell_type": "code",
"source": """
# Load the dataset as a DataFrame
{first_code}
""",
},
{
"cell_type": "code",
"source": """
# Specify the column name that contains the text data to generate embeddings
column_to_generate_embeddings = '{longest_col}'
""",
},
{
"cell_type": "markdown",
"source": "## 2. Loading embedding model and creating FAISS index",
},
{
"cell_type": "code",
"source": """
# Remove duplicate entries based on the specified column
df = df.drop_duplicates(subset=column_to_generate_embeddings)
""",
},
{
"cell_type": "code",
"source": """
# Convert the column data to a list of text entries
text_list = df[column_to_generate_embeddings].tolist()
""",
},
{
"cell_type": "code",
"source": """
# Specify the embedding model you want to use
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
""",
},
{
"cell_type": "code",
"source": """
vectors = model.encode(text_list)
vector_dimension = vectors.shape[1]
# Initialize the FAISS index with the appropriate dimension (384 for this model)
index = faiss.IndexFlatL2(vector_dimension)
# Encode the text list into embeddings and add them to the FAISS index
index.add(vectors)
""",
},
{
"cell_type": "markdown",
"source": "## 3. Perform a text search",
},
{
"cell_type": "code",
"source": """
# Specify the text you want to search for in the list
query = "How to cook sushi?"
# Generate the embedding for the search query
query_embedding = model.encode([query])
""",
},
{
"cell_type": "code",
"source": """
# Perform the search to find the 'k' nearest neighbors (adjust 'k' as needed)
D, I = index.search(query_embedding, k=10)
# Print the similar documents found
print(f"Similar documents: {[text_list[i] for i in I[0]]}")
""",
},
{
"cell_type": "markdown",
"source": "## 4. Load pipeline and perform inference locally",
},
{
"cell_type": "code",
"source": """
# Adjust model name as needed
checkpoint = 'HuggingFaceTB/SmolLM-1.7B-Instruct'
device = "cuda" if torch.cuda.is_available() else "cpu" # for GPU usage or "cpu" for CPU usage
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
model = AutoModelForCausalLM.from_pretrained(checkpoint).to(device)
generator = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0 if device == "cuda" else -1)
""",
},
{
"cell_type": "code",
"source": """
# Create a prompt with two parts: 'system' for instructions based on a 'context' from the retrieved documents, and 'user' for the query
selected_elements = [text_list[i] for i in I[0].tolist()]
context = ','.join(selected_elements)
messages = [
{
"role": "system",
"content": f"You are an intelligent assistant tasked with providing accurate and concise answers based on the following context. Use the information retrieved to construct your response. Context: {context}",
},
{"role": "user", "content": query},
]
""",
},
{
"cell_type": "code",
"source": """
# Send the prompt to the pipeline and show the answer
output = generator(messages)
print("Generated result:")
print(output[0]['generated_text'][-1]['content']) # Print the assistant's response content
""",
},
{
"cell_type": "markdown",
"source": "## 5. Alternatively call the inference client",
},
{
"cell_type": "code",
"source": """
# Adjust model name as needed
checkpoint = "meta-llama/Meta-Llama-3-8B-Instruct"
# Change here your Hugging Face API token
token = "hf_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
inference_client = InferenceClient(checkpoint, token=token)
output = inference_client.chat_completion(messages=messages, stream=False)
print("Generated result:")
print(output.choices[0].message.content)
""",
},
]
def generate_rag_system_prompt():
"""
1. Install necessary libraries.
2. Import libraries.
3. Load the dataset as a DataFrame using the provided code.
4. Select the column for generating embeddings.
5. Remove duplicate data.
6. Convert the selected column to a list.
7. Load the sentence-transformers model.
8. Create a FAISS index.
9. Encode a query sample.
10. Search for similar documents using the FAISS index.
11. Load the 'HuggingFaceH4/zephyr-7b-beta' model from the transformers library and create a pipeline.
12. Create a prompt with two parts: 'system' for instructions based on a 'context' from the retrieved documents, and 'user' for the query.
13. Send the prompt to the pipeline and display the answer.
Ensure the notebook is well-organized with explanations for each step.
The output should be Markdown content with Python code snippets enclosed in "```python" and "```".
The user will provide the dataset information in the following format:
## Columns and Data Types
## Sample Data
## Loading Data code
Use the provided code to load the dataset; do not use any other method.
"""
def load_json_files_from_folder(folder_path):
components = {}
for filename in os.listdir(folder_path):
if filename.endswith(".json"):
file_path = os.path.join(folder_path, filename)
with open(file_path, "r") as json_file:
data = json.load(json_file)
components[data["notebook_title"]] = data
return components
|