nastasiasnk commited on
Commit
98eefd8
1 Parent(s): f6b4e6d

Upload 2 files

Browse files
Files changed (2) hide show
  1. data_utils.py +616 -0
  2. speckle_utils.py +656 -0
data_utils.py ADDED
@@ -0,0 +1,616 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import pandas as pd
3
+ import numpy as np
4
+ import copy
5
+ import os
6
+ import csv
7
+ import io
8
+ import json
9
+ import requests
10
+
11
+ try:
12
+ from fuzzywuzzy import fuzz
13
+ except:
14
+ pass
15
+
16
+ def helper():
17
+ """
18
+ Prints out the help message for this module.
19
+ """
20
+ print("This module contains a set of utility functions for data processing.")
21
+ print("______________________________________________________________________")
22
+ print("for detailed help call >>> help(speckle_utils.function_name) <<< ")
23
+ print("______________________________________________________________________")
24
+ print("available functions:")
25
+ print("cleanData(data, mode='drop', num_only=False) -> clean dataframes, series or numpy arrays" )
26
+ print( """ sort_and_match_df(A, B, uuid_column) -> merges two dataframes by a common uuid comon (best practice: always use this)""")
27
+ print("transform_to_score(data, minPts, maxPts, t_low, t_high, cull_invalid=False) -> transform data to a score based on percentiles and provided points")
28
+ print("colab_create_directory(base_name) -> create a directory with the given name, if it already exists, add a number to the end of the name, usefull for colab")
29
+ print("colab_zip_download_folder(dir_name) -> zips and downloads a directory from colab. will only work in google colaboratory ")
30
+
31
+
32
+ def cleanData(data, mode="drop", num_only=False, print_report=True):
33
+ """
34
+ Cleans data by handling missing or null values according to the specified mode.
35
+
36
+ Args:
37
+ data (numpy.ndarray, pandas.DataFrame, pandas.Series): Input data to be cleaned.
38
+ mode (str, optional): Specifies the method to handle missing or null values.
39
+ "drop" drops rows with missing values (default),
40
+ "replace_zero" replaces missing values with zero,
41
+ "replace_mean" replaces missing values with the mean of the column.
42
+ num_only (bool, optional): If True and data is a DataFrame, only numeric columns are kept. Defaults to False.#
43
+ print_report (bool, optional): if True the report is printed to the console. Defaults to True.
44
+
45
+ Returns:
46
+ numpy.ndarray, pandas.DataFrame, pandas.Series: Cleaned data with the same type as the input.
47
+
48
+
49
+ Raises:
50
+ ValueError: If the input data type is not supported (must be numpy.ndarray, pandas.DataFrame or pandas.Series).
51
+
52
+ This function checks the type of the input data and applies the appropriate cleaning operation accordingly.
53
+ It supports pandas DataFrame, pandas Series, and numpy array. For pandas DataFrame, it can optionally
54
+ convert and keep only numeric columns.
55
+ """
56
+ report = {}
57
+ if isinstance(data, pd.DataFrame):
58
+ initial_cols = data.columns.tolist()
59
+ initial_rows = data.shape[0]
60
+ if num_only:
61
+ # attempt casting before doing this selection
62
+ data = data.apply(pd.to_numeric, errors='coerce')
63
+ data = data.select_dtypes(include=['int64', 'float64'])
64
+ report['dropped_cols'] = list(set(initial_cols) - set(data.columns.tolist()))
65
+
66
+ if mode == "drop":
67
+ data = data.dropna()
68
+ report['dropped_rows'] = initial_rows - data.shape[0]
69
+ elif mode=="replace_zero":
70
+ data = data.fillna(0)
71
+ elif mode=="replace_mean":
72
+ data = data.fillna(data.mean())
73
+
74
+ elif isinstance(data, pd.Series):
75
+ initial_length = len(data)
76
+ if mode == "drop":
77
+ data = data.dropna()
78
+ report['dropped_rows'] = initial_length - len(data)
79
+ elif mode=="replace_zero":
80
+ data = data.fillna(0)
81
+ elif mode=="replace_mean":
82
+ data = data.fillna(data.mean())
83
+
84
+ elif isinstance(data, np.ndarray):
85
+ initial_length = data.size
86
+ if mode=="drop":
87
+ data = data[~np.isnan(data)]
88
+ report['dropped_rows'] = initial_length - data.size
89
+ elif mode=="replace_zero":
90
+ data = np.nan_to_num(data, nan=0)
91
+ elif mode=="replace_mean":
92
+ data = np.where(np.isnan(data), np.nanmean(data), data)
93
+
94
+ else:
95
+ raise ValueError("Unsupported data type")
96
+ if print_report:
97
+ print(report)
98
+ return data
99
+
100
+
101
+
102
+ def sort_and_match_df(A, B, uuid_column):
103
+ """
104
+ Sorts and matches DataFrame B to A based on a shared uuid_column.
105
+ Prioritizes uuid_column as an index if present, otherwise uses it as a column.
106
+
107
+ Parameters:
108
+ A, B (DataFrame): Input DataFrames to be sorted and matched.
109
+ uuid_column (str): Shared column/index for matching rows.
110
+
111
+ Returns:
112
+ DataFrame: Resulting DataFrame after left join of A and B on uuid_column.
113
+ """
114
+ if uuid_column in A.columns:
115
+ A = A.set_index(uuid_column, drop=False)
116
+ if uuid_column in B.columns:
117
+ B = B.set_index(uuid_column, drop=False)
118
+
119
+ merged_df = pd.merge(A, B, left_index=True, right_index=True, how='left')
120
+ return merged_df.reset_index(drop=False)
121
+
122
+
123
+ def sort_and_match_dfs(dfs, uuid_column):
124
+ """
125
+ Sorts and matches all DataFrames in list based on a shared uuid_column.
126
+ Prioritizes uuid_column as an index if present, otherwise uses it as a column.
127
+ Raises a warning if any two DataFrames have overlapping column names.
128
+
129
+ Parameters:
130
+ dfs (list): A list of DataFrames to be sorted and matched.
131
+ uuid_column (str): Shared column/index for matching rows.
132
+
133
+ Returns:
134
+ DataFrame: Resulting DataFrame after successive left joins on uuid_column.
135
+ """
136
+ if not dfs:
137
+ raise ValueError("The input list of DataFrames is empty")
138
+
139
+ # Convert uuid_column to index if it's a column
140
+ for i, df in enumerate(dfs):
141
+ if uuid_column in df.columns:
142
+ dfs[i] = df.set_index(uuid_column, drop=False)
143
+
144
+ # Check for overlapping column names
145
+ all_columns = [set(df.columns) for df in dfs]
146
+ for i, columns_i in enumerate(all_columns):
147
+ for j, columns_j in enumerate(all_columns[i+1:], start=i+1):
148
+ overlapping_columns = columns_i.intersection(columns_j) - {uuid_column}
149
+ if overlapping_columns:
150
+ print(f"Warning: DataFrames at indices {i} and {j} have overlapping column(s): {', '.join(overlapping_columns)}")
151
+
152
+ result_df = dfs[0]
153
+ for df in dfs[1:]:
154
+ result_df = pd.merge(result_df, df, left_index=True, right_index=True, how='left')
155
+
156
+ return result_df.reset_index(drop=False)
157
+
158
+
159
+
160
+
161
+ def transform_to_score(data, minPts, maxPts, t_low, t_high, cull_invalid=False):
162
+ """
163
+ Transforms data to a score based on percentiles and provided points.
164
+
165
+ Args:
166
+ data (numpy.array or pandas.Series): Input data to be transformed.
167
+ minPts (float): The minimum points to be assigned.
168
+ maxPts (float): The maximum points to be assigned.
169
+ t_low (float): The lower percentile threshold.
170
+ t_high (float): The upper percentile threshold.
171
+ cull_invalid (bool, optional): If True, invalid data is removed. Defaults to False.
172
+
173
+ Returns:
174
+ numpy.array: The transformed data, where each element has been converted to a score based on its percentile rank.
175
+
176
+ This function calculates the t_low and t_high percentiles of the input data, and uses linear interpolation
177
+ to transform each data point to a score between minPts and maxPts. Any data point that falls above the t_high
178
+ percentile is given a score of maxPts. If cull_invalid is True, any invalid data points (such as NaNs or
179
+ infinite values) are removed before the transformation is applied.
180
+ """
181
+
182
+ # If cull_invalid is True, the data is cleaned and invalid data is removed.
183
+ if cull_invalid:
184
+ inp_data = cleanData(inp_data, mode="drop", num_only=True)
185
+
186
+ # Calculate the percentile values based on the data
187
+ percentile_low = np.percentile(data, t_low)
188
+ percentile_high = np.percentile(data, t_high)
189
+
190
+ # Create a copy of the data to store the transformed points
191
+ transformed_data = data.copy()
192
+
193
+ # Apply linear interpolation between minPts and maxPts
194
+ transformed_data = np.interp(transformed_data, [percentile_low, percentile_high], [minPts, maxPts])
195
+
196
+ # Replace values above the percentile threshold with maxPts
197
+ transformed_data[transformed_data >= percentile_high] = maxPts
198
+
199
+ return transformed_data
200
+
201
+
202
+ def colab_create_directory(base_name):
203
+ """ creates a directory with the given name, if it already exists, add a number to the end of the name.
204
+ Usefull for colab to batch save e.g. images and avoid overwriting.
205
+ Args:
206
+ base_name (str): name of the directory to create
207
+ Returns:
208
+ str: name of the created directory"""
209
+ counter = 1
210
+ dir_name = base_name
211
+
212
+ while os.path.exists(dir_name):
213
+ dir_name = f"{base_name}_{counter}"
214
+ counter += 1
215
+
216
+ os.mkdir(dir_name)
217
+ return dir_name
218
+
219
+ def smart_round(x):
220
+ if abs(x) >= 1000:
221
+ return round(x)
222
+ elif abs(x) >= 10:
223
+ return round(x, 1)
224
+ elif abs(x) >= 1:
225
+ return round(x, 2)
226
+ else:
227
+ return round(x, 3)
228
+
229
+ def colab_zip_download_folder(dir_name):
230
+ """ zips and downloads a directory from colab. will only work in google colab
231
+ Args:
232
+ dir_name (str): name of the directory to zip and download
233
+ returns:
234
+ None, file will be downloaded to the local machine"""
235
+ try:
236
+ # zip the directory
237
+ get_ipython().system('zip -r /content/{dir_name}.zip /content/{dir_name}')
238
+
239
+ # download the zip file
240
+ from google.colab import files
241
+ files.download(f"/content/{dir_name}.zip")
242
+ except:
243
+ print("something went wrong, this function will only work in google colab, make sure to import the necessary packages. >>> from google.colab import files <<<" )
244
+
245
+
246
+
247
+
248
+ def generate__cluster_prompt(data_context, analysis_goal, column_descriptions, cluster_stat, complexity, exemplary_cluster_names_descriptions=None, creativity=None):
249
+ # Define complexity levels
250
+ complexity_levels = {
251
+ 1: "Please explain the findings in a simple way, suitable for someone with no knowledge of statistics or data science.",
252
+ 2: "Please explain the findings in moderate detail, suitable for someone with basic understanding of statistics or data science.",
253
+ 3: "Please explain the findings in great detail, suitable for someone with advanced understanding of statistics or data science."
254
+ }
255
+
256
+ # Start the prompt
257
+ prompt = f"The data you are analyzing is from the following context: {data_context}. The goal of this analysis is: {analysis_goal}.\n\n"
258
+
259
+ # Add column descriptions
260
+ prompt += "The data consists of the following columns:\n"
261
+ for column, description in column_descriptions.items():
262
+ prompt += f"- {column}: {description}\n"
263
+
264
+ # Add cluster stat and ask for generation
265
+ prompt += "\nBased on the data, the following cluster has been identified:\n"
266
+ prompt += f"\nCluster ID: {cluster_stat['cluster_id']}\n"
267
+ for column, stats in cluster_stat['columns'].items():
268
+ prompt += f"- {column}:\n"
269
+ for stat, value in stats.items():
270
+ prompt += f" - {stat}: {value}\n"
271
+
272
+ # Adjust the prompt based on whether examples are provided
273
+ if exemplary_cluster_names_descriptions is not None and creativity is not None:
274
+ prompt += f"\nPlease generate a name and description for this cluster, using a creativity level of {creativity} (where 0 is sticking closely to the examples and 1 is completely original). The examples provided are: {exemplary_cluster_names_descriptions}\n"
275
+ else:
276
+ prompt += "\nPlease generate a name and description for this cluster. Be creative and original in your descriptions.\n"
277
+
278
+ prompt += "Please fill the following JSON template with the cluster name and two types of descriptions:\n"
279
+ prompt += "{\n \"cluster_name\": \"<generate>\",\n \"description_narrative\": \"<generate>\",\n \"description_statistical\": \"<generate>\"\n}\n"
280
+ prompt += f"\nFor the narrative description, {complexity_levels[complexity]}"
281
+
282
+ return prompt
283
+
284
+
285
+ def generate_cluster_description(cluster_df, original_df=None, stats_list=['mean', 'min', 'max', 'std', 'kurt'], cluster_id = ""):
286
+ cluster_description = {"cluster_id": cluster_id,
287
+ "name":"<generate>",
288
+ "description_narrative":"<generate>",
289
+ "description_statistical":"<generate>",
290
+ "size": len(cluster_df),
291
+ "columns": {}
292
+ }
293
+ if original_df is not None:
294
+ size_relative = round(len(cluster_df)/len(original_df), 2)
295
+ for column in cluster_df.columns:
296
+ cluster_description["columns"][column] = {}
297
+ for stat in stats_list:
298
+ # Compute the statistic for the cluster
299
+ if stat == 'mean':
300
+ value = round(cluster_df[column].mean(),2)
301
+ elif stat == 'min':
302
+ value = round(cluster_df[column].min(),2)
303
+ elif stat == 'max':
304
+ value = round(cluster_df[column].max(),2)
305
+ elif stat == 'std':
306
+ value = round(cluster_df[column].std(), 2)
307
+ elif stat == 'kurt':
308
+ value = round(cluster_df[column].kurt(), 2)
309
+
310
+ # Compute the relative difference if the original dataframe is provided
311
+ if original_df is not None:
312
+ original_value = original_df[column].mean() if stat == 'mean' else original_df[column].min() if stat == 'min' else original_df[column].max() if stat == 'max' else original_df[column].std() if stat == 'std' else original_df[column].kurt()
313
+ relative_difference = (value - original_value) / original_value * 100
314
+ cluster_description["columns"][column][stat] = {"value": round(value,2), "relative_difference": f"{round(relative_difference,2)}%"}
315
+ else:
316
+ cluster_description["columns"][column][stat] = {"value": round(value,2)}
317
+
318
+ return cluster_description
319
+
320
+
321
+
322
+
323
+ def generate_cluster_description_mixed(cluster_df, original_df=None, stats_list=['mean', 'min', 'max', 'std', 'kurt'], cluster_id = ""):
324
+ cluster_description = {
325
+ "cluster_id": cluster_id,
326
+ "name":"<generate>",
327
+ "description_narrative":"<generate>",
328
+ "description_statistical":"<generate>",
329
+ "size": len(cluster_df),
330
+ "columns": {}
331
+ }
332
+
333
+ if original_df is not None:
334
+ size_relative = round(len(cluster_df)/len(original_df), 2)
335
+
336
+ # Create CSV string in memory
337
+ csv_io = io.StringIO()
338
+ writer = csv.writer(csv_io)
339
+
340
+ # CSV Headers
341
+ writer.writerow(['Column', 'Stat', 'Value', 'Relative_Difference'])
342
+
343
+ for column in cluster_df.columns:
344
+ for stat in stats_list:
345
+ if stat == 'mean':
346
+ value = round(cluster_df[column].mean(),2)
347
+ elif stat == 'min':
348
+ value = round(cluster_df[column].min(),2)
349
+ elif stat == 'max':
350
+ value = round(cluster_df[column].max(),2)
351
+ elif stat == 'std':
352
+ value = round(cluster_df[column].std(), 2)
353
+ elif stat == 'kurt':
354
+ value = round(cluster_df[column].kurt(), 2)
355
+
356
+ if original_df is not None:
357
+ original_value = original_df[column].mean() if stat == 'mean' else original_df[column].min() if stat == 'min' else original_df[column].max() if stat == 'max' else original_df[column].std() if stat == 'std' else original_df[column].kurt()
358
+ relative_difference = (value - original_value) / original_value * 100
359
+ writer.writerow([column, stat, value, f"{round(relative_difference,2)}%"])
360
+ else:
361
+ writer.writerow([column, stat, value, "N/A"])
362
+
363
+ # Store CSV data in JSON
364
+ cluster_description["columns"] = csv_io.getvalue()
365
+
366
+ data_description = """
367
+ The input data is a JSON object with details about clusters. It has the following structure:
368
+
369
+ 1. 'cluster_id': An identifier for the cluster.
370
+ 2. 'name': A placeholder for the name of the cluster.
371
+ 3. 'description_narrative': A placeholder for a narrative description of the cluster.
372
+ 4. 'description_statistical': A placeholder for a statistical description of the cluster.
373
+ 5. 'size': The number of elements in the cluster.
374
+ 6. 'columns': This contains statistical data about different aspects, presented in CSV format.
375
+
376
+ In the 'columns' CSV:
377
+ - 'Column' corresponds to the aspect.
378
+ - 'Stat' corresponds to the computed statistic for that aspect in the cluster.
379
+ - 'Value' is the value of that statistic.
380
+ - 'Relative_Difference' is the difference of the statistic's value compared to the average value of this statistic in the entire dataset, expressed in percentages.
381
+ """
382
+
383
+ return cluster_description, data_description
384
+
385
+ # ==================================================================================================
386
+ # ========== TESTING ===============================================================================
387
+
388
+ def compare_column_names(ref_list, check_list):
389
+ """
390
+ Compares two lists of column names to check for inconsistencies.
391
+
392
+ Args:
393
+ ref_list (list): The reference list of column names.
394
+ check_list (list): The list of column names to be checked.
395
+
396
+ Returns:
397
+ report_dict (dict): Report about the comparison process.
398
+
399
+ Raises:
400
+ ValueError: If the input types are not list.
401
+ """
402
+ # Check the type of input data
403
+ if not all(isinstance(i, list) for i in [ref_list, check_list]):
404
+ raise ValueError("Both inputs must be of type list")
405
+
406
+ missing_cols = [col for col in ref_list if col not in check_list]
407
+ extra_cols = [col for col in check_list if col not in ref_list]
408
+
409
+ try:
410
+ typos = {}
411
+ for col in check_list:
412
+ if col not in ref_list:
413
+ similarity_scores = {ref_col: fuzz.ratio(col, ref_col) for ref_col in ref_list}
414
+ likely_match = max(similarity_scores, key=similarity_scores.get)
415
+ if similarity_scores[likely_match] > 70: # you may adjust this threshold as needed
416
+ typos[col] = likely_match
417
+ except:
418
+ typos = {"error":"fuzzywuzzy is probably not installed"}
419
+
420
+ report_dict = {
421
+ "missing_columns": missing_cols,
422
+ "extra_columns": extra_cols,
423
+ "likely_typos": typos
424
+ }
425
+
426
+ print("\nREPORT:")
427
+ print('-'*50)
428
+ print("\n- Missing columns:")
429
+ print(' ' + '\n '.join(f'"{col}"' for col in missing_cols) if missing_cols else ' None')
430
+ print("\n- Extra columns:")
431
+ print(' ' + '\n '.join(f'"{col}"' for col in extra_cols) if extra_cols else ' None')
432
+ print("\n- Likely typos:")
433
+ if typos:
434
+ for k, v in typos.items():
435
+ print(f' "{k}": "{v}"')
436
+ else:
437
+ print(' None')
438
+
439
+ return report_dict
440
+
441
+
442
+ def compare_dataframes(df1, df2, threshold=0.1):
443
+ """
444
+ Compare two pandas DataFrame and returns a report highlighting any significant differences.
445
+ Significant differences are defined as differences that exceed the specified threshold.
446
+
447
+ Args:
448
+ df1, df2 (pandas.DataFrame): Input dataframes to be compared.
449
+ threshold (float): The percentage difference to be considered significant. Defaults to 0.1 (10%).
450
+
451
+ Returns:
452
+ pandas.DataFrame: A report highlighting the differences between df1 and df2.
453
+ """
454
+ # Column comparison
455
+ cols_df1 = set(df1.columns)
456
+ cols_df2 = set(df2.columns)
457
+
458
+ common_cols = cols_df1 & cols_df2
459
+ missing_df1 = cols_df2 - cols_df1
460
+ missing_df2 = cols_df1 - cols_df2
461
+
462
+ print("Column Comparison:")
463
+ print("------------------")
464
+ print(f"Common columns ({len(common_cols)}): {sorted(list(common_cols)) if common_cols else 'None'}")
465
+ print(f"Columns missing in df1 ({len(missing_df1)}): {sorted(list(missing_df1)) if missing_df1 else 'None'}")
466
+ print(f"Columns missing in df2 ({len(missing_df2)}): {sorted(list(missing_df2)) if missing_df2 else 'None'}")
467
+ print("\n")
468
+
469
+ # Check for new null values
470
+ print("Null Values Check:")
471
+ print("------------------")
472
+ inconsistent_values_cols = []
473
+ inconsistent_ranges_cols = []
474
+ constant_cols = []
475
+
476
+ for col in common_cols:
477
+ nulls1 = df1[col].isnull().sum()
478
+ nulls2 = df2[col].isnull().sum()
479
+ if nulls1 == 0 and nulls2 > 0:
480
+ print(f"New null values detected in '{col}' of df2.")
481
+
482
+ # Check for value consistency
483
+ if df1[col].nunique() <= 10 and df2[col].nunique() <= 10:
484
+ inconsistent_values_cols.append(col)
485
+
486
+
487
+ # Check for range consistency
488
+ if df1[col].dtype.kind in 'if' and df2[col].dtype.kind in 'if':
489
+ range1 = df1[col].max() - df1[col].min()
490
+ range2 = df2[col].max() - df2[col].min()
491
+ diff = abs(range1 - range2)
492
+ mean_range = (range1 + range2) / 2
493
+ if diff / mean_range * 100 > threshold * 100:
494
+ inconsistent_ranges_cols.append(col)
495
+
496
+ # Check for constant columns
497
+ if len(df1[col].unique()) == 1 or len(df2[col].unique()) == 1:
498
+ constant_cols.append(col)
499
+
500
+ # Print out the results of value consistency, range consistency, and constant columns check
501
+ print("\nValue Consistency Check:")
502
+ print("------------------------")
503
+ print(f"Columns with inconsistent values (checks if the unique values are the same in both dataframes): {inconsistent_values_cols if inconsistent_values_cols else 'None'}")
504
+
505
+ print("\nRange Consistency Check (checks if the range (max - min) of the values in both dataframes is consistent):")
506
+ print("------------------------")
507
+ print(f"Columns with inconsistent ranges: {inconsistent_ranges_cols if inconsistent_ranges_cols else 'None'}")
508
+
509
+ print("\nConstant Columns Check (columns that have constant values in either dataframe):")
510
+ print("-----------------------")
511
+ print(f"Constant columns: {constant_cols if constant_cols else 'None'}")
512
+
513
+ # Check for changes in data type
514
+ print("\nData Type Check:")
515
+ print("----------------")
516
+ for col in common_cols:
517
+ dtype1 = df1[col].dtype
518
+ dtype2 = df2[col].dtype
519
+ if dtype1 != dtype2:
520
+ print(f"df1 '{dtype1}' -> '{dtype2}' in df2, Data type for '{col}' has changed.")
521
+ print("\n")
522
+
523
+
524
+
525
+ report_dict = {"column": [], "statistic": [], "df1": [], "df2": [], "diff%": []}
526
+ statistics = ["mean", "std", "min", "25%", "75%", "max", "nulls", "outliers"]
527
+
528
+ for col in common_cols:
529
+ if df1[col].dtype in ['int64', 'float64'] and df2[col].dtype in ['int64', 'float64']:
530
+ desc1 = df1[col].describe()
531
+ desc2 = df2[col].describe()
532
+ for stat in statistics[:-2]:
533
+ report_dict["column"].append(col)
534
+ report_dict["statistic"].append(stat)
535
+ report_dict["df1"].append(desc1[stat])
536
+ report_dict["df2"].append(desc2[stat])
537
+ diff = abs(desc1[stat] - desc2[stat])
538
+ mean = (desc1[stat] + desc2[stat]) / 2
539
+ report_dict["diff%"].append(diff / mean * 100 if mean != 0 else 0) # Fix for division by zero
540
+ nulls1 = df1[col].isnull().sum()
541
+ nulls2 = df2[col].isnull().sum()
542
+ outliers1 = df1[(df1[col] < desc1["25%"] - 1.5 * (desc1["75%"] - desc1["25%"])) |
543
+ (df1[col] > desc1["75%"] + 1.5 * (desc1["75%"] - desc1["25%"]))][col].count()
544
+ outliers2 = df2[(df2[col] < desc2["25%"] - 1.5 * (desc2["75%"] - desc2["25%"])) |
545
+ (df2[col] > desc2["75%"] + 1.5 * (desc2["75%"] - desc2["25%"]))][col].count()
546
+ for stat, value1, value2 in zip(statistics[-2:], [nulls1, outliers1], [nulls2, outliers2]):
547
+ report_dict["column"].append(col)
548
+ report_dict["statistic"].append(stat)
549
+ report_dict["df1"].append(value1)
550
+ report_dict["df2"].append(value2)
551
+ diff = abs(value1 - value2)
552
+ mean = (value1 + value2) / 2
553
+ report_dict["diff%"].append(diff / mean * 100 if mean != 0 else 0) # Fix for division by zero
554
+
555
+ report_df = pd.DataFrame(report_dict)
556
+ report_df["significant"] = report_df["diff%"] > threshold * 100
557
+ report_df = report_df[report_df["significant"]]
558
+ report_df = report_df.round(2)
559
+
560
+ print(f"REPORT:\n{'-'*50}")
561
+ for col in report_df["column"].unique():
562
+ print(f"\n{'='*50}")
563
+ print(f"Column: {col}\n{'='*50}")
564
+ subset = report_df[report_df["column"]==col][["statistic", "df1", "df2", "diff%"]]
565
+ subset.index = subset["statistic"]
566
+ print(subset.to_string(header=True))
567
+
568
+ return report_df
569
+
570
+
571
+ def notion_db_as_df(database_id, token):
572
+ base_url = "https://api.notion.com/v1"
573
+
574
+ # Headers for API requests
575
+ headers = {
576
+ "Authorization": f"Bearer {token}",
577
+ "Notion-Version": "2022-06-28",
578
+ "Content-Type": "application/json"
579
+ }
580
+
581
+ response = requests.post(f"{base_url}/databases/{database_id}/query", headers=headers)
582
+ # response.raise_for_status() # Uncomment to raise an exception for HTTP errors
583
+ pages = response.json().get('results', [])
584
+ print(response.json().keys())
585
+
586
+ # Used to create df
587
+ table_data = {}
588
+ page_cnt = len(pages)
589
+ for i, page in enumerate(pages):
590
+ for cur_col, val in page["properties"].items():
591
+ if cur_col not in table_data:
592
+ table_data[cur_col] = [None] * page_cnt
593
+ val_type = val["type"]
594
+ if val_type == "title":
595
+ value = val[val_type][0]["text"]["content"]
596
+ elif val_type in ["number", "checkbox"]:
597
+ value = val[val_type]
598
+ elif val_type in ["select", "multi_select"]:
599
+ value = ', '.join([option["name"] for option in val[val_type]])
600
+ elif val_type == "date":
601
+ value = val[val_type]["start"]
602
+ elif val_type in ["people", "files"]:
603
+ value = ', '.join([item["id"] for item in val[val_type]])
604
+ elif val_type in ["url", "email", "phone_number"]:
605
+ value = val[val_type]
606
+ elif val_type == "formula":
607
+ value = val[val_type]["string"] if "string" in val[val_type] else val[val_type]["number"]
608
+ elif val_type == "rich_text":
609
+ value = val[val_type][0]["text"]["content"]
610
+ else:
611
+ value = str(val[val_type]) # Fallback to string representation
612
+ table_data[cur_col][i] = value
613
+
614
+ # To DataFrame
615
+ df = pd.DataFrame(table_data)
616
+ return df
speckle_utils.py ADDED
@@ -0,0 +1,656 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #speckle utils
2
+ import json
3
+ import pandas as pd
4
+ import numpy as np
5
+ import specklepy
6
+ from specklepy.api.client import SpeckleClient
7
+ from specklepy.api.credentials import get_default_account, get_local_accounts
8
+ from specklepy.transports.server import ServerTransport
9
+ from specklepy.api import operations
10
+ from specklepy.objects.geometry import Polyline, Point, Mesh
11
+
12
+ from specklepy.api.wrapper import StreamWrapper
13
+ try:
14
+ import openai
15
+ except:
16
+ pass
17
+
18
+ import requests
19
+ from datetime import datetime
20
+ import copy
21
+
22
+
23
+ # HELP FUNCTION ===============================================================
24
+ def helper():
25
+ """
26
+ Prints out the help message for this module.
27
+ """
28
+ print("This module contains a set of utility functions for speckle streams.")
29
+ print("______________________________________________________________________")
30
+ print("It requires the specklepy package to be installed -> !pip install specklepy")
31
+ print("the following functions are available:")
32
+ print("getSpeckleStream(stream_id, branch_name, client)")
33
+ print("getSpeckleGlobals(stream_id, client)")
34
+ print("get_dataframe(objects_raw, return_original_df)")
35
+ print("updateStreamAnalysis(stream_id, new_data, branch_name, geometryGroupPath, match_by_id, openai_key, return_original)")
36
+ print("there are some more function available not documented fully yet, including updating a notion database")
37
+ print("______________________________________________________________________")
38
+ print("for detailed help call >>> help(speckle_utils.function_name) <<< ")
39
+ print("______________________________________________________________________")
40
+ print("standard usage:")
41
+ print("______________________________________________________________________")
42
+ print("retreiving data")
43
+ print("1. import speckle_utils & speckle related libaries from specklepy")
44
+ print("2. create a speckle client -> client = SpeckleClient(host='https://speckle.xyz/')" )
45
+ print(" client.authenticate_with_token(token='your_token_here')")
46
+ print("3. get a speckle stream -> stream = speckle_utils.getSpeckleStream(stream_id, branch_name, client)")
47
+ print("4. get the stream data -> data = stream['pth']['to']['data']")
48
+ print("5. transform data to dataframe -> df = speckle_utils.get_dataframe(data, return_original_df=False)")
49
+ print("______________________________________________________________________")
50
+ print("updating data")
51
+ print("1. call updateStreamAnalysis --> updateStreamAnalysis(new_data, stream_id, branch_name, geometryGroupPath, match_by_id, openai_key, return_original)")
52
+
53
+
54
+ #==============================================================================
55
+
56
+ def getSpeckleStream(stream_id,
57
+ branch_name,
58
+ client,
59
+ commit_id=""
60
+ ):
61
+ """
62
+ Retrieves data from a specific branch of a speckle stream.
63
+
64
+ Args:
65
+ stream_id (str): The ID of the speckle stream.
66
+ branch_name (str): The name of the branch within the speckle stream.
67
+ client (specklepy.api.client.Client, optional): A speckle client. Defaults to a global `client`.
68
+ commit_id (str): id of a commit, if nothing is specified, the latest commit will be fetched
69
+
70
+ Returns:
71
+ dict: The speckle stream data received from the specified branch.
72
+
73
+ This function retrieves the last commit from a specific branch of a speckle stream.
74
+ It uses the provided speckle client to get the branch and commit information, and then
75
+ retrieves the speckle stream data associated with the last commit.
76
+ It prints out the branch details and the creation dates of the last three commits for debugging purposes.
77
+ """
78
+
79
+ print("updated A")
80
+
81
+ # set stream and branch
82
+ try:
83
+ branch = client.branch.get(stream_id, branch_name, 3)
84
+ print(branch)
85
+ except:
86
+ branch = client.branch.get(stream_id, branch_name, 1)
87
+ print(branch)
88
+
89
+ print("last three commits:")
90
+ [print(ite.createdAt) for ite in branch.commits.items]
91
+
92
+ if commit_id == "":
93
+ latest_commit = branch.commits.items[0]
94
+ choosen_commit_id = latest_commit.id
95
+ commit = client.commit.get(stream_id, choosen_commit_id)
96
+ print("latest commit ", branch.commits.items[0].createdAt, " was choosen")
97
+ elif type(commit_id) == type("s"): # string, commit uuid
98
+ choosen_commit_id = commit_id
99
+ commit = client.commit.get(stream_id, choosen_commit_id)
100
+ print("provided commit ", choosen_commit_id, " was choosen")
101
+ elif type(commit_id) == type(1): #int
102
+ latest_commit = branch.commits.items[commit_id]
103
+ choosen_commit_id = latest_commit.id
104
+ commit = client.commit.get(stream_id, choosen_commit_id)
105
+
106
+
107
+ print(commit)
108
+ print(commit.referencedObject)
109
+ # get transport
110
+ transport = ServerTransport(client=client, stream_id=stream_id)
111
+ #speckle stream
112
+ res = operations.receive(commit.referencedObject, transport)
113
+
114
+ return res
115
+
116
+ def getSpeckleGlobals(stream_id, client):
117
+ """
118
+ Retrieves global analysis information from the "globals" branch of a speckle stream.
119
+
120
+ Args:
121
+ stream_id (str): The ID of the speckle stream.
122
+ client (specklepy.api.client.Client, optional): A speckle client. Defaults to a global `client`.
123
+
124
+ Returns:
125
+ analysisInfo (dict or None): The analysis information retrieved from globals. None if no globals found.
126
+ analysisGroups (list or None): The analysis groups retrieved from globals. None if no globals found.
127
+
128
+ This function attempts to retrieve and parse the analysis information from the "globals"
129
+ branch of the specified speckle stream. It accesses and parses the "analysisInfo" and "analysisGroups"
130
+ global attributes, extracts analysis names and UUIDs.
131
+ If no globals are found in the speckle stream, it returns None for both analysisInfo and analysisGroups.
132
+ """
133
+ # get the latest commit
134
+ try:
135
+ # speckle stream globals
136
+ branchGlob = client.branch.get(stream_id, "globals")
137
+ latest_commit_Glob = branchGlob.commits.items[0]
138
+ transport = ServerTransport(client=client, stream_id=stream_id)
139
+
140
+ globs = operations.receive(latest_commit_Glob.referencedObject, transport)
141
+
142
+ # access and parse globals
143
+ #analysisInfo = json.loads(globs["analysisInfo"]["@{0;0;0;0}"][0].replace("'", '"'))
144
+ #analysisGroups = [json.loads(gr.replace("'", '"')) for gr in globs["analysisGroups"]["@{0}"]]
145
+
146
+ def get_error_context(e, context=100):
147
+ start = max(0, e.pos - context)
148
+ end = e.pos + context
149
+ error_line = e.doc[start:end]
150
+ pointer_line = ' ' * (e.pos - start - 1) + '^'
151
+ return error_line, pointer_line
152
+
153
+ try:
154
+ analysisInfo = json.loads(globs["analysisInfo"]["@{0;0;0;0}"][0].replace("'", '"').replace("None", "null"))
155
+ except json.JSONDecodeError as e:
156
+ print(f"Error decoding analysisInfo: {e}")
157
+ error_line, pointer_line = get_error_context(e)
158
+ print("Error position and surrounding text:")
159
+ print(error_line)
160
+ print(pointer_line)
161
+ analysisInfo = None
162
+
163
+ try:
164
+ analysisGroups = [json.loads(gr.replace("'", '"').replace("None", "null")) for gr in globs["analysisGroups"]["@{0}"]]
165
+ except json.JSONDecodeError as e:
166
+ print(f"Error decoding analysisGroups: {e}")
167
+ error_line, pointer_line = get_error_context(e)
168
+ print("Error position and surrounding text:")
169
+ print(error_line)
170
+ print(pointer_line)
171
+ analysisGroups = None
172
+
173
+
174
+
175
+ # extract analysis names
176
+ analysis_names = []
177
+ analysis_uuid = []
178
+ [(analysis_names.append(key.split("++")[0]),analysis_uuid.append(key.split("++")[1]) ) for key in analysisInfo.keys()]
179
+
180
+
181
+ # print extracted results
182
+ print("there are global dictionaries with additional information for each analysis")
183
+ print("<analysisGroups> -> ", [list(curgrp.keys()) for curgrp in analysisGroups])
184
+ print("<analysis_names> -> ", analysis_names)
185
+ print("<analysis_uuid> -> ", analysis_uuid)
186
+ except Exception as e: # catch exception as 'e'
187
+ analysisInfo = None
188
+ analysisGroups = None
189
+ print("No GlOBALS FOUND")
190
+ print(f"Error: {e}") # print error description
191
+
192
+ return analysisInfo, analysisGroups
193
+
194
+
195
+
196
+ #function to extract non geometry data from speckle
197
+ def get_dataframe(objects_raw, return_original_df=False):
198
+ """
199
+ Creates a pandas DataFrame from a list of raw Speckle objects.
200
+
201
+ Args:
202
+ objects_raw (list): List of raw Speckle objects.
203
+ return_original_df (bool, optional): If True, the function also returns the original DataFrame before any conversion to numeric. Defaults to False.
204
+
205
+ Returns:
206
+ pd.DataFrame or tuple: If return_original_df is False, returns a DataFrame where all numeric columns have been converted to their respective types,
207
+ and non-numeric columns are left unchanged.
208
+ If return_original_df is True, returns a tuple where the first item is the converted DataFrame,
209
+ and the second item is the original DataFrame before conversion.
210
+
211
+ This function iterates over the raw Speckle objects, creating a dictionary for each object that excludes the '@Geometry' attribute.
212
+ These dictionaries are then used to create a pandas DataFrame.
213
+ The function attempts to convert each column to a numeric type if possible, and leaves it unchanged if not.
214
+ Non-convertible values in numeric columns are replaced with their original values.
215
+ """
216
+ # dataFrame
217
+ df_data = []
218
+ # Iterate over speckle objects
219
+ for obj_raw in objects_raw:
220
+ obj = obj_raw.__dict__
221
+ df_obj = {k: v for k, v in obj.items() if k != '@Geometry'}
222
+ df_data.append(df_obj)
223
+
224
+ # Create DataFrame and GeoDataFrame
225
+ df = pd.DataFrame(df_data)
226
+ # Convert columns to float or int if possible, preserving non-convertible values <-
227
+ df_copy = df.copy()
228
+ for col in df.columns:
229
+ df[col] = pd.to_numeric(df[col], errors='coerce')
230
+ df[col].fillna(df_copy[col], inplace=True)
231
+
232
+ if return_original_df:
233
+ return df, df_copy
234
+ else:
235
+ return df
236
+
237
+
238
+ def updateStreamAnalysis(
239
+ client,
240
+ new_data,
241
+ stream_id,
242
+ branch_name,
243
+ geometryGroupPath=None,
244
+ match_by_id="",
245
+ openai_key ="",
246
+ return_original = False
247
+ ):
248
+
249
+
250
+ """
251
+ Updates Stream Analysis by modifying object attributes based on new data.
252
+
253
+ Args:
254
+ new_data (pandas.DataFrame): DataFrame containing new data.
255
+ stream_id (str): Stream ID.
256
+ branch_name (str): Branch name.
257
+ geometry_group_path (list, optional): Path to geometry group. Defaults to ["@Data", "@{0}"].
258
+ match_by_id (str, optional): key for column that should be used for matching. If empty, the index is used.
259
+ openai_key (str, optional): OpenAI key. If empty no AI commit message is generated Defaults to an empty string.
260
+ return_original (bool, optional): Determines whether to return original speckle stream objects. Defaults to False.
261
+
262
+ Returns:
263
+ list: original speckle stream objects as backup if return_original is set to True.
264
+
265
+ This function retrieves the latest commit from a specified branch, obtains the
266
+ necessary geometry objects, and matches new data with existing objects using
267
+ an ID mapper. The OpenAI GPT model is optionally used to create a commit summary
268
+ message. Changes are sent back to the server and a new commit is created, with
269
+ the original objects returned as a backup if return_original is set to True.
270
+ The script requires active server connection, necessary permissions, and relies
271
+ on Speckle and OpenAI's GPT model libraries.
272
+ """
273
+
274
+ if geometryGroupPath == None:
275
+ geometryGroupPath = ["@Speckle", "Geometry"]
276
+
277
+ branch = client.branch.get(stream_id, branch_name, 2)
278
+
279
+ latest_commit = branch.commits.items[0]
280
+ commitID = latest_commit.id
281
+
282
+ commit = client.commit.get(stream_id, commitID)
283
+
284
+ # get objects
285
+ transport = ServerTransport(client=client, stream_id=stream_id)
286
+
287
+ #speckle stream
288
+ res = operations.receive(commit.referencedObject, transport)
289
+
290
+ # get geometry objects (they carry the attributes)
291
+ objects_raw = res[geometryGroupPath[0]][geometryGroupPath[1]]
292
+ res_new = copy.deepcopy(res)
293
+
294
+ # map ids
295
+ id_mapper = {}
296
+ if match_by_id != "":
297
+ for i, obj in enumerate(objects_raw):
298
+ id_mapper[obj[match_by_id]] = i
299
+ else:
300
+ for i, obj in enumerate(objects_raw):
301
+ id_mapper[str(i)] = i
302
+
303
+ # iterate through rows (objects)
304
+ for index, row in new_data.iterrows():
305
+ #determin target object
306
+ if match_by_id != "":
307
+ local_id = row[match_by_id]
308
+ else:
309
+ local_id = index
310
+ target_id = id_mapper[local_id]
311
+
312
+ #iterate through columns (attributes)
313
+ for col_name in new_data.columns:
314
+ res_new[geometryGroupPath[0]][geometryGroupPath[1]][target_id][col_name] = row[col_name]
315
+
316
+
317
+ # ======================== OPEN AI FUN ===========================
318
+ try:
319
+ answer_summary = gptCommitMessage(objects_raw, new_data,openai_key)
320
+ if answer_summary == None:
321
+ _, answer_summary = compareStats(get_dataframe(objects_raw),new_data)
322
+ except:
323
+ _, answer_summary = compareStats(get_dataframe(objects_raw),new_data)
324
+ # ================================================================
325
+
326
+ new_objects_raw_speckle_id = operations.send(base=res_new, transports=[transport])
327
+
328
+ # You can now create a commit on your stream with this object
329
+ commit_id = client.commit.create(
330
+ stream_id=stream_id,
331
+ branch_name=branch_name,
332
+ object_id=new_objects_raw_speckle_id,
333
+ message="Updated item in colab -" + answer_summary,
334
+ )
335
+
336
+ print("Commit created!")
337
+ if return_original:
338
+ return objects_raw #as back-up
339
+
340
+ def custom_describe(df):
341
+ # Convert columns to numeric if possible
342
+ df = df.apply(lambda x: pd.to_numeric(x, errors='ignore'))
343
+
344
+ # Initial describe with 'include = all'
345
+ desc = df.describe(include='all')
346
+
347
+ # Desired statistics
348
+ desired_stats = ['count', 'unique', 'mean', 'min', 'max']
349
+
350
+ # Filter for desired statistics
351
+ result = desc.loc[desired_stats, :].copy()
352
+ return result
353
+
354
+ def compareStats(df_before, df_after):
355
+ """
356
+ Compares the descriptive statistics of two pandas DataFrames before and after some operations.
357
+
358
+ Args:
359
+ df_before (pd.DataFrame): DataFrame representing the state of data before operations.
360
+ df_after (pd.DataFrame): DataFrame representing the state of data after operations.
361
+
362
+ Returns:
363
+ The CSV string includes column name, intervention type, and before and after statistics for each column.
364
+ The summary string provides a count of updated and new columns.
365
+
366
+ This function compares the descriptive statistics of two DataFrames: 'df_before' and 'df_after'.
367
+ It checks the columns in both DataFrames and categorizes them as either 'updated' or 'new'.
368
+ The 'updated' columns exist in both DataFrames while the 'new' columns exist only in 'df_after'.
369
+ For 'updated' columns, it compares the statistics before and after and notes the differences.
370
+ For 'new' columns, it lists the 'after' statistics and marks the 'before' statistics as 'NA'.
371
+ The function provides a summary with the number of updated and new columns,
372
+ and a detailed account in CSV format of changes in column statistics.
373
+ """
374
+
375
+ desc_before = custom_describe(df_before)
376
+ desc_after = custom_describe(df_after)
377
+
378
+ # Get union of all columns
379
+ all_columns = set(desc_before.columns).union(set(desc_after.columns))
380
+
381
+ # Track number of updated and new columns
382
+ updated_cols = 0
383
+ new_cols = 0
384
+
385
+ # Prepare DataFrame output
386
+ output_data = []
387
+
388
+ for column in all_columns:
389
+ row_data = {'column': column}
390
+ stat_diff = False # Track if there's a difference in stats for a column
391
+
392
+ # Check if column exists in both dataframes
393
+ if column in desc_before.columns and column in desc_after.columns:
394
+ updated_cols += 1
395
+ row_data['interventionType'] = 'updated'
396
+ for stat in desc_before.index:
397
+ before_val = round(desc_before.loc[stat, column], 1) if pd.api.types.is_number(desc_before.loc[stat, column]) else desc_before.loc[stat, column]
398
+ after_val = round(desc_after.loc[stat, column], 1) if pd.api.types.is_number(desc_after.loc[stat, column]) else desc_after.loc[stat, column]
399
+ if before_val != after_val:
400
+ stat_diff = True
401
+ row_data[stat+'_before'] = before_val
402
+ row_data[stat+'_after'] = after_val
403
+ elif column in desc_after.columns:
404
+ new_cols += 1
405
+ stat_diff = True
406
+ row_data['interventionType'] = 'new'
407
+ for stat in desc_after.index:
408
+ row_data[stat+'_before'] = 'NA'
409
+ after_val = round(desc_after.loc[stat, column], 1) if pd.api.types.is_number(desc_after.loc[stat, column]) else desc_after.loc[stat, column]
410
+ row_data[stat+'_after'] = after_val
411
+
412
+ # Only add to output_data if there's actually a difference in the descriptive stats between "before" and "after".
413
+ if stat_diff:
414
+ output_data.append(row_data)
415
+
416
+ output_df = pd.DataFrame(output_data)
417
+ csv_output = output_df.to_csv(index=False)
418
+ print (output_df)
419
+ # Add summary to beginning of output
420
+ summary = f"Summary:\n Number of updated columns: {updated_cols}\n Number of new columns: {new_cols}\n\n"
421
+ csv_output = summary + csv_output
422
+
423
+ return csv_output, summary
424
+
425
+
426
+
427
+ # Function to call ChatGPT API
428
+ def ask_chatgpt(prompt, model="gpt-3.5-turbo", max_tokens=300, n=1, stop=None, temperature=0.3):
429
+ import openai
430
+ response = openai.ChatCompletion.create(
431
+ model=model,
432
+ messages=[
433
+ {"role": "system", "content": "You are a helpfull assistant,."},
434
+ {"role": "user", "content": prompt}
435
+ ],
436
+ max_tokens=max_tokens,
437
+ n=n,
438
+ stop=stop,
439
+ temperature=temperature,
440
+ )
441
+ return response.choices[0].message['content']
442
+
443
+
444
+
445
+
446
+ def gptCommitMessage(objects_raw, new_data,openai_key):
447
+ # the idea is to automatically create commit messages. Commits coming through this channel are all
448
+ # about updating or adding a dataTable. So we can compare the descriptive stats of a before and after
449
+ # data frame
450
+ #try:
451
+ try:
452
+ import openai
453
+ openai.api_key = openai_key
454
+ except NameError as ne:
455
+ if str(ne) == "name 'openai' is not defined":
456
+ print("No auto commit message: openai module not imported. Please import the module before setting the API key.")
457
+ elif str(ne) == "name 'openai_key' is not defined":
458
+ print("No auto commit message: openai_key is not defined. Please define the variable before setting the API key.")
459
+ else:
460
+ raise ne
461
+
462
+ report, summary = compareStats(get_dataframe(objects_raw),new_data)
463
+
464
+ # prompt
465
+ prompt = f"""Given the following changes in my tabular data structure, generate a
466
+ precise and informative commit message. The changes involve updating or adding
467
+ attribute keys and values. The provided summary statistics detail the changes in
468
+ the data from 'before' to 'after'.
469
+ The CSV format below demonstrates the structure of the summary:
470
+
471
+ Summary:
472
+ Number of updated columns: 2
473
+ Number of new columns: 1
474
+ column,interventionType,count_before,count_after,unique_before,unique_after,mean_before,mean_after,min_before,min_after,max_before,max_after
475
+ A,updated,800,800,2,3,,nan,nan,nan,nan,nan
476
+ B,updated,800,800,3,3,,nan,nan,nan,nan,nan
477
+ C,new,NA,800,NA,4,NA,nan,NA,nan,NA,nan
478
+
479
+ For the commit message, your focus should be on changes in the data structure, not the interpretation of the content. Be precise, state the facts, and highlight significant differences or trends in the statistics, such as shifts in mean values or an increase in unique entries.
480
+
481
+ Based on the above guidance, draft a commit message using the following actual summary statistics:
482
+
483
+ {report}
484
+
485
+ Your commit message should follow this structure:
486
+
487
+ 1. Brief description of the overall changes.
488
+ 2. Significant changes in summary statistics (count, unique, mean, min, max).
489
+ 3. Conclusion, summarizing the most important findings with the strucutre:
490
+ # changed columns: , comment: ,
491
+ # added Columns: , comment: ,
492
+ # Chaged statistic: , coment: ,
493
+
494
+ Mark the beginning of the conclusion with ">>>" and ensure to emphasize hard facts and significant findings.
495
+ """
496
+
497
+ try:
498
+ answer = ask_chatgpt(prompt)
499
+ answer_summery = answer.split(">>>")[1]
500
+ if answer == None:
501
+ answer_summery = summary
502
+ except:
503
+ answer_summery = summary
504
+ return answer_summery
505
+
506
+ def specklePolyline_to_BokehPatches(speckle_objs, pth_to_geo="curves", id_key="ids"):
507
+ """
508
+ Takes a list of speckle objects, extracts the polyline geometry at the specified path, and returns a dataframe of x and y coordinates for each polyline.
509
+ This format is compatible with the Bokeh Patches object for plotting.
510
+
511
+ Args:
512
+ speckle_objs (list): A list of Speckle Objects
513
+ pth_to_geo (str): Path to the geometry in the Speckle Object
514
+ id_key (str): The key to use for the uuid in the dataframe. Defaults to "uuid"
515
+
516
+ Returns:
517
+ pd.DataFrame: A Pandas DataFrame with columns "uuid", "patches_x" and "patches_y"
518
+ """
519
+ patchesDict = {"uuid":[], "patches_x":[], "patches_y":[]}
520
+
521
+ for obj in speckle_objs:
522
+ obj_geo = obj[pth_to_geo]
523
+ obj_pts = Polyline.as_points(obj_geo)
524
+ coorX = []
525
+ coorY = []
526
+ for pt in obj_pts:
527
+ coorX.append(pt.x)
528
+ coorY.append(pt.y)
529
+
530
+ patchesDict["patches_x"].append(coorX)
531
+ patchesDict["patches_y"].append(coorY)
532
+ patchesDict["uuid"].append(obj[id_key])
533
+
534
+ return pd.DataFrame(patchesDict)
535
+
536
+
537
+
538
+ def rebuildAnalysisInfoDict(analysisInfo):
539
+ """rebuild the analysisInfo dictionary to remove the ++ from the keys
540
+
541
+ Args:
542
+ analysisInfo (list): a list containing the analysisInfo dictionary
543
+
544
+ Returns:
545
+ dict: a dictionary containing the analysisInfo dictionary with keys without the ++
546
+
547
+ """
548
+ analysisInfoDict = {}
549
+ for curKey in analysisInfo[0]:
550
+ newkey = curKey.split("++")[0]
551
+ analysisInfoDict[newkey] = analysisInfo[0][curKey]
552
+ return analysisInfoDict
553
+
554
+
555
+ def specklePolyline2Patches(speckle_objs, pth_to_geo="curves", id_key=None):
556
+ """
557
+ Converts Speckle objects' polyline information into a format suitable for Bokeh patches.
558
+
559
+ Args:
560
+ speckle_objs (list): A list of Speckle objects.
561
+ pth_to_geo (str, optional): The path to the polyline geometric information in the Speckle objects. Defaults to "curves".
562
+ id_key (str, optional): The key for object identification. Defaults to "uuid".
563
+
564
+ Returns:
565
+ DataFrame: A pandas DataFrame with three columns - "uuid", "patches_x", and "patches_y". Each row corresponds to a Speckle object.
566
+ "uuid" column contains the object's identifier.
567
+ "patches_x" and "patches_y" columns contain lists of x and y coordinates of the polyline points respectively.
568
+
569
+ This function iterates over the given Speckle objects, retrieves the polyline geometric information and the object's id from each Speckle object,
570
+ and formats this information into a format suitable for Bokeh or matplotlib patches. The formatted information is stored in a dictionary with three lists
571
+ corresponding to the "uuid", "patches_x", and "patches_y", and this dictionary is then converted into a pandas DataFrame.
572
+ """
573
+ patchesDict = {"patches_x":[], "patches_y":[]}
574
+ if id_key != None:
575
+ patchesDict[id_key] = []
576
+
577
+ for obj in speckle_objs:
578
+ obj_geo = obj[pth_to_geo]
579
+
580
+ coorX = []
581
+ coorY = []
582
+
583
+ if isinstance(obj_geo, Mesh):
584
+ # For meshes, we'll just use the vertices for now
585
+ for pt in obj_geo.vertices:
586
+ coorX.append(pt.x)
587
+ coorY.append(pt.y)
588
+ else:
589
+ # For polylines, we'll use the existing logic
590
+ obj_pts = Polyline.as_points(obj_geo)
591
+ for pt in obj_pts:
592
+ coorX.append(pt.x)
593
+ coorY.append(pt.y)
594
+
595
+ patchesDict["patches_x"].append(coorX)
596
+ patchesDict["patches_y"].append(coorY)
597
+ if id_key != None:
598
+ patchesDict[id_key].append(obj[id_key])
599
+
600
+ return pd.DataFrame(patchesDict)
601
+
602
+
603
+ #================= NOTION INTEGRATION ============================
604
+ headers = {
605
+ "Notion-Version": "2022-06-28",
606
+ "Content-Type": "application/json"
607
+ }
608
+
609
+ def get_page_id(token, database_id, name):
610
+ headers['Authorization'] = "Bearer " + token
611
+ # Send a POST request to the Notion API
612
+ response = requests.post(f"https://api.notion.com/v1/databases/{database_id}/query", headers=headers)
613
+
614
+ # Load the response data
615
+ data = json.loads(response.text)
616
+
617
+ # Check each page in the results
618
+ for page in data['results']:
619
+ # If the name matches, return the ID
620
+ if page['properties']['name']['title'][0]['text']['content'] == name:
621
+ return page['id']
622
+
623
+ # If no match was found, return None
624
+ return None
625
+
626
+ def add_or_update_page(token, database_id, name, type, time_updated, comment, speckle_link):
627
+ # Format time_updated as a string 'YYYY-MM-DD'
628
+ date_string = time_updated.strftime('%Y-%m-%d')
629
+
630
+ # Construct the data payload
631
+ data = {
632
+ 'parent': {'database_id': database_id},
633
+ 'properties': {
634
+ 'name': {'title': [{'text': {'content': name}}]},
635
+ 'type': {'rich_text': [{'text': {'content': type}}]},
636
+ 'time_updated': {'date': {'start': date_string}},
637
+ 'comment': {'rich_text': [{'text': {'content': comment}}]},
638
+ 'speckle_link': {'rich_text': [{'text': {'content': speckle_link}}]}
639
+ }
640
+ }
641
+
642
+ # Check if a page with this name already exists
643
+ page_id = get_page_id(token, database_id, name)
644
+
645
+ headers['Authorization'] = "Bearer " + token
646
+ if page_id:
647
+ # If the page exists, send a PATCH request to update it
648
+ response = requests.patch(f"https://api.notion.com/v1/pages/{page_id}", headers=headers, data=json.dumps(data))
649
+ else:
650
+ # If the page doesn't exist, send a POST request to create it
651
+ response = requests.post("https://api.notion.com/v1/pages", headers=headers, data=json.dumps(data))
652
+
653
+ print(response.text)
654
+
655
+ # Use the function
656
+ #add_or_update_page('your_token', 'your_database_id', 'New Title', 'New Type', datetime.now(), 'This is a comment', 'https://your-link.com')