Mustehson commited on
Commit
a8d09b2
·
1 Parent(s): 74c5dc5

Initial Commit

Browse files
Files changed (5) hide show
  1. README.md +2 -2
  2. app.py +219 -48
  3. logo.png +0 -0
  4. prompt.py +64 -0
  5. requirements.txt +7 -1
README.md CHANGED
@@ -1,10 +1,10 @@
1
  ---
2
  title: Dataset Test Workflow
3
- emoji: 💬
4
  colorFrom: yellow
5
  colorTo: purple
6
  sdk: gradio
7
- sdk_version: 4.36.1
8
  app_file: app.py
9
  pinned: false
10
  license: mit
 
1
  ---
2
  title: Dataset Test Workflow
3
+ emoji: 🧪
4
  colorFrom: yellow
5
  colorTo: purple
6
  sdk: gradio
7
+ sdk_version: 4.42.0
8
  app_file: app.py
9
  pinned: false
10
  license: mit
app.py CHANGED
@@ -1,63 +1,234 @@
 
 
 
1
  import gradio as gr
 
 
 
 
2
  from huggingface_hub import InferenceClient
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
25
 
26
- messages.append({"role": "user", "content": message})
27
 
28
- response = ""
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
 
62
  if __name__ == "__main__":
63
- demo.launch()
 
1
+ import os
2
+ import json
3
+ import duckdb
4
  import gradio as gr
5
+ import pandas as pd
6
+ import pandera as pa
7
+ from pandera import Column
8
+ import ydata_profiling as pp
9
  from huggingface_hub import InferenceClient
10
+ from prompt import PROMPT_PANDERA
11
 
 
 
 
 
12
 
13
+ # Height of the Tabs Text Area
14
+ TAB_LINES = 8
15
+ # Load Token
16
+ md_token = os.getenv('MD_TOKEN')
17
+ os.environ['HF_TOKEN'] = os.getenv('HF_TOKEN')
18
 
 
 
 
 
 
 
 
 
 
19
 
20
+ INPUT_PROMPT = '''
21
+ Here is the frist few samples of data:
22
+ <Sample Data>
23
+ {data}
24
+ </Sample Data<>
25
+ '''
26
 
 
27
 
28
+ print('Connecting to DB...')
29
+ # Connect to DB
30
+ conn = duckdb.connect(f"md:my_db?motherduck_token={md_token}", read_only=True)
31
+ client = InferenceClient("meta-llama/Meta-Llama-3-70B-Instruct")
32
 
33
+ # Get Databases
34
+ def get_schemas():
35
+ schemas = conn.execute("""
36
+ SELECT DISTINCT schema_name
37
+ FROM information_schema.schemata
38
+ WHERE schema_name NOT IN ('information_schema', 'pg_catalog')
39
+ """).fetchall()
40
+ return [item[0] for item in schemas]
41
 
42
+ # Get Tables
43
+ def get_tables_names(schema_name):
44
+ tables = conn.execute(f"SELECT table_name FROM information_schema.tables WHERE table_schema = '{schema_name}'").fetchall()
45
+ return [table[0] for table in tables]
46
 
47
+ # Update Tables
48
+ def update_table_names(schema_name):
49
+ tables = get_tables_names(schema_name)
50
+ return gr.update(choices=tables)
51
+
52
+ def get_data_df(schema):
53
+ print('Getting Dataframe from the Database')
54
+ return conn.sql(f"SELECT * FROM {schema} LIMIT 1000").df()
55
+
56
+ def run_llm(df):
57
+ messages=[
58
+ {"role": "system", "content": PROMPT_PANDERA},
59
+ {"role": "user", "content": INPUT_PROMPT.format(data=df.head().to_json(orient='records'))},
60
+ ]
61
+ try:
62
+ response = client.chat_completion(messages, max_tokens=1024)
63
+ print(response.choices[0].message.content)
64
+ tests = json.loads(response.choices[0].message.content)
65
+ except Exception as e:
66
+ return e
67
+ return tests
68
+
69
+ # Get Schema
70
+ def get_table_schema(table):
71
+ result = conn.sql(f"SELECT sql, database_name, schema_name FROM duckdb_tables() where table_name ='{table}';").df()
72
+ ddl_create = result.iloc[0,0]
73
+ parent_database = result.iloc[0,1]
74
+ schema_name = result.iloc[0,2]
75
+ full_path = f"{parent_database}.{schema_name}.{table}"
76
+ if schema_name != "main":
77
+ old_path = f"{schema_name}.{table}"
78
+ else:
79
+ old_path = table
80
+ ddl_create = ddl_create.replace(old_path, full_path)
81
+ return full_path
82
+
83
+ def describe(df):
84
+ numerical_info = df.select_dtypes(include=['number']).describe().T.reset_index()
85
+ numerical_info.rename(columns={'index': 'column'}, inplace=True)
86
+
87
+ categorical_info = df.select_dtypes(include=['object']).describe().T.reset_index()
88
+ categorical_info.rename(columns={'index': 'column'}, inplace=True)
89
+
90
+ return numerical_info, categorical_info
91
+
92
+ def validate_pandera(tests, df):
93
+ validation_results = []
94
+
95
+ # Loop through each test rule and validate each column separately
96
+ for test in tests:
97
+ column_name = test['column_name']
98
+ rule = eval(test['pandera_rule']) # Evaluate the Pandera column rule
99
+
100
+ try:
101
+ # Apply the rule to the column and validate
102
+ validated_column = rule(df[[column_name]]) # Validate the specific column
103
+ validation_results.append({
104
+ "Columns": column_name,
105
+ "Result": "✅ Pass"
106
+ })
107
+ except Exception as e:
108
+ # If validation fails, catch the exception and mark the column as 'Fail'
109
+ validation_results.append({
110
+ "Columns": column_name,
111
+ "Result": f"❌ Fail - {str(e)}"
112
+ })
113
+ return pd.DataFrame(validation_results)
114
+
115
+ def statistics(df):
116
+ profile = pp.ProfileReport(df)
117
+ report_dict = profile.get_description()
118
+ description, alerts = report_dict.table, report_dict.alerts
119
+ # Statistics
120
+ mapping = {
121
+ 'n': 'Number of observations',
122
+ 'n_var': 'Number of variables',
123
+ 'n_cells_missing': 'Number of cells missing',
124
+ 'n_vars_with_missing': 'Number of columns with missing data',
125
+ 'n_vars_all_missing': 'Columns with all missing data',
126
+ 'p_cells_missing': 'Missing cells (%)',
127
+ 'n_duplicates': 'Duplicated rows',
128
+ 'p_duplicates': 'Duplicated rows (%)',
129
+ }
130
+
131
+ updated_data = {mapping.get(k, k): v for k, v in description.items() if k != 'types'}
132
+ # Add flattened types information
133
+ if 'Text' in description.get('types', {}):
134
+ updated_data['Number of text columns'] = description['types']['Text']
135
+ if 'Categorical' in description.get('types', {}):
136
+ updated_data['Number of categorical columns'] = description['types']['Categorical']
137
+ if 'Numeric' in description.get('types', {}):
138
+ updated_data['Number of numeric columns'] = description['types']['Numeric']
139
+ if 'DateTime' in description.get('types', {}):
140
+ updated_data['Number of datetime columns'] = description['types']['DateTime']
141
+
142
+ df_statistics = pd.DataFrame(list(updated_data.items()), columns=['Statistic Description', 'Value'])
143
+ df_statistics['Value'] = df_statistics['Value'].astype(int)
144
+
145
+ # Alerts
146
+ alerts_list = [(str(alert).replace('[', '').replace(']', ''), alert.alert_type_name) for alert in alerts]
147
+ df_alerts = pd.DataFrame(alerts_list, columns=['Data Quality Issue', 'Category'])
148
+
149
+ return df_statistics, df_alerts
150
+ # Main Function
151
+ def main(table):
152
+ schema = get_table_schema(table)
153
+ df = get_data_df(schema)
154
+ df_statistics, df_alerts = statistics(df)
155
+ describe_cat, describe_num = describe(df)
156
+
157
+ tests = run_llm(df)
158
+ print(tests)
159
+ if isinstance(tests, Exception):
160
+ tests = pd.DataFrame([{"error": f"❌ Unable to get the SQL query based on the text. {tests}"}])
161
+ return df.head(10), df_statistics, df_alerts, describe_cat, describe_num, tests, pd.DataFrame([])
162
+
163
+ tests_df = pd.DataFrame(tests)
164
+ tests_df.rename(columns={tests_df.columns[0]: 'Column', tests_df.columns[1]: 'Rule Name', tests_df.columns[2]: 'Rules' }, inplace=True)
165
+ pandera_results = validate_pandera(tests, df)
166
+
167
+ return df.head(10), df_statistics, df_alerts, describe_cat, describe_num, tests_df, pandera_results
168
+
169
+ # Custom CSS styling
170
+ custom_css = """
171
+ .gradio-container {
172
+ background-color: #f0f4f8;
173
+ }
174
+ .logo {
175
+ max-width: 200px;
176
+ margin: 20px auto;
177
+ display: block;
178
+ }
179
+ .gr-button {
180
+ background-color: #4a90e2 !important;
181
+ }
182
+ .gr-button:hover {
183
+ background-color: #3a7bc8 !important;
184
+ }
185
  """
186
+
187
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="purple", secondary_hue="indigo"), css=custom_css) as demo:
188
+ gr.Image("logo.png", label=None, show_label=False, container=False, height=100)
189
+
190
+ gr.Markdown("""
191
+ <div style='text-align: center;'>
192
+ <strong style='font-size: 36px;'>Dataset Test Workflow</strong>
193
+ <br>
194
+ <span style='font-size: 20px;'>Implement and Automate Data Validation Processes.</span>
195
+ </div>
196
+ """)
197
+
198
+ with gr.Row():
199
+ with gr.Column(scale=1):
200
+ schema_dropdown = gr.Dropdown(choices=get_schemas(), label="Select Schema", interactive=True)
201
+ tables_dropdown = gr.Dropdown(choices=[], label="Available Tables", value=None)
202
+ with gr.Row():
203
+ generate_query_button = gr.Button("Validate Data", variant="primary")
204
+
205
+ with gr.Column(scale=2):
206
+ with gr.Tabs():
207
+
208
+ with gr.Tab("Description"):
209
+ with gr.Row():
210
+ with gr.Column(min_width=220):
211
+ data_description = gr.DataFrame(label="Data Description", value=[], interactive=False)
212
+ with gr.Row():
213
+ with gr.Column(min_width=320):
214
+ describe_cat = gr.DataFrame(label="Categorical Information", value=[], interactive=False)
215
+ with gr.Column(min_width=320):
216
+ describe_num = gr.DataFrame(label="Numerical Information", value=[], interactive=False)
217
+
218
+ with gr.Tab("Alerts"):
219
+ data_alerts = gr.DataFrame(label="Alerts", value=[], interactive=False)
220
+
221
+ with gr.Tab("Rules & Validations"):
222
+ tests_output = gr.DataFrame(label="Validation Rules", value=[], interactive=False)
223
+ test_result_output = gr.DataFrame(label="Validation Result", value=[], interactive=False)
224
+
225
+ with gr.Tab("Data"):
226
+ result_output = gr.DataFrame(label="Dataframe (10 Rows)", value=[], interactive=False)
227
+
228
+ schema_dropdown.change(update_table_names, inputs=schema_dropdown, outputs=tables_dropdown)
229
+ generate_query_button.click(main, inputs=[tables_dropdown], outputs=[result_output, data_description, data_alerts, describe_cat, describe_num, tests_output, test_result_output])
230
+
231
 
232
 
233
  if __name__ == "__main__":
234
+ demo.launch(debug=True)
logo.png ADDED
prompt.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ PROMPT_PANDERA = """
2
+ You are a data quality engineer. Your role is to create deterministic rules to validate the quality of a dataset using **Pandera**.
3
+ You will be provided with the first few rows of data below that represents the dataset for which you need to create validation rules. Please note that this is only a sample of the data, and there may be additional rows and categorical columns that are not fully represented in the sample. Keep in mind that the sample may not cover all possible values, but the validation rules must handle all data in the dataset.
4
+
5
+ Follow this process:
6
+
7
+ 1. **Observe the sample data.**
8
+ 2. **For each column**, create a validation rule using Pandera syntax.
9
+ Here are the valid pandera check class methods DO NOT USE ANYOTHER METHODS OTHER THAN THE BELOW GIVEN METHODS:
10
+ [
11
+ 'pa.Check.between(min_value, max_value, include_min=True, include_max=True, **kwargs)',
12
+ 'pa.Check.eq(value, **kwargs)',
13
+ 'pa.Check.equal_to(value, **kwargs)',
14
+ 'pa.Check.ge(min_value, **kwargs)',
15
+ 'pa.Check.greater_than(min_value, **kwargs)',
16
+ 'pa.Check.greater_than_or_equal_to(min_value, **kwargs)',
17
+ 'pa.Check.gt(min_value, **kwargs)',
18
+ 'pa.Check.in_range(min_value, max_value, include_min=True, include_max=True, **kwargs)',
19
+ 'pa.Check.isin(allowed_values, **kwargs)',
20
+ 'pa.Check.le(max_value, **kwargs)',
21
+ 'pa.Check.less_than(max_value, **kwargs)',
22
+ 'pa.Check.less_than_or_equal_to(max_value, **kwargs)',
23
+ 'pa.Check.lt(max_value, **kwargs)',
24
+ 'pa.Check.ne(value, **kwargs)',
25
+ 'pa.Check.not_equal_to(value, **kwargs)',
26
+ 'pa.Check.notin(forbidden_values, **kwargs)',
27
+ 'pa.Check.str_contains(pattern, **kwargs)',
28
+ 'pa.Check.str_endswith(string, **kwargs)',
29
+ 'pa.Check.str_length(min_value=None, max_value=None, **kwargs)',
30
+ 'pa.Check.str_matches(pattern, **kwargs)',
31
+ 'pa.Check.str_startswith(string, **kwargs)',
32
+ 'pa.Check.unique_values_eq(values, **kwargs)'
33
+ ]
34
+ ALSO DONT USE REGEX FOR VALIDATIONS
35
+ 3. Ensure that each rule specifies the expected data type and applies necessary checks such as:
36
+ name argument should be a valid column name. DO NOT USE ANYOTHER PANDERA
37
+ - **Data Type Validation** (e.g., `pa.Column(int, nullable=False, name="age")` ensures integers)
38
+ - **Non-null Check** (e.g., `pa.Column(str, nullable=False, name="name")` to ensure no nulls are allowed)
39
+ - **Unique Value Check** (e.g., `pa.Column(int, unique=True, name="ID")` for uniqueness)
40
+ - **Range or Bound Checks** (e.g., `pa.Column(float, checks=pa.Check.in_range(min_value=0, max_value=100), name="score")` for numerical ranges)
41
+ - **Allowed Value Checks** (e.g., `pa.Column(str, checks=pa.Check.isin([value1, value2]), name="gender")` to restrict values to a set)
42
+ - **Custom Validation Logic** using `pa.Column(int, checks=pa.Check(lambda x: x % 2 == 0), name="even_number")` with lambda functions (e.g., custom logic for even numbers or string patterns)
43
+ FOR DATETIME OR DATE COLUMN USE THE BELOW VALIDATION DO NOT CONISER IT AS INT OR FLOAT
44
+ - **DateTime or Date Validation** (e.g., `pa.Column(pa.dtypes.Timestamp, nullable=False), name="date_column")` to ensure dates or datetime)
45
+
46
+ For each column, provide a **column name**, **rule name** and a pandera_rule. Example structure:
47
+
48
+ ```json
49
+ [
50
+ {
51
+ "column_name": "age",
52
+ "rule_name": "Ensure Column is Integer",
53
+ "pandera_rule": "Column(int, nullable=False, name='age')"
54
+ },
55
+ {
56
+ "column_name": "ID",
57
+ "rule_name": "Unique Identifier Check",
58
+ "pandera_rule": "Column(int, unique=True, name='ID')"
59
+ }
60
+ ]
61
+ 3 Repeat this process for max 5 columns in the dataset. If the data is less than 5 columns than include all columns. Group all the rules into a single JSON object and ensure that there is at least one validation rule for each column.
62
+ Return the final rules as a single JSON object, ensuring that each column is thoroughly validated based on the observations of the sample data.
63
+ DO NOT RETURN ANYTHING OR ANY EXPLAINATION OTHER THAN JSON
64
+ """
requirements.txt CHANGED
@@ -1 +1,7 @@
1
- huggingface_hub==0.22.2
 
 
 
 
 
 
 
1
+ torch
2
+ huggingface_hub
3
+ accelerate
4
+ transformers
5
+ duckdb
6
+ pandera
7
+ ydata-profiling