parqv 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- parqv/__init__.py +0 -0
- parqv/app.py +131 -0
- parqv/parquet_handler.py +389 -0
- parqv/parqv.css +150 -0
- parqv/views/__init__.py +0 -0
- parqv/views/data_view.py +68 -0
- parqv/views/metadata_view.py +19 -0
- parqv/views/row_group_view.py +33 -0
- parqv/views/schema_view.py +187 -0
- parqv-0.1.0.dist-info/METADATA +91 -0
- parqv-0.1.0.dist-info/RECORD +15 -0
- parqv-0.1.0.dist-info/WHEEL +5 -0
- parqv-0.1.0.dist-info/entry_points.txt +2 -0
- parqv-0.1.0.dist-info/licenses/LICENSE +201 -0
- parqv-0.1.0.dist-info/top_level.txt +1 -0
parqv/__init__.py
ADDED
File without changes
|
parqv/app.py
ADDED
@@ -0,0 +1,131 @@
|
|
1
|
+
import sys
|
2
|
+
from pathlib import Path
|
3
|
+
import logging
|
4
|
+
from logging.handlers import RotatingFileHandler
|
5
|
+
from typing import Optional
|
6
|
+
|
7
|
+
from textual.app import App, ComposeResult, Binding
|
8
|
+
from textual.containers import Container
|
9
|
+
from textual.widgets import Header, Footer, Static, Label, TabbedContent, TabPane
|
10
|
+
|
11
|
+
from .parquet_handler import ParquetHandler, ParquetHandlerError
|
12
|
+
from .views.metadata_view import MetadataView
|
13
|
+
from .views.schema_view import SchemaView
|
14
|
+
from .views.data_view import DataView
|
15
|
+
from .views.row_group_view import RowGroupView
|
16
|
+
|
17
|
+
LOG_FILENAME = "parqv.log"
|
18
|
+
file_handler = RotatingFileHandler(
|
19
|
+
LOG_FILENAME, maxBytes=1024 * 1024 * 5, backupCount=3, encoding="utf-8"
|
20
|
+
)
|
21
|
+
logging.basicConfig(
|
22
|
+
level=logging.DEBUG,
|
23
|
+
format="%(asctime)s [%(levelname)-5.5s] %(name)s (%(filename)s:%(lineno)d) - %(message)s",
|
24
|
+
handlers=[file_handler], # Log to file
|
25
|
+
)
|
26
|
+
|
27
|
+
log = logging.getLogger(__name__)
|
28
|
+
|
29
|
+
|
30
|
+
class ParqV(App[None]):
|
31
|
+
"""A Textual app to visualize Parquet files."""
|
32
|
+
|
33
|
+
CSS_PATH = "parqv.css"
|
34
|
+
BINDINGS = [
|
35
|
+
Binding("q", "quit", "Quit", priority=True),
|
36
|
+
]
|
37
|
+
|
38
|
+
# App State
|
39
|
+
file_path: Optional[Path] = None
|
40
|
+
handler: Optional[ParquetHandler] = None
|
41
|
+
error_message: Optional[str] = None
|
42
|
+
|
43
|
+
def __init__(self, file_path_str: Optional[str] = None, *args, **kwargs):
|
44
|
+
super().__init__(*args, **kwargs)
|
45
|
+
log.info("Initializing ParqVApp...")
|
46
|
+
if file_path_str:
|
47
|
+
self.file_path = Path(file_path_str)
|
48
|
+
log.info(f"Attempting to load file: {self.file_path}")
|
49
|
+
try:
|
50
|
+
# Initialize the Parquet handler on app start
|
51
|
+
self.handler = ParquetHandler(self.file_path)
|
52
|
+
log.info("Parquet handler initialized successfully.")
|
53
|
+
except ParquetHandlerError as e:
|
54
|
+
self.error_message = str(e)
|
55
|
+
log.error(f"Failed to initialize handler: {e}", exc_info=True)
|
56
|
+
except Exception as e:
|
57
|
+
self.error_message = (
|
58
|
+
f"An unexpected error occurred during initialization: {e}"
|
59
|
+
)
|
60
|
+
log.exception("Unexpected error during app initialization:")
|
61
|
+
|
62
|
+
def compose(self) -> ComposeResult:
|
63
|
+
yield Header()
|
64
|
+
|
65
|
+
if self.error_message:
|
66
|
+
log.error(f"Displaying error message: {self.error_message}")
|
67
|
+
yield Container(
|
68
|
+
Label("Error Loading File:", classes="error-title"),
|
69
|
+
Static(self.error_message, classes="error-content"),
|
70
|
+
)
|
71
|
+
elif self.handler:
|
72
|
+
log.debug("Composing main layout with TabbedContent.")
|
73
|
+
with TabbedContent(id="main-tabs"):
|
74
|
+
with TabPane("Metadata", id="tab-metadata"):
|
75
|
+
yield MetadataView(id="metadata-view")
|
76
|
+
with TabPane("Schema", id="tab-schema"):
|
77
|
+
yield SchemaView(id="schema-view")
|
78
|
+
with TabPane("Data Preview", id="tab-data"):
|
79
|
+
yield DataView(id="data-view")
|
80
|
+
with TabPane("Row Groups", id="tab-rowgroups"):
|
81
|
+
yield RowGroupView(id="rowgroup-view")
|
82
|
+
else:
|
83
|
+
log.warning("No handler available, showing 'no file' message.")
|
84
|
+
yield Container(Label("No file loaded or handler initialization failed."))
|
85
|
+
|
86
|
+
yield Footer()
|
87
|
+
|
88
|
+
def on_mount(self) -> None:
|
89
|
+
log.debug("App mounted.")
|
90
|
+
try:
|
91
|
+
header = self.query_one(Header)
|
92
|
+
if self.handler and self.file_path:
|
93
|
+
header.title = f"parqv - {self.file_path.name}"
|
94
|
+
elif self.error_message:
|
95
|
+
header.title = "parqv - Error"
|
96
|
+
else:
|
97
|
+
header.title = "parqv"
|
98
|
+
except Exception as e:
|
99
|
+
log.error(f"Failed to set header title: {e}")
|
100
|
+
|
101
|
+
|
102
|
+
def action_quit(self) -> None:
|
103
|
+
log.info("Quit action triggered.")
|
104
|
+
self.exit()
|
105
|
+
|
106
|
+
|
107
|
+
# CLI Entry Point
|
108
|
+
def run_app():
|
109
|
+
log.info("--- parqv started ---")
|
110
|
+
if len(sys.argv) < 2:
|
111
|
+
print("Usage: parqv <path_to_parquet_file>")
|
112
|
+
log.error("No file path provided.")
|
113
|
+
sys.exit(1)
|
114
|
+
|
115
|
+
file_path_str = sys.argv[1]
|
116
|
+
file_path = Path(file_path_str)
|
117
|
+
log.debug(f"File path from argument: {file_path}")
|
118
|
+
|
119
|
+
# Basic file validation
|
120
|
+
if not file_path.is_file():
|
121
|
+
print(f"Error: Path is not a file or does not exist: {file_path}")
|
122
|
+
log.error(f"Invalid file path provided: {file_path}")
|
123
|
+
sys.exit(1)
|
124
|
+
|
125
|
+
app = ParqV(file_path_str=file_path_str)
|
126
|
+
app.run()
|
127
|
+
log.info("--- parqv finished ---")
|
128
|
+
|
129
|
+
|
130
|
+
if __name__ == "__main__":
|
131
|
+
run_app()
|
parqv/parquet_handler.py
ADDED
@@ -0,0 +1,389 @@
|
|
1
|
+
import logging
|
2
|
+
from pathlib import Path
|
3
|
+
from typing import Any, Dict, List, Tuple, Optional, Union
|
4
|
+
|
5
|
+
import pandas as pd
|
6
|
+
import pyarrow as pa
|
7
|
+
import pyarrow.compute as pc
|
8
|
+
import pyarrow.parquet as pq
|
9
|
+
|
10
|
+
log = logging.getLogger(__name__)
|
11
|
+
|
12
|
+
|
13
|
+
class ParquetHandlerError(Exception):
|
14
|
+
pass
|
15
|
+
|
16
|
+
|
17
|
+
class ParquetHandler:
|
18
|
+
|
19
|
+
def __init__(self, file_path: Path):
|
20
|
+
self.file_path = file_path
|
21
|
+
self.pq_file: Optional[pq.ParquetFile] = None
|
22
|
+
self.schema: Optional[pa.Schema] = None
|
23
|
+
self.metadata: Optional[pq.FileMetaData] = None
|
24
|
+
try:
|
25
|
+
self.pq_file = pq.ParquetFile(file_path)
|
26
|
+
self.schema = self.pq_file.schema_arrow
|
27
|
+
self.metadata = self.pq_file.metadata
|
28
|
+
except Exception as e:
|
29
|
+
log.exception("Error initializing ParquetHandler")
|
30
|
+
raise ParquetHandlerError(f"Failed to open or read Parquet file: {e}") from e
|
31
|
+
|
32
|
+
def get_metadata_summary(self) -> Dict[str, Any]:
|
33
|
+
if not self.metadata or not self.schema:
|
34
|
+
return {"error": "Metadata or schema not available"}
|
35
|
+
|
36
|
+
created_by = self._decode_metadata_bytes(self.metadata.created_by) or "N/A"
|
37
|
+
summary = {
|
38
|
+
"File Path": str(self.file_path.resolve()),
|
39
|
+
"Size": f"{self.file_path.stat().st_size:,} bytes",
|
40
|
+
"Total Rows": f"{self.metadata.num_rows:,}",
|
41
|
+
"Row Groups": self.metadata.num_row_groups,
|
42
|
+
"Columns": self.metadata.num_columns,
|
43
|
+
"Format Version": self.metadata.format_version,
|
44
|
+
"Creator": created_by,
|
45
|
+
"Schema Fields": len(self.schema.names),
|
46
|
+
}
|
47
|
+
kv_meta = self._decode_key_value_metadata(self.metadata.metadata)
|
48
|
+
if kv_meta:
|
49
|
+
summary["Key Value Metadata"] = kv_meta
|
50
|
+
return summary
|
51
|
+
|
52
|
+
def get_schema_tree_data(self) -> Optional[Dict[str, Any]]:
|
53
|
+
if not self.schema or not self.schema.names:
|
54
|
+
log.warning("Schema is not available or has no fields.")
|
55
|
+
return None
|
56
|
+
|
57
|
+
root_data: Dict[str, Any] = {}
|
58
|
+
for field in self.schema:
|
59
|
+
try:
|
60
|
+
label, children = self._build_schema_tree_nodes(field)
|
61
|
+
root_data[label] = children
|
62
|
+
except Exception as field_e:
|
63
|
+
log.error(f"Error processing schema field '{field.name}': {field_e}", exc_info=True)
|
64
|
+
root_data[f"[red]Error processing: {field.name}[/red]"] = None
|
65
|
+
|
66
|
+
if not root_data:
|
67
|
+
log.warning("Processed schema data resulted in an empty dictionary.")
|
68
|
+
return None
|
69
|
+
|
70
|
+
return root_data
|
71
|
+
|
72
|
+
def get_data_preview(self, num_rows: int = 50) -> Optional[pd.DataFrame]:
|
73
|
+
if not self.pq_file:
|
74
|
+
log.warning("ParquetFile handler not available for data preview.")
|
75
|
+
return None
|
76
|
+
|
77
|
+
tables_to_concat = []
|
78
|
+
rows_accumulated = 0
|
79
|
+
for i in range(self.pq_file.num_row_groups):
|
80
|
+
rg_meta = self.pq_file.metadata.row_group(i)
|
81
|
+
rows_to_read_from_group = min(rg_meta.num_rows, num_rows - rows_accumulated)
|
82
|
+
|
83
|
+
if rows_to_read_from_group <= 0:
|
84
|
+
log.debug(f"Limit {num_rows} reached after {i} groups.")
|
85
|
+
break
|
86
|
+
|
87
|
+
rg_table = self.pq_file.read_row_group(i)
|
88
|
+
tables_to_concat.append(rg_table)
|
89
|
+
rows_accumulated += rg_meta.num_rows
|
90
|
+
|
91
|
+
if not tables_to_concat:
|
92
|
+
log.warning("No row groups read or file is empty.")
|
93
|
+
return pd.DataFrame()
|
94
|
+
|
95
|
+
combined_table = pa.concat_tables(tables_to_concat)
|
96
|
+
preview_table = combined_table.slice(0, num_rows)
|
97
|
+
|
98
|
+
df = preview_table.to_pandas(
|
99
|
+
split_blocks=True, self_destruct=True, date_as_object=False, types_mapper=pd.ArrowDtype
|
100
|
+
)
|
101
|
+
return df
|
102
|
+
|
103
|
+
def get_column_stats(self, column_name: str) -> Dict[str, Any]:
|
104
|
+
if not self.pq_file or not self.schema or not column_name:
|
105
|
+
log.warning("Prerequisites not met for get_column_stats.")
|
106
|
+
return {"error": "File, schema, or column name not available"}
|
107
|
+
|
108
|
+
error_msg: Optional[str] = None
|
109
|
+
field: Optional[pa.Field] = None
|
110
|
+
calculated_stats: Dict[str, Any] = {}
|
111
|
+
|
112
|
+
field = self.schema.field(column_name)
|
113
|
+
col_type = field.type
|
114
|
+
|
115
|
+
table = self.pq_file.read(columns=[column_name])
|
116
|
+
if table.num_rows == 0:
|
117
|
+
log.warning(f"Column '{column_name}' is empty.")
|
118
|
+
return self._create_stats_result(column_name, field, msg="Column is empty (0 rows).")
|
119
|
+
|
120
|
+
column_data = table.column(column_name)
|
121
|
+
# Basic counts
|
122
|
+
total_count = len(column_data)
|
123
|
+
null_count = column_data.null_count
|
124
|
+
valid_count = total_count - null_count
|
125
|
+
calculated_stats["Total Count"] = f"{total_count:,}"
|
126
|
+
calculated_stats["Valid Count"] = f"{valid_count:,}"
|
127
|
+
calculated_stats["Null Count"] = f"{null_count:,}"
|
128
|
+
calculated_stats[
|
129
|
+
"Null Percentage"] = f"{(null_count / total_count * 100):.2f}%" if total_count > 0 else "N/A"
|
130
|
+
|
131
|
+
# Type-specific calculations
|
132
|
+
if valid_count > 0:
|
133
|
+
valid_data = column_data.drop_null()
|
134
|
+
if pa.types.is_integer(col_type) or pa.types.is_floating(col_type):
|
135
|
+
calculated_stats.update(self._calculate_numeric_stats(valid_data))
|
136
|
+
elif pa.types.is_temporal(col_type):
|
137
|
+
calculated_stats.update(self._calculate_temporal_stats(valid_data))
|
138
|
+
elif pa.types.is_string(col_type) or pa.types.is_large_string(col_type):
|
139
|
+
calculated_stats.update(self._calculate_string_stats(valid_data))
|
140
|
+
elif pa.types.is_boolean(col_type):
|
141
|
+
calculated_stats.update(self._calculate_boolean_stats(valid_data))
|
142
|
+
else:
|
143
|
+
log.debug("No valid data points for calculation.")
|
144
|
+
|
145
|
+
metadata_stats, metadata_stats_error = self._get_stats_from_metadata(column_name)
|
146
|
+
return self._create_stats_result(
|
147
|
+
column_name, field, calculated_stats, metadata_stats, metadata_stats_error, error_msg
|
148
|
+
)
|
149
|
+
|
150
|
+
def get_row_group_info(self) -> List[Dict[str, Any]]:
|
151
|
+
if not self.metadata:
|
152
|
+
log.warning("Metadata not available for row group info.")
|
153
|
+
return []
|
154
|
+
groups = []
|
155
|
+
num_groups = self.metadata.num_row_groups
|
156
|
+
|
157
|
+
for i in range(num_groups):
|
158
|
+
try:
|
159
|
+
rg_meta = self.metadata.row_group(i)
|
160
|
+
num_rows = getattr(rg_meta, 'num_rows', 'N/A')
|
161
|
+
size = getattr(rg_meta, 'total_byte_size', 'N/A')
|
162
|
+
comp_size_val = getattr(rg_meta, 'total_compressed_size', -1)
|
163
|
+
comp_size = f"{comp_size_val:,}" if isinstance(comp_size_val, int) and comp_size_val > 0 else "N/A"
|
164
|
+
|
165
|
+
groups.append({
|
166
|
+
"Group": i,
|
167
|
+
"Rows": f"{num_rows:,}" if isinstance(num_rows, int) else num_rows,
|
168
|
+
"Size (bytes)": f"{size:,}" if isinstance(size, int) else size,
|
169
|
+
"Size (comp.)": comp_size,
|
170
|
+
})
|
171
|
+
except Exception as e:
|
172
|
+
log.error(f"Error reading metadata for row group {i}", exc_info=True)
|
173
|
+
groups.append({"Group": i, "Rows": "Error", "Size (bytes)": "Error", "Size (comp.)": "Error"})
|
174
|
+
return groups
|
175
|
+
|
176
|
+
def _decode_metadata_bytes(self, value: Optional[bytes]) -> Optional[str]:
|
177
|
+
if isinstance(value, bytes):
|
178
|
+
try:
|
179
|
+
return value.decode('utf-8', errors='replace')
|
180
|
+
except Exception as e:
|
181
|
+
log.warning(f"Could not decode metadata bytes: {e}")
|
182
|
+
return repr(value)
|
183
|
+
return value
|
184
|
+
|
185
|
+
def _decode_key_value_metadata(self, kv_meta: Optional[Dict[bytes, bytes]]) -> Optional[Dict[str, str]]:
|
186
|
+
if not kv_meta:
|
187
|
+
return None
|
188
|
+
decoded_kv = {}
|
189
|
+
try:
|
190
|
+
for k, v in kv_meta.items():
|
191
|
+
key_str = self._decode_metadata_bytes(k) or repr(k)
|
192
|
+
val_str = self._decode_metadata_bytes(v) or repr(v)
|
193
|
+
decoded_kv[key_str] = val_str
|
194
|
+
return decoded_kv
|
195
|
+
except Exception as e:
|
196
|
+
log.warning(f"Could not decode key-value metadata: {e}")
|
197
|
+
return {"error": f"Error decoding: {e}"}
|
198
|
+
|
199
|
+
def _format_pyarrow_type(self, field_type: pa.DataType) -> str:
|
200
|
+
if pa.types.is_timestamp(field_type):
|
201
|
+
return f"TIMESTAMP(unit={field_type.unit}, tz={field_type.tz})"
|
202
|
+
|
203
|
+
if pa.types.is_decimal128(field_type) or pa.types.is_decimal256(field_type):
|
204
|
+
return f"DECIMAL({field_type.precision}, {field_type.scale})"
|
205
|
+
|
206
|
+
if pa.types.is_list(field_type) or pa.types.is_large_list(field_type):
|
207
|
+
return f"LIST<{self._format_pyarrow_type(field_type.value_type)}>"
|
208
|
+
|
209
|
+
if pa.types.is_struct(field_type):
|
210
|
+
return f"STRUCT<{field_type.num_fields} fields>"
|
211
|
+
|
212
|
+
if pa.types.is_map(field_type):
|
213
|
+
return f"MAP<{self._format_pyarrow_type(field_type.key_type)}, {self._format_pyarrow_type(field_type.item_type)}>"
|
214
|
+
|
215
|
+
return str(field_type).upper()
|
216
|
+
|
217
|
+
def _build_schema_tree_nodes(self, field: pa.Field) -> Tuple[str, Optional[Dict]]:
|
218
|
+
node_label = f"[bold]{field.name}[/] ({self._format_pyarrow_type(field.type)})"
|
219
|
+
if not field.nullable:
|
220
|
+
node_label += " [red]REQUIRED[/]"
|
221
|
+
|
222
|
+
children_data: Dict[str, Any] = {}
|
223
|
+
field_type = field.type
|
224
|
+
|
225
|
+
if pa.types.is_struct(field_type):
|
226
|
+
for i in range(field_type.num_fields):
|
227
|
+
child_label, grandchild_data = self._build_schema_tree_nodes(field_type.field(i))
|
228
|
+
children_data[child_label] = grandchild_data
|
229
|
+
|
230
|
+
elif pa.types.is_list(field_type) or pa.types.is_large_list(field_type):
|
231
|
+
element_field = pa.field("item", field_type.value_type, nullable=True)
|
232
|
+
child_label, grandchild_data = self._build_schema_tree_nodes(element_field)
|
233
|
+
children_data[child_label] = grandchild_data
|
234
|
+
|
235
|
+
elif pa.types.is_map(field_type):
|
236
|
+
key_field = pa.field("key", field_type.key_type, nullable=False)
|
237
|
+
value_field = pa.field("value", field_type.item_type, nullable=True)
|
238
|
+
key_label, _ = self._build_schema_tree_nodes(key_field)
|
239
|
+
value_label, value_grandchild = self._build_schema_tree_nodes(value_field)
|
240
|
+
children_data[key_label] = None
|
241
|
+
children_data[value_label] = value_grandchild
|
242
|
+
|
243
|
+
return node_label, children_data if children_data else None
|
244
|
+
|
245
|
+
def _calculate_numeric_stats(self, valid_data: pa.ChunkedArray) -> Dict[str, Any]:
|
246
|
+
stats: Dict[str, Any] = {}
|
247
|
+
try:
|
248
|
+
stats["Min"] = pc.min(valid_data).as_py()
|
249
|
+
except Exception as e:
|
250
|
+
log.warning(f"Min calc error: {e}");
|
251
|
+
stats["Min"] = "Error"
|
252
|
+
try:
|
253
|
+
stats["Max"] = pc.max(valid_data).as_py()
|
254
|
+
except Exception as e:
|
255
|
+
log.warning(f"Max calc error: {e}");
|
256
|
+
stats["Max"] = "Error"
|
257
|
+
try:
|
258
|
+
stats["Mean"] = f"{pc.mean(valid_data).as_py():.4f}"
|
259
|
+
except Exception as e:
|
260
|
+
log.warning(f"Mean calc error: {e}");
|
261
|
+
stats["Mean"] = "Error"
|
262
|
+
try:
|
263
|
+
stats["StdDev"] = f"{pc.stddev(valid_data, ddof=1).as_py():.4f}"
|
264
|
+
except Exception as e:
|
265
|
+
log.warning(f"StdDev calc error: {e}");
|
266
|
+
stats["StdDev"] = "Error"
|
267
|
+
return stats
|
268
|
+
|
269
|
+
def _calculate_temporal_stats(self, valid_data: pa.ChunkedArray) -> Dict[str, Any]:
|
270
|
+
stats: Dict[str, Any] = {}
|
271
|
+
try:
|
272
|
+
stats["Min"] = pc.min(valid_data).as_py()
|
273
|
+
except Exception as e:
|
274
|
+
log.warning(f"Min calc error (temporal): {e}");
|
275
|
+
stats["Min"] = "Error"
|
276
|
+
try:
|
277
|
+
stats["Max"] = pc.max(valid_data).as_py()
|
278
|
+
except Exception as e:
|
279
|
+
log.warning(f"Max calc error (temporal): {e}");
|
280
|
+
stats["Max"] = "Error"
|
281
|
+
return stats
|
282
|
+
|
283
|
+
def _calculate_string_stats(self, valid_data: pa.ChunkedArray) -> Dict[str, Any]:
|
284
|
+
stats: Dict[str, Any] = {}
|
285
|
+
try:
|
286
|
+
stats["Distinct Count"] = f"{pc.count_distinct(valid_data).as_py():,}"
|
287
|
+
except Exception as e:
|
288
|
+
log.warning(f"Distinct count error: {e}");
|
289
|
+
stats["Distinct Count"] = "Error"
|
290
|
+
# TopN removed as requested
|
291
|
+
return stats
|
292
|
+
|
293
|
+
def _calculate_boolean_stats(self, valid_data: pa.ChunkedArray) -> Dict[str, Any]:
|
294
|
+
stats: Dict[str, Any] = {}
|
295
|
+
try:
|
296
|
+
value_counts_table = valid_data.value_counts()
|
297
|
+
if isinstance(value_counts_table, pa.Table):
|
298
|
+
counts_df = value_counts_table.to_pandas()
|
299
|
+
elif isinstance(value_counts_table, pa.StructArray):
|
300
|
+
try:
|
301
|
+
counts_df = value_counts_table.flatten().to_pandas()
|
302
|
+
except NotImplementedError:
|
303
|
+
counts_df = pd.DataFrame(value_counts_table.to_pylist()) # Fallback
|
304
|
+
|
305
|
+
else:
|
306
|
+
counts_df = pd.DataFrame(value_counts_table.to_pylist())
|
307
|
+
|
308
|
+
if 'values' in counts_df.columns and 'counts' in counts_df.columns:
|
309
|
+
stats["Value Counts"] = counts_df.set_index('values')['counts'].to_dict()
|
310
|
+
elif len(counts_df.columns) == 2: # Assume first is value, second is count
|
311
|
+
stats["Value Counts"] = counts_df.set_index(counts_df.columns[0])[counts_df.columns[1]].to_dict()
|
312
|
+
else:
|
313
|
+
log.warning("Could not parse boolean value counts structure.")
|
314
|
+
stats["Value Counts"] = "Could not parse structure"
|
315
|
+
|
316
|
+
except Exception as vc_e:
|
317
|
+
log.warning(f"Boolean value count error: {vc_e}");
|
318
|
+
stats["Value Counts"] = "Error calculating"
|
319
|
+
return stats
|
320
|
+
|
321
|
+
def _extract_stats_for_single_group(
|
322
|
+
self, rg_meta: pq.RowGroupMetaData, col_index: int
|
323
|
+
) -> Union[str, Dict[str, Any]]:
|
324
|
+
|
325
|
+
if col_index >= rg_meta.num_columns:
|
326
|
+
log.warning(
|
327
|
+
f"Column index {col_index} out of bounds for row group "
|
328
|
+
f"with {rg_meta.num_columns} columns."
|
329
|
+
)
|
330
|
+
return "Index Error"
|
331
|
+
|
332
|
+
col_chunk_meta = rg_meta.column(col_index)
|
333
|
+
stats = col_chunk_meta.statistics
|
334
|
+
|
335
|
+
if not stats:
|
336
|
+
return "No stats"
|
337
|
+
|
338
|
+
has_min_max = getattr(stats, 'has_min_max', False)
|
339
|
+
has_distinct = getattr(stats, 'has_distinct_count', False)
|
340
|
+
|
341
|
+
return {
|
342
|
+
"min": getattr(stats, 'min', 'N/A') if has_min_max else "N/A",
|
343
|
+
"max": getattr(stats, 'max', 'N/A') if has_min_max else "N/A",
|
344
|
+
"nulls": getattr(stats, 'null_count', 'N/A'),
|
345
|
+
"distinct": getattr(stats, 'distinct_count', 'N/A') if has_distinct else "N/A",
|
346
|
+
}
|
347
|
+
|
348
|
+
def _get_stats_from_metadata(self, column_name: str) -> Tuple[Dict[str, Any], Optional[str]]:
|
349
|
+
metadata_stats: Dict[str, Any] = {}
|
350
|
+
if not self.metadata or not self.schema:
|
351
|
+
log.warning("Metadata or Schema not available for _get_stats_from_metadata.")
|
352
|
+
return {}, "Metadata or Schema not available"
|
353
|
+
col_index = self.schema.get_field_index(column_name)
|
354
|
+
|
355
|
+
for i in range(self.metadata.num_row_groups):
|
356
|
+
group_key = f"RG {i}"
|
357
|
+
try:
|
358
|
+
rg_meta = self.metadata.row_group(i)
|
359
|
+
metadata_stats[group_key] = self._extract_stats_for_single_group(
|
360
|
+
rg_meta, col_index
|
361
|
+
)
|
362
|
+
except Exception as e:
|
363
|
+
log.warning(
|
364
|
+
f"Error processing metadata for row group {i}, column '{column_name}': {e}"
|
365
|
+
)
|
366
|
+
metadata_stats[group_key] = f"Read Error: {e}"
|
367
|
+
|
368
|
+
return metadata_stats, None
|
369
|
+
|
370
|
+
def _create_stats_result(
|
371
|
+
self,
|
372
|
+
column_name: str,
|
373
|
+
field: Optional[pa.Field],
|
374
|
+
calculated_stats: Optional[Dict] = None,
|
375
|
+
metadata_stats: Optional[Dict] = None,
|
376
|
+
metadata_stats_error: Optional[str] = None,
|
377
|
+
calculation_error: Optional[str] = None,
|
378
|
+
message: Optional[str] = None
|
379
|
+
) -> Dict[str, Any]:
|
380
|
+
return {
|
381
|
+
"column": column_name,
|
382
|
+
"type": self._format_pyarrow_type(field.type) if field else "Unknown",
|
383
|
+
"nullable": field.nullable if field else "Unknown",
|
384
|
+
"calculated": calculated_stats if calculated_stats else None,
|
385
|
+
"basic_metadata_stats": metadata_stats if metadata_stats else None,
|
386
|
+
"metadata_stats_error": metadata_stats_error,
|
387
|
+
"error": calculation_error,
|
388
|
+
"message": message
|
389
|
+
}
|
parqv/parqv.css
ADDED
@@ -0,0 +1,150 @@
|
|
1
|
+
/* --- Base Screen Styles --- */
|
2
|
+
Screen {
|
3
|
+
background: $surface;
|
4
|
+
color: $text;
|
5
|
+
}
|
6
|
+
|
7
|
+
/* --- Header & Footer Styles --- */
|
8
|
+
Header {
|
9
|
+
background: $primary;
|
10
|
+
}
|
11
|
+
Footer {
|
12
|
+
background: $primary-darken-1;
|
13
|
+
}
|
14
|
+
Footer > .footer--key {
|
15
|
+
color: $text-muted;
|
16
|
+
}
|
17
|
+
Footer > .footer--highlight-key {
|
18
|
+
background: $accent-darken-1;
|
19
|
+
color: $text;
|
20
|
+
text-style: bold;
|
21
|
+
}
|
22
|
+
|
23
|
+
/* --- Tabbed Interface Styles --- */
|
24
|
+
TabbedContent {
|
25
|
+
height: 100%;
|
26
|
+
}
|
27
|
+
TabbedContent > Tabs {
|
28
|
+
background: $primary-darken-1;
|
29
|
+
color: $text-muted;
|
30
|
+
}
|
31
|
+
TabbedContent > Tabs > Tab {
|
32
|
+
padding: 1 2;
|
33
|
+
}
|
34
|
+
TabbedContent > Tabs > Tab:hover {
|
35
|
+
background: $primary;
|
36
|
+
}
|
37
|
+
TabbedContent > Tabs > .--current {
|
38
|
+
background: $accent;
|
39
|
+
color: $text;
|
40
|
+
text-style: bold;
|
41
|
+
}
|
42
|
+
TabbedContent > Content {
|
43
|
+
padding: 1 2;
|
44
|
+
height: 1fr;
|
45
|
+
width: 100%;
|
46
|
+
overflow: hidden;
|
47
|
+
}
|
48
|
+
TabbedContent > Content > * {
|
49
|
+
height: 100%;
|
50
|
+
width: 100%;
|
51
|
+
}
|
52
|
+
|
53
|
+
/* --- Schema Tab (#schema-view - VerticalScroll) --- */
|
54
|
+
#schema-view {
|
55
|
+
padding: 0;
|
56
|
+
}
|
57
|
+
#schema-view > ListView#column-list-view {
|
58
|
+
border: round $accent-lighten-2;
|
59
|
+
margin-bottom: 1;
|
60
|
+
background: $primary-background;
|
61
|
+
overflow: auto;
|
62
|
+
}
|
63
|
+
#schema-view > ListView#column-list-view > ListItem {
|
64
|
+
padding: 0 1;
|
65
|
+
height: auto;
|
66
|
+
}
|
67
|
+
#schema-view > ListView#column-list-view > ListItem.--highlight {
|
68
|
+
background: $accent;
|
69
|
+
color: $text;
|
70
|
+
}
|
71
|
+
#schema-view > ListView#column-list-view > ListItem.--highlight Label {
|
72
|
+
color: $text;
|
73
|
+
}
|
74
|
+
#schema-view > LoadingIndicator#schema-loading-indicator {
|
75
|
+
margin: 1 0;
|
76
|
+
width: 100%;
|
77
|
+
text-align: center;
|
78
|
+
}
|
79
|
+
#schema-view > Container#schema-stats-content {
|
80
|
+
padding: 1;
|
81
|
+
overflow: auto;
|
82
|
+
}
|
83
|
+
#schema-view .stats-line {
|
84
|
+
margin-bottom: 0;
|
85
|
+
height: auto;
|
86
|
+
width: 100%;
|
87
|
+
}
|
88
|
+
#schema-view .stats-code {
|
89
|
+
background: $panel-darken-1;
|
90
|
+
border: solid $accent-lighten-1;
|
91
|
+
padding: 0 1;
|
92
|
+
margin: 1 0;
|
93
|
+
width: 100%;
|
94
|
+
height: auto;
|
95
|
+
overflow: auto;
|
96
|
+
}
|
97
|
+
#schema-view .stats-error {
|
98
|
+
color: $error;
|
99
|
+
}
|
100
|
+
|
101
|
+
/* --- Metadata Tab (#metadata-view - VerticalScroll) --- */
|
102
|
+
#metadata-view {
|
103
|
+
overflow-y: auto;
|
104
|
+
}
|
105
|
+
#metadata-view > Pretty {
|
106
|
+
width: 100%;
|
107
|
+
}
|
108
|
+
|
109
|
+
/* --- Data Preview Tab (#data-view - Container) --- */
|
110
|
+
#data-view {
|
111
|
+
}
|
112
|
+
#data-view > DataTable {
|
113
|
+
height: 100%;
|
114
|
+
width: 100%;
|
115
|
+
}
|
116
|
+
|
117
|
+
/* --- Row Groups Tab (#rowgroup-view - VerticalScroll) --- */
|
118
|
+
#rowgroup-view {
|
119
|
+
overflow-y: auto;
|
120
|
+
}
|
121
|
+
#rowgroup-view > DataTable {
|
122
|
+
width: 100%;
|
123
|
+
}
|
124
|
+
|
125
|
+
/* --- General Widget Styles --- */
|
126
|
+
DataTable {
|
127
|
+
margin-top: 1;
|
128
|
+
}
|
129
|
+
DataTable > Header {
|
130
|
+
background: $secondary;
|
131
|
+
color: $text;
|
132
|
+
text-style: bold;
|
133
|
+
}
|
134
|
+
DataTable > Body > Row.--cursor {
|
135
|
+
background: $accent;
|
136
|
+
color: $text;
|
137
|
+
}
|
138
|
+
DataTable > Body > Row:hover {
|
139
|
+
background: $secondary-darken-2;
|
140
|
+
}
|
141
|
+
|
142
|
+
/* --- Error Message Styles (Used in App Level Error) --- */
|
143
|
+
.error-title {
|
144
|
+
color: $error;
|
145
|
+
text-style: bold;
|
146
|
+
margin-bottom: 1;
|
147
|
+
}
|
148
|
+
.error-content {
|
149
|
+
color: $error;
|
150
|
+
}
|
parqv/views/__init__.py
ADDED
File without changes
|
parqv/views/data_view.py
ADDED
@@ -0,0 +1,68 @@
|
|
1
|
+
import logging
|
2
|
+
from typing import Optional
|
3
|
+
|
4
|
+
import pandas as pd
|
5
|
+
from textual.app import ComposeResult
|
6
|
+
from textual.containers import Container
|
7
|
+
from textual.widgets import DataTable, Static
|
8
|
+
|
9
|
+
log = logging.getLogger(__name__)
|
10
|
+
|
11
|
+
|
12
|
+
class DataView(Container):
|
13
|
+
DEFAULT_ROWS = 50
|
14
|
+
|
15
|
+
def compose(self) -> ComposeResult:
|
16
|
+
yield DataTable(id="data-table")
|
17
|
+
|
18
|
+
def on_mount(self) -> None:
|
19
|
+
self.load_data()
|
20
|
+
|
21
|
+
def load_data(self):
|
22
|
+
table: Optional[DataTable] = self.query_one("#data-table", DataTable)
|
23
|
+
|
24
|
+
try:
|
25
|
+
table.clear(columns=True)
|
26
|
+
except Exception as e:
|
27
|
+
log.error(f"Error clearing DataTable: {e}")
|
28
|
+
try:
|
29
|
+
table.remove()
|
30
|
+
table = DataTable(id="data-table")
|
31
|
+
self.mount(table)
|
32
|
+
except Exception as remount_e:
|
33
|
+
log.error(f"Failed to remount DataTable: {remount_e}")
|
34
|
+
self.mount(Static("[red]Error initializing data table.[/red]", classes="error-content"))
|
35
|
+
return
|
36
|
+
|
37
|
+
try:
|
38
|
+
if not self.app.handler:
|
39
|
+
self.mount(Static("Parquet handler not available.", classes="error-content"))
|
40
|
+
return
|
41
|
+
|
42
|
+
df: Optional[pd.DataFrame] = self.app.handler.get_data_preview(num_rows=self.DEFAULT_ROWS)
|
43
|
+
|
44
|
+
if df is None:
|
45
|
+
self.mount(Static("Could not load data preview."))
|
46
|
+
return
|
47
|
+
|
48
|
+
if df.empty:
|
49
|
+
self.mount(Static("No data in the preview range or file is empty."))
|
50
|
+
return
|
51
|
+
|
52
|
+
table.cursor_type = "row"
|
53
|
+
columns = [str(col) for col in df.columns]
|
54
|
+
table.add_columns(*columns)
|
55
|
+
rows_data = [
|
56
|
+
tuple(str(item) if pd.notna(item) else "" for item in row)
|
57
|
+
for row in df.itertuples(index=False, name=None)
|
58
|
+
]
|
59
|
+
table.add_rows(rows_data)
|
60
|
+
log.info("DataTable populated successfully.")
|
61
|
+
|
62
|
+
except Exception as e:
|
63
|
+
log.exception("Error loading data preview in DataView:")
|
64
|
+
try:
|
65
|
+
self.query("DataTable, Static").remove()
|
66
|
+
self.mount(Static(f"Error loading data preview: {e}", classes="error-content"))
|
67
|
+
except Exception as display_e:
|
68
|
+
log.error(f"Error displaying error message: {display_e}")
|
@@ -0,0 +1,19 @@
|
|
1
|
+
from textual.containers import VerticalScroll
|
2
|
+
from textual.widgets import Static, Pretty
|
3
|
+
|
4
|
+
|
5
|
+
class MetadataView(VerticalScroll):
|
6
|
+
|
7
|
+
def on_mount(self) -> None:
|
8
|
+
self.load_metadata()
|
9
|
+
|
10
|
+
def load_metadata(self):
|
11
|
+
try:
|
12
|
+
if self.app.handler:
|
13
|
+
meta_data = self.app.handler.get_metadata_summary()
|
14
|
+
pretty_widget = Pretty(meta_data)
|
15
|
+
self.mount(pretty_widget)
|
16
|
+
else:
|
17
|
+
self.mount(Static("Parquet handler not available.", classes="error-content"))
|
18
|
+
except Exception as e:
|
19
|
+
self.mount(Static(f"Error loading metadata: {e}", classes="error-content"))
|
@@ -0,0 +1,33 @@
|
|
1
|
+
from textual.containers import VerticalScroll
|
2
|
+
from textual.widgets import DataTable, Static
|
3
|
+
|
4
|
+
|
5
|
+
class RowGroupView(VerticalScroll):
|
6
|
+
|
7
|
+
def on_mount(self) -> None:
|
8
|
+
self.load_row_groups()
|
9
|
+
|
10
|
+
def load_row_groups(self):
|
11
|
+
try:
|
12
|
+
if self.app.handler:
|
13
|
+
rg_info_list = self.app.handler.get_row_group_info()
|
14
|
+
|
15
|
+
if rg_info_list:
|
16
|
+
table = DataTable(id="rowgroup-table")
|
17
|
+
table.cursor_type = "row"
|
18
|
+
|
19
|
+
columns = list(rg_info_list[0].keys())
|
20
|
+
table.add_columns(*columns)
|
21
|
+
|
22
|
+
rows_data = [
|
23
|
+
tuple(str(rg.get(col, '')) for col in columns)
|
24
|
+
for rg in rg_info_list
|
25
|
+
]
|
26
|
+
table.add_rows(rows_data)
|
27
|
+
self.mount(table)
|
28
|
+
else:
|
29
|
+
self.mount(Static("No row group information available or file has no row groups."))
|
30
|
+
else:
|
31
|
+
self.mount(Static("Parquet handler not available.", classes="error-content"))
|
32
|
+
except Exception as e:
|
33
|
+
self.mount(Static(f"Error loading row group info: {e}", classes="error-content"))
|
@@ -0,0 +1,187 @@
|
|
1
|
+
import json
|
2
|
+
import logging
|
3
|
+
from typing import Dict, Any, Optional, List, Union
|
4
|
+
|
5
|
+
from rich.text import Text
|
6
|
+
from textual.app import ComposeResult
|
7
|
+
from textual.containers import VerticalScroll, Container
|
8
|
+
from textual.reactive import var
|
9
|
+
from textual.widgets import Static, ListView, ListItem, Label, LoadingIndicator
|
10
|
+
|
11
|
+
log = logging.getLogger(__name__)
|
12
|
+
|
13
|
+
|
14
|
+
class ColumnListItem(ListItem):
|
15
|
+
def __init__(self, column_name: str) -> None:
|
16
|
+
super().__init__(Label(column_name), name=column_name, id=f"col-item-{column_name.replace(' ', '_')}")
|
17
|
+
self.column_name = column_name
|
18
|
+
|
19
|
+
|
20
|
+
def format_stats_for_display(stats_data: Dict[str, Any]) -> List[Union[str, Text]]:
|
21
|
+
if not stats_data:
|
22
|
+
return [Text.from_markup("[red]No statistics data available.[/red]")]
|
23
|
+
|
24
|
+
lines: List[Union[str, Text]] = []
|
25
|
+
col_name = stats_data.get("column", "N/A")
|
26
|
+
col_type = stats_data.get("type", "Unknown")
|
27
|
+
nullable = stats_data.get("nullable", "Unknown")
|
28
|
+
|
29
|
+
lines.append(Text.assemble(("Column: ", "bold"), f"`{col_name}`"))
|
30
|
+
lines.append(Text.assemble(("Type: ", "bold"), f"{col_type} ({'Nullable' if nullable else 'Required'})"))
|
31
|
+
lines.append("─" * (len(col_name) + len(col_type) + 20))
|
32
|
+
|
33
|
+
calc_error = stats_data.get("error")
|
34
|
+
if calc_error:
|
35
|
+
lines.append(Text("Calculation Error:", style="bold red"))
|
36
|
+
lines.append(f"```{calc_error}```")
|
37
|
+
|
38
|
+
calculated = stats_data.get("calculated")
|
39
|
+
if calculated:
|
40
|
+
lines.append(Text("Calculated Statistics:", style="bold"))
|
41
|
+
keys_to_display = [
|
42
|
+
"Total Count", "Valid Count", "Null Count", "Null Percentage",
|
43
|
+
"Min", "Max", "Mean", "StdDev", "Distinct Count", "Value Counts"
|
44
|
+
]
|
45
|
+
for key in keys_to_display:
|
46
|
+
if key in calculated:
|
47
|
+
value = calculated[key]
|
48
|
+
if isinstance(value, dict):
|
49
|
+
lines.append(f" - {key}:")
|
50
|
+
for sub_key, sub_val in value.items():
|
51
|
+
lines.append(f" - {sub_key}: {sub_val:,}")
|
52
|
+
else:
|
53
|
+
lines.append(f" - {key}: {value}")
|
54
|
+
lines.append("")
|
55
|
+
|
56
|
+
meta_stats = stats_data.get("basic_metadata_stats")
|
57
|
+
if meta_stats:
|
58
|
+
lines.append(Text("Stats from File Metadata (Per Row Group):", style="bold"))
|
59
|
+
try:
|
60
|
+
json_str = json.dumps(meta_stats, indent=2, default=str)
|
61
|
+
lines.append(f"```json\n{json_str}\n```")
|
62
|
+
except Exception as e:
|
63
|
+
lines.append(f" (Error formatting metadata: {e})")
|
64
|
+
lines.append("")
|
65
|
+
|
66
|
+
meta_stats_error = stats_data.get("metadata_stats_error")
|
67
|
+
if meta_stats_error:
|
68
|
+
lines.append(Text(f"Metadata Stats Warning: {meta_stats_error}", style="yellow"))
|
69
|
+
|
70
|
+
message = stats_data.get("message")
|
71
|
+
if message and not calculated:
|
72
|
+
lines.append(Text(message, style="italic"))
|
73
|
+
|
74
|
+
return lines
|
75
|
+
|
76
|
+
|
77
|
+
class SchemaView(VerticalScroll):
|
78
|
+
DEFAULT_STATS_MESSAGE = "Select a column above to view statistics."
|
79
|
+
loading = var(False)
|
80
|
+
|
81
|
+
def compose(self) -> ComposeResult:
|
82
|
+
yield ListView(id="column-list-view")
|
83
|
+
yield LoadingIndicator(id="schema-loading-indicator")
|
84
|
+
yield Container(id="schema-stats-content")
|
85
|
+
|
86
|
+
def on_mount(self) -> None:
|
87
|
+
self.query_one("#schema-loading-indicator", LoadingIndicator).styles.display = "none"
|
88
|
+
self.call_later(self.load_column_list)
|
89
|
+
self.call_later(self._update_stats_display, [])
|
90
|
+
|
91
|
+
def load_column_list(self):
|
92
|
+
list_view: Optional[ListView] = None
|
93
|
+
try:
|
94
|
+
list_views = self.query("#column-list-view")
|
95
|
+
if not list_views:
|
96
|
+
log.error("ListView widget (#column-list-view) not found!")
|
97
|
+
return
|
98
|
+
list_view = list_views.first()
|
99
|
+
log.debug("ListView widget found.")
|
100
|
+
|
101
|
+
list_view.clear()
|
102
|
+
|
103
|
+
if self.app.handler and self.app.handler.schema:
|
104
|
+
column_names: List[str] = self.app.handler.schema.names
|
105
|
+
if column_names:
|
106
|
+
for name in column_names:
|
107
|
+
list_view.append(ColumnListItem(name))
|
108
|
+
else:
|
109
|
+
log.warning("Schema has no columns.")
|
110
|
+
list_view.append(ListItem(Label("[yellow]Schema has no columns.[/yellow]")))
|
111
|
+
elif not self.app.handler:
|
112
|
+
log.error("Parquet handler not available.")
|
113
|
+
list_view.append(ListItem(Label("[red]Parquet handler not available.[/red]")))
|
114
|
+
else:
|
115
|
+
log.error("Parquet schema not available.")
|
116
|
+
list_view.append(ListItem(Label("[red]Parquet schema not available.[/red]")))
|
117
|
+
|
118
|
+
except Exception as e:
|
119
|
+
log.exception("Error loading column list in SchemaView:")
|
120
|
+
if list_view:
|
121
|
+
list_view.clear()
|
122
|
+
list_view.append(ListItem(Label(f"[red]Error loading schema view: {e}[/red]")))
|
123
|
+
|
124
|
+
def watch_loading(self, loading: bool) -> None:
|
125
|
+
loading_indicator = self.query_one("#schema-loading-indicator", LoadingIndicator)
|
126
|
+
stats_content = self.query_one("#schema-stats-content", Container)
|
127
|
+
loading_indicator.styles.display = "block" if loading else "none"
|
128
|
+
stats_content.styles.display = "none" if loading else "block"
|
129
|
+
|
130
|
+
async def _update_stats_display(self, lines: List[Union[str, Text]]) -> None:
|
131
|
+
try:
|
132
|
+
content_area = self.query_one("#schema-stats-content", Container)
|
133
|
+
await content_area.query("*").remove()
|
134
|
+
|
135
|
+
if not lines:
|
136
|
+
await content_area.mount(Static(self.DEFAULT_STATS_MESSAGE, classes="stats-line"))
|
137
|
+
return
|
138
|
+
|
139
|
+
new_widgets: List[Static] = []
|
140
|
+
for line in lines:
|
141
|
+
content: Union[str, Text] = line
|
142
|
+
css_class = "stats-line"
|
143
|
+
if isinstance(line, str) and line.startswith("```"):
|
144
|
+
content = line.strip("` \n")
|
145
|
+
css_class = "stats-code"
|
146
|
+
elif isinstance(line, Text) and ("red" in str(line.style) or "yellow" in str(line.style)):
|
147
|
+
css_class = "stats-error stats-line"
|
148
|
+
|
149
|
+
new_widgets.append(Static(content, classes=css_class))
|
150
|
+
|
151
|
+
if new_widgets:
|
152
|
+
await content_area.mount_all(new_widgets)
|
153
|
+
except Exception as e:
|
154
|
+
log.error(f"Error updating stats display: {e}", exc_info=True)
|
155
|
+
try:
|
156
|
+
await content_area.query("*").remove()
|
157
|
+
await content_area.mount(Static(f"[red]Internal error displaying stats: {e}[/red]"))
|
158
|
+
except Exception:
|
159
|
+
pass
|
160
|
+
|
161
|
+
async def on_list_view_selected(self, event: ListView.Selected) -> None:
|
162
|
+
event.stop()
|
163
|
+
selected_item = event.item
|
164
|
+
|
165
|
+
if isinstance(selected_item, ColumnListItem):
|
166
|
+
column_name = selected_item.column_name
|
167
|
+
log.info(f"Column selected: {column_name}")
|
168
|
+
self.loading = True
|
169
|
+
|
170
|
+
stats_data: Dict[str, Any] = {}
|
171
|
+
error_str: Optional[str] = None
|
172
|
+
try:
|
173
|
+
if self.app.handler:
|
174
|
+
stats_data = self.app.handler.get_column_stats(column_name)
|
175
|
+
else:
|
176
|
+
error_str = "[red]Error: Parquet handler not available.[/]"
|
177
|
+
log.error("Parquet handler not found on app.")
|
178
|
+
except Exception as e:
|
179
|
+
log.exception(f"ERROR calculating stats for {column_name}")
|
180
|
+
error_str = f"[red]Error loading stats for {column_name}:\n{type(e).__name__}: {e}[/]"
|
181
|
+
|
182
|
+
lines_to_render = format_stats_for_display(stats_data) if not error_str else [Text.from_markup(error_str)]
|
183
|
+
await self._update_stats_display(lines_to_render)
|
184
|
+
self.loading = False
|
185
|
+
else:
|
186
|
+
await self._update_stats_display([])
|
187
|
+
self.loading = False
|
@@ -0,0 +1,91 @@
|
|
1
|
+
Metadata-Version: 2.4
|
2
|
+
Name: parqv
|
3
|
+
Version: 0.1.0
|
4
|
+
Summary: An interactive Python TUI for visualizing, exploring, and analyzing Parquet files directly in your terminal.
|
5
|
+
Author-email: Sangmin Yoon <sanspareilsmyn@gmail.com>
|
6
|
+
License-Expression: Apache-2.0
|
7
|
+
Requires-Python: >=3.10
|
8
|
+
Description-Content-Type: text/markdown
|
9
|
+
License-File: LICENSE
|
10
|
+
Requires-Dist: textual>=1.0.0
|
11
|
+
Requires-Dist: pyarrow>=16.0.0
|
12
|
+
Requires-Dist: pandas>=2.0.0
|
13
|
+
Requires-Dist: numpy>=1.20.0
|
14
|
+
Dynamic: license-file
|
15
|
+
|
16
|
+
# parqv
|
17
|
+
|
18
|
+
[](https://www.python.org/)
|
19
|
+
[](LICENSE)
|
20
|
+
[](https://badge.fury.io/py/parqv) <!-- Link after PyPI release -->
|
21
|
+
[](https://textual.textualize.io/)
|
22
|
+
<!-- Optional: Add BuyMeACoffee or other badges later if desired -->
|
23
|
+
|
24
|
+
**`parqv` is a Python-based interactive TUI (Text User Interface) tool designed to explore, analyze, and understand Parquet files directly within your terminal.** Forget juggling multiple commands; `parqv` provides a unified, visual experience.
|
25
|
+
|
26
|
+
## 💻 Demo (Placeholder)
|
27
|
+
|
28
|
+

|
29
|
+
|
30
|
+
## 🤔 Why `parqv`?
|
31
|
+
1. **Unified Interface:** Launch `parqv <file.parquet>` to access **metadata, schema, data preview, column statistics, and row group details** all within a single, navigable terminal window. No more memorizing different commands.
|
32
|
+
2. **Interactive Exploration:**
|
33
|
+
* **🖱️ Keyboard & Mouse Driven:** Navigate using familiar keys (arrows, `hjkl`, Tab) or even your mouse (thanks to `Textual`).
|
34
|
+
* **📜 Scrollable Views:** Easily scroll through large schemas, data tables, or row group lists.
|
35
|
+
* **🌲 Expandable Schema:** Visualize and navigate complex nested structures (Structs, Lists) effortlessly.
|
36
|
+
* **📊 Dynamic Stats:** Select a column and instantly see its detailed statistics and distribution.
|
37
|
+
3. **Enhanced Analysis & Visualization:**
|
38
|
+
* **🎨 Rich Display:** Leverages `rich` and `Textual` for colorful, readable tables and syntax-highlighted schema.
|
39
|
+
* **📈 Quick Stats:** Go beyond min/max/nulls. See means, medians, quantiles, distinct counts, frequency distributions, and even text-based histograms.
|
40
|
+
* **🔬 Row Group Deep Dive:** Inspect individual row groups to understand compression, encoding, and potential data skew.
|
41
|
+
|
42
|
+
## ✨ Features (TUI Mode)
|
43
|
+
* **Interactive TUI:** Run `parqv <file.parquet>` to launch the main interface.
|
44
|
+
* **Metadata Panel:** Displays key file information (path, creator, total rows, row groups, compression, etc.).
|
45
|
+
* **Schema Explorer:**
|
46
|
+
* Interactive, collapsible tree view for schemas.
|
47
|
+
* Clearly shows column names, data types (including nested types), and nullability.
|
48
|
+
* Syntax highlighting for better readability.
|
49
|
+
* **Data Table Viewer:**
|
50
|
+
* Scrollable table preview of the file's data.
|
51
|
+
* Handles large files by loading data pages on demand.
|
52
|
+
* (Planned) Column selection/reordering.
|
53
|
+
* **Row Group Inspector:**
|
54
|
+
* List all row groups with key stats (row count, compressed/uncompressed size).
|
55
|
+
* Select a row group to view per-column details (encoding, size, stats within the group).
|
56
|
+
|
57
|
+
## 🚀 Getting Started
|
58
|
+
|
59
|
+
**1. Prerequisites:**
|
60
|
+
* **Python:** Version 3.10 or higher.
|
61
|
+
* **pip:** The Python package installer.
|
62
|
+
|
63
|
+
**2. Install `parqv`:**
|
64
|
+
* Open your terminal and run:
|
65
|
+
```bash
|
66
|
+
pip install parqv
|
67
|
+
```
|
68
|
+
* **Updating `parqv`:**
|
69
|
+
```bash
|
70
|
+
pip install --upgrade parqv
|
71
|
+
```
|
72
|
+
|
73
|
+
**3. Run `parqv`:**
|
74
|
+
* Point `parqv` to your Parquet file:
|
75
|
+
```bash
|
76
|
+
parqv /path/to/your/data.parquet
|
77
|
+
```
|
78
|
+
* The interactive TUI will launch. Use your keyboard (and mouse, if supported by your terminal) to navigate:
|
79
|
+
* **Arrow Keys / `h`,`j`,`k`,`l`:** Move focus within lists, tables, trees.
|
80
|
+
* **`Tab` / `Shift+Tab`:** Cycle focus between different panes/widgets.
|
81
|
+
* **`Enter`:** Select items, expand/collapse tree nodes.
|
82
|
+
* **View Switching Keys (Examples - check help):** `m` (Metadata), `s` (Schema), `d` (Data), `t` (Stats), `g` (Row Groups).
|
83
|
+
* **`PageUp` / `PageDown` / `Home` / `End`:** Scroll long lists or tables.
|
84
|
+
* **`?`:** Show help screen with keybindings.
|
85
|
+
* **`q` / `Ctrl+C`:** Quit `parqv`.
|
86
|
+
|
87
|
+
---
|
88
|
+
|
89
|
+
## 📄 License
|
90
|
+
|
91
|
+
Licensed under the Apache License, Version 2.0. See [LICENSE](LICENSE) for the full license text.
|
@@ -0,0 +1,15 @@
|
|
1
|
+
parqv/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
2
|
+
parqv/app.py,sha256=akN-tLb0QpYrG9A_1-Sa2zg--MOZpSGMbVYEZDFpyY0,4587
|
3
|
+
parqv/parquet_handler.py,sha256=Jh210_neAhVZU4vcz8N4gVbV0NqilkYZ0IlQTMcrrkc,16589
|
4
|
+
parqv/parqv.css,sha256=C42ZXUwMX1ZXfGo0AmixbHxz0CWKzWBHZ_hkhq5aehg,2920
|
5
|
+
parqv/views/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
6
|
+
parqv/views/data_view.py,sha256=T_LPbXdxm_KOmwtTQWAxlUeNTlSGfIgQIg853WDMAME,2355
|
7
|
+
parqv/views/metadata_view.py,sha256=KgLOjefGyY50zTs-H99PwvJ9IDPE1jfq6--qmD5zp48,656
|
8
|
+
parqv/views/row_group_view.py,sha256=4BkaUM2Q2HQ-bvdRYpiYIl5T4oGJGReoaJOcttUd-8s,1210
|
9
|
+
parqv/views/schema_view.py,sha256=IYsxkIV9kvOKGfylOQhqeUyakvymlGlgwXWMibhslmI,7880
|
10
|
+
parqv-0.1.0.dist-info/licenses/LICENSE,sha256=Ewl2wCa8r6ncxHlpf-ZZXb77c82zdfxHuEeKzBbm6nM,11324
|
11
|
+
parqv-0.1.0.dist-info/METADATA,sha256=TxX4NHmXdfu4O5bK6-UiMqlncusxfxj1KvZQaGVLPR0,4525
|
12
|
+
parqv-0.1.0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
|
13
|
+
parqv-0.1.0.dist-info/entry_points.txt,sha256=8Tm8rTiIB-tbVItoOA4M7seEmFnrtK25BMH9UKzqfXg,44
|
14
|
+
parqv-0.1.0.dist-info/top_level.txt,sha256=_t3_49ZluJbvl0QU_P3GNVuXxCffqiTp37dzZIa2GEw,6
|
15
|
+
parqv-0.1.0.dist-info/RECORD,,
|
@@ -0,0 +1,201 @@
|
|
1
|
+
Apache License
|
2
|
+
Version 2.0, January 2004
|
3
|
+
http://www.apache.org/licenses/
|
4
|
+
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6
|
+
|
7
|
+
1. Definitions.
|
8
|
+
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
11
|
+
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13
|
+
the copyright owner that is granting the License.
|
14
|
+
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
16
|
+
other entities that control, are controlled by, or are under common
|
17
|
+
control with that entity. For the purposes of this definition,
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
19
|
+
direction or management of such entity, whether by contract or
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22
|
+
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24
|
+
exercising permissions granted by this License.
|
25
|
+
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
27
|
+
including but not limited to software source code, documentation
|
28
|
+
source, and configuration files.
|
29
|
+
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
31
|
+
transformation or translation of a Source form, including but
|
32
|
+
not limited to compiled object code, generated documentation,
|
33
|
+
and conversions to other media types.
|
34
|
+
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
36
|
+
Object form, made available under the License, as indicated by a
|
37
|
+
copyright notice that is included in or attached to the work
|
38
|
+
(an example is provided in the Appendix below).
|
39
|
+
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46
|
+
the Work and Derivative Works thereof.
|
47
|
+
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
49
|
+
the original version of the Work and any modifications or additions
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
61
|
+
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
64
|
+
subsequently incorporated within the Work.
|
65
|
+
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
72
|
+
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78
|
+
where such license applies only to those patent claims licensable
|
79
|
+
by such Contributor that are necessarily infringed by their
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
82
|
+
institute patent litigation against any entity (including a
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
85
|
+
or contributory patent infringement, then any patent licenses
|
86
|
+
granted to You under this License for that Work shall terminate
|
87
|
+
as of the date such litigation is filed.
|
88
|
+
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
91
|
+
modifications, and in Source or Object form, provided that You
|
92
|
+
meet the following conditions:
|
93
|
+
|
94
|
+
(a) You must give any other recipients of the Work or
|
95
|
+
Derivative Works a copy of this License; and
|
96
|
+
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
98
|
+
stating that You changed the files; and
|
99
|
+
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
102
|
+
attribution notices from the Source form of the Work,
|
103
|
+
excluding those notices that do not pertain to any part of
|
104
|
+
the Derivative Works; and
|
105
|
+
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
108
|
+
include a readable copy of the attribution notices contained
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
111
|
+
of the following places: within a NOTICE text file distributed
|
112
|
+
as part of the Derivative Works; within the Source form or
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
114
|
+
within a display generated by the Derivative Works, if and
|
115
|
+
wherever such third-party notices normally appear. The contents
|
116
|
+
of the NOTICE file are for informational purposes only and
|
117
|
+
do not modify the License. You may add Your own attribution
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
120
|
+
that such additional attribution notices cannot be construed
|
121
|
+
as modifying the License.
|
122
|
+
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
124
|
+
may provide additional or different license terms and conditions
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
128
|
+
the conditions stated in this License.
|
129
|
+
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
133
|
+
this License, without any additional terms or conditions.
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135
|
+
the terms of any separate license agreement you may have executed
|
136
|
+
with Licensor regarding such Contributions.
|
137
|
+
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
140
|
+
except as required for reasonable and customary use in describing the
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
142
|
+
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
152
|
+
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
158
|
+
incidental, or consequential damages of any character arising as a
|
159
|
+
result of this License or out of the use or inability to use the
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
162
|
+
other commercial damages or losses), even if such Contributor
|
163
|
+
has been advised of the possibility of such damages.
|
164
|
+
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168
|
+
or other liability obligations and/or rights consistent with this
|
169
|
+
License. However, in accepting such obligations, You may act only
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
174
|
+
of your accepting any such warranty or additional liability.
|
175
|
+
|
176
|
+
END OF TERMS AND CONDITIONS
|
177
|
+
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
179
|
+
|
180
|
+
To apply the Apache License to your work, attach the following
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182
|
+
replaced with your own identifying information. (Don't include
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
184
|
+
comment syntax for the file format. We also recommend that a
|
185
|
+
file or class name and description of purpose be included on the
|
186
|
+
same "printed page" as the copyright notice for easier
|
187
|
+
identification within third-party archives.
|
188
|
+
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
190
|
+
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192
|
+
you may not use this file except in compliance with the License.
|
193
|
+
You may obtain a copy of the License at
|
194
|
+
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
196
|
+
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200
|
+
See the License for the specific language governing permissions and
|
201
|
+
limitations under the License.
|
@@ -0,0 +1 @@
|
|
1
|
+
parqv
|