cpuz_parser 0.2.0b0__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.
@@ -0,0 +1,6 @@
1
+ from .parsers import CpuzTxtParser
2
+
3
+
4
+ __all__ = [
5
+ 'CpuzTxtParser',
6
+ ]
@@ -0,0 +1,5 @@
1
+ from .cli import main
2
+
3
+
4
+ if __name__ == '__main__':
5
+ main()
cpuz_parser/cli.py ADDED
@@ -0,0 +1,205 @@
1
+ """Command-line interface for cpuz_parser."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sys
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ from .features import FEATURE_RICH
11
+
12
+
13
+ if FEATURE_RICH:
14
+ import rich_click as click
15
+
16
+ click.rich_click.TEXT_MARKUP = 'markdown'
17
+ click.rich_click.SHOW_ARGUMENTS = True
18
+ click.rich_click.GROUP_ARGUMENTS_OPTIONS = True
19
+ click.rich_click.STYLE_OPTIONS_PANEL_BORDER = 'cyan'
20
+ click.rich_click.STYLE_COMMANDS_PANEL_BORDER = 'green'
21
+ else:
22
+ import click # type: ignore[no-redef]
23
+
24
+ from . import exporters
25
+ from .parsers import CpuzTxtParser
26
+
27
+
28
+ FORMAT_EXTENSION_MAP = {
29
+ '.json': 'json',
30
+ '.yaml': 'yaml',
31
+ '.yml': 'yaml',
32
+ '.toml': 'toml',
33
+ '.xml': 'xml',
34
+ '.txt': 'plain',
35
+ }
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class CliConfig:
40
+ """Validated configuration loaded from a JSON config file."""
41
+
42
+ ram_freqs_single_mul2_to_friendly: dict[str, str] | None = None
43
+ auto_combine_slots: bool | None = None
44
+
45
+
46
+ def load_config(config_file: Path) -> CliConfig:
47
+ """Load and validate a JSON configuration file.
48
+
49
+ Validates the supported options:
50
+ - ``ram_freqs_single_mul2_to_friendly``: mapping of ``str`` to ``str``.
51
+ - ``auto_combine_slots``: strict ``bool``.
52
+
53
+ Raises ``click.ClickException`` (exit code 1) if the file is malformed.
54
+ """
55
+ try:
56
+ with open(config_file, 'r', encoding='utf-8') as f:
57
+ cfg = json.load(f)
58
+ except json.JSONDecodeError as e:
59
+ raise click.ClickException(f"Malformed JSON in config file '{config_file}': {e.msg}") from e
60
+
61
+ if not isinstance(cfg, dict):
62
+ raise click.ClickException(f"Config file '{config_file}' must contain a JSON object.")
63
+
64
+ ram_freq_translate: dict[str, str] | None = cfg.get('ram_freqs_single_mul2_to_friendly')
65
+ if 'ram_freqs_single_mul2_to_friendly' in cfg and (
66
+ not isinstance(ram_freq_translate, dict)
67
+ or not all(isinstance(k, str) and isinstance(v, str) for k, v in ram_freq_translate.items())
68
+ ):
69
+ raise click.ClickException(
70
+ "Config key 'ram_freqs_single_mul2_to_friendly' must be an object mapping strings to strings."
71
+ )
72
+
73
+ auto_combine_slots: bool | None = cfg.get('auto_combine_slots')
74
+ if 'auto_combine_slots' in cfg and not isinstance(auto_combine_slots, bool):
75
+ raise click.ClickException("Config key 'auto_combine_slots' must be a boolean (true/false).")
76
+
77
+ return CliConfig(
78
+ ram_freqs_single_mul2_to_friendly=ram_freq_translate,
79
+ auto_combine_slots=auto_combine_slots,
80
+ )
81
+
82
+
83
+ @click.command(name='cpuz_parser', context_settings={'help_option_names': ['-h', '--help']})
84
+ @click.argument(
85
+ 'report_file',
86
+ type=click.Path(allow_dash=True, path_type=str),
87
+ required=True,
88
+ )
89
+ @click.option(
90
+ '-c',
91
+ '--config',
92
+ 'config_file',
93
+ type=click.Path(exists=True, dir_okay=False, path_type=Path),
94
+ default=None,
95
+ help='Path to JSON configuration file.',
96
+ )
97
+ @click.option(
98
+ '--auto-combine-slots/--no-auto-combine-slots',
99
+ 'auto_combine_slots',
100
+ default=None,
101
+ help='Merge each RAM slot into a single string and count duplicates. Overrides `--config` (default: True).',
102
+ )
103
+ @click.option(
104
+ '-f',
105
+ '--format',
106
+ 'output_format',
107
+ type=click.Choice(['plain', 'rich', 'json', 'yaml', 'toml', 'xml'], case_sensitive=False),
108
+ default=None,
109
+ help="Output format (default: 'rich' if available and writing to stdout, otherwise 'plain').",
110
+ )
111
+ @click.option(
112
+ '-o',
113
+ '--output',
114
+ 'output_file',
115
+ type=click.Path(allow_dash=True, path_type=str),
116
+ default='-',
117
+ show_default=True,
118
+ help="Destination file path, or '-' to print to stdout.",
119
+ )
120
+ @click.version_option(package_name='cpuz_parser')
121
+ def main(
122
+ report_file: str,
123
+ config_file: Path | None,
124
+ auto_combine_slots: bool | None,
125
+ output_format: str | None,
126
+ output_file: str,
127
+ ) -> int:
128
+ """Parse CPU-Z TXT reports and export structured hardware data."""
129
+ config = load_config(config_file) if config_file is not None else CliConfig()
130
+
131
+ if auto_combine_slots is not None:
132
+ effective_auto_combine = auto_combine_slots
133
+ elif config.auto_combine_slots is not None:
134
+ effective_auto_combine = config.auto_combine_slots
135
+ else:
136
+ effective_auto_combine = True
137
+
138
+ # Instantiate parser from stdin ('-') or file path
139
+ if report_file == '-':
140
+ parser = CpuzTxtParser(
141
+ sys.stdin.buffer,
142
+ ram_freq_translate=config.ram_freqs_single_mul2_to_friendly,
143
+ auto_combine_slots=effective_auto_combine,
144
+ )
145
+ else:
146
+ path = Path(report_file)
147
+ if not path.is_file():
148
+ raise click.BadParameter(f"File '{report_file}' does not exist.", param_hint="'REPORT_FILE'")
149
+ parser = CpuzTxtParser(
150
+ str(path),
151
+ ram_freq_translate=config.ram_freqs_single_mul2_to_friendly,
152
+ auto_combine_slots=effective_auto_combine,
153
+ )
154
+
155
+ # Deduce output format
156
+ if output_format is None:
157
+ if output_file != '-' and Path(output_file).suffix.lower() in FORMAT_EXTENSION_MAP:
158
+ output_format = FORMAT_EXTENSION_MAP[Path(output_file).suffix.lower()]
159
+ else:
160
+ output_format = 'rich' if (FEATURE_RICH and output_file == '-') else 'plain'
161
+ else:
162
+ output_format = output_format.lower()
163
+
164
+ # Route to exporters via match/case
165
+ try:
166
+ match output_format:
167
+ case 'rich':
168
+ # TODO: caso '-o -' e '-f rich', tentar imprimir no arquivo mesmo?
169
+ if output_file == '-':
170
+ exporters.to_rich(parser)
171
+ return 0
172
+ content = exporters.to_plain(parser)
173
+ case 'plain':
174
+ content = exporters.to_plain(parser)
175
+ case 'json':
176
+ content = exporters.to_json(parser)
177
+ case 'yaml':
178
+ content = exporters.to_yaml(parser)
179
+ case 'toml':
180
+ content = exporters.to_toml(parser)
181
+ case 'xml':
182
+ content = exporters.to_xml(parser)
183
+ case _:
184
+ raise click.UsageError(f"Unsupported format: '{output_format}'")
185
+ except ImportError as e:
186
+ raise click.UsageError(str(e)) from e
187
+
188
+ # Output to stdout ('-') or file
189
+ if output_file == '-':
190
+ if output_format == 'json' and FEATURE_RICH:
191
+ from rich.console import Console
192
+
193
+ Console().print_json(content)
194
+ else:
195
+ click.echo(content, nl=output_format not in ('plain',))
196
+ else:
197
+ Path(output_file).write_text(content, encoding='utf-8')
198
+ if FEATURE_RICH:
199
+ from rich.console import Console
200
+
201
+ Console().print(f'[bold green]Report successfully exported to:[/bold green] {output_file}')
202
+ else:
203
+ click.echo(f'Report successfully exported to: {output_file}')
204
+
205
+ return 0
@@ -0,0 +1,175 @@
1
+ """Data serializers and formatters for cpuz_parser."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import xml.etree.ElementTree as ET # nosec B405 # XML serialization only, no parsing
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ from .features import (
10
+ require_rich_feature,
11
+ require_toml_feature,
12
+ require_yaml_feature,
13
+ )
14
+
15
+
16
+ if TYPE_CHECKING:
17
+ from .parsers import SystemInfo
18
+
19
+
20
+ def _format_slot_plain_text(slot: str | dict[str, str]) -> str:
21
+ """Format a RAM slot entry (either combined string or raw dict) as plain text."""
22
+ if isinstance(slot, dict):
23
+ return ' '.join(filter(None, (
24
+ slot.get('type', ''),
25
+ slot.get('bandwidth', ''),
26
+ slot.get('size', ''),
27
+ slot.get('manufacturer', ''),
28
+ )))
29
+ return slot
30
+
31
+
32
+ def to_plain(si: SystemInfo) -> str:
33
+ """Serialize system info to human-readable plain text."""
34
+ data = si.system_info
35
+ lines: list[str] = []
36
+
37
+ mb_parts = ' '.join(filter(None, (
38
+ data['motherboard']['vendor'], data['motherboard']['model']
39
+ )))
40
+ lines.append(f'Motherboard: {mb_parts}')
41
+
42
+ bios_parts = ' '.join(filter(None, (
43
+ data['bios']['vendor'], data['bios']['version'], data['bios']['date']
44
+ )))
45
+ lines.append(f'BIOS: {bios_parts}')
46
+
47
+ lines.append(f"CPU: {' + '.join(data['cpu'])}")
48
+ lines.append(f"Memory: {data['ram']['size']}")
49
+ for slot in data['ram']['slots']:
50
+ lines.append(_format_slot_plain_text(slot))
51
+ lines.append(f"Graphics: {' + '.join(data['gpu'])}")
52
+ lines.append(f"Operating System: {' + '.join(data['os'])}")
53
+
54
+ return '\n'.join(lines) + '\n'
55
+
56
+
57
+ def to_rich(si: SystemInfo, console: Any = None) -> None:
58
+ """Render system hardware information using Rich panels and tables."""
59
+ require_rich_feature()
60
+ from rich.console import Console
61
+ from rich.panel import Panel
62
+ from rich.table import Table
63
+
64
+ if console is None:
65
+ console = Console()
66
+
67
+ data = si.system_info
68
+
69
+ # Motherboard
70
+ mb_lines = [
71
+ f"[bold cyan]Vendor:[/bold cyan] {data['motherboard']['vendor'] or 'N/A'}",
72
+ f"[bold cyan]Model:[/bold cyan] {data['motherboard']['model'] or 'N/A'}",
73
+ ]
74
+ console.print(Panel('\n'.join(mb_lines), title='[bold green]Motherboard[/bold green]', expand=False))
75
+
76
+ # BIOS
77
+ bios_lines = [
78
+ f"[bold cyan]Vendor:[/bold cyan] {data['bios']['vendor'] or 'N/A'}",
79
+ f"[bold cyan]Version:[/bold cyan] {data['bios']['version'] or 'N/A'}",
80
+ f"[bold cyan]Date:[/bold cyan] {data['bios']['date'] or 'N/A'}",
81
+ ]
82
+ console.print(Panel('\n'.join(bios_lines), title='[bold green]BIOS[/bold green]', expand=False))
83
+
84
+ # Processor (CPU)
85
+ cpus = data.get('cpu', [])
86
+ cpu_text = '\n'.join(f'[bold yellow]•[/bold yellow] {cpu}' for cpu in cpus) if cpus else 'N/A'
87
+ console.print(Panel(cpu_text, title='[bold green]Processor (CPU)[/bold green]', expand=False))
88
+
89
+ # Memory (RAM)
90
+ ram_info = data.get('ram', {})
91
+ total_size = ram_info.get('size', 'N/A')
92
+ slots = ram_info.get('slots', [])
93
+
94
+ ram_table = Table(
95
+ title=f'RAM Memory — Total Detected: {total_size}',
96
+ show_header=True,
97
+ header_style='bold magenta',
98
+ )
99
+
100
+ if slots and isinstance(slots[0], dict):
101
+ ram_table.add_column('Type', style='white')
102
+ ram_table.add_column('Bandwidth', style='cyan')
103
+ ram_table.add_column('Size', style='green')
104
+ ram_table.add_column('Manufacturer', style='white')
105
+ for slot in slots:
106
+ ram_table.add_row(
107
+ slot.get('type', '') or 'N/A',
108
+ slot.get('bandwidth', '') or 'N/A',
109
+ slot.get('size', '') or 'N/A',
110
+ slot.get('manufacturer', '') or 'N/A',
111
+ )
112
+ else:
113
+ ram_table.add_column('Installed RAM Slots', style='white')
114
+ if slots:
115
+ for slot in slots:
116
+ ram_table.add_row(slot)
117
+ else:
118
+ ram_table.add_row('[dim]No detailed memory slots found[/dim]')
119
+ console.print(ram_table)
120
+
121
+ # Graphics (GPU)
122
+ gpus = data.get('gpu', [])
123
+ gpu_text = '\n'.join(f'[bold yellow]•[/bold yellow] {gpu}' for gpu in gpus) if gpus else 'N/A'
124
+ console.print(Panel(gpu_text, title='[bold green]Graphics (GPU)[/bold green]', expand=False))
125
+
126
+ # Operating System
127
+ os_info = data.get('os', [])
128
+ os_text = '\n'.join(os_info) if os_info else 'N/A'
129
+ console.print(Panel(os_text, title='[bold green]Operating System (OS)[/bold green]', expand=False))
130
+
131
+
132
+ def to_json(si: SystemInfo, indent: int = 2) -> str:
133
+ """Serialize system info data to formatted JSON."""
134
+ data = si.system_info
135
+ return json.dumps(data, indent=indent, ensure_ascii=False)
136
+
137
+
138
+ def _build_xml_element(tag: str, value: Any) -> ET.Element:
139
+ """Recursively convert nested dicts, lists, and primitives into XML elements."""
140
+ elem = ET.Element(tag)
141
+ if isinstance(value, dict):
142
+ for k, v in value.items():
143
+ elem.append(_build_xml_element(str(k), v))
144
+ elif isinstance(value, list):
145
+ for item in value:
146
+ elem.append(_build_xml_element('item', item))
147
+ else:
148
+ elem.text = '' if value is None else str(value)
149
+ return elem
150
+
151
+
152
+ def to_xml(si: SystemInfo, root_tag: str = 'system_info') -> str:
153
+ """Serialize system info data to formatted XML."""
154
+ data = si.system_info
155
+ root = _build_xml_element(root_tag, data)
156
+ ET.indent(root, space=' ')
157
+ return ET.tostring(root, encoding='utf-8').decode('utf-8')
158
+
159
+
160
+ def to_yaml(si: SystemInfo) -> str:
161
+ """Serialize system info data to YAML format."""
162
+ require_yaml_feature()
163
+ import yaml # type: ignore[import-untyped]
164
+
165
+ data = si.system_info
166
+ return yaml.dump(data, sort_keys=False, allow_unicode=True, default_flow_style=False)
167
+
168
+
169
+ def to_toml(si: SystemInfo) -> str:
170
+ """Serialize system info data to TOML format."""
171
+ require_toml_feature()
172
+ import tomli_w
173
+
174
+ data = si.system_info
175
+ return tomli_w.dumps(data)
@@ -0,0 +1,38 @@
1
+ """Feature toggles detecting optional dependencies and capabilities."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.util import find_spec
6
+
7
+
8
+ # Feature Toggles
9
+ FEATURE_RICH: bool = find_spec('rich') is not None and find_spec('rich_click') is not None
10
+ FEATURE_YAML: bool = find_spec('yaml') is not None
11
+ FEATURE_TOML: bool = find_spec('tomli_w') is not None
12
+
13
+
14
+ def require_rich_feature() -> None:
15
+ """Validate that the Rich feature toggle is active; raise ImportError otherwise."""
16
+ if not FEATURE_RICH:
17
+ raise ImportError(
18
+ "Rich visualization requires 'rich' and 'rich-click'. "
19
+ "Install with: pip install 'cpuz_parser[rich]' (or 'cpuz_parser[all]')"
20
+ )
21
+
22
+
23
+ def require_yaml_feature() -> None:
24
+ """Validate that the YAML feature toggle is active; raise ImportError otherwise."""
25
+ if not FEATURE_YAML:
26
+ raise ImportError(
27
+ "YAML export feature is disabled because 'pyyaml' is not installed. "
28
+ "Install it with: pip install 'cpuz_parser[yaml]' (or 'cpuz_parser[all]')"
29
+ )
30
+
31
+
32
+ def require_toml_feature() -> None:
33
+ """Validate that the TOML feature toggle is active; raise ImportError otherwise."""
34
+ if not FEATURE_TOML:
35
+ raise ImportError(
36
+ "TOML export feature is disabled because 'tomli-w' is not installed. "
37
+ "Install it with: pip install 'cpuz_parser[toml]' (or 'cpuz_parser[all]')"
38
+ )
cpuz_parser/parsers.py ADDED
@@ -0,0 +1,249 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ from abc import ABC
5
+ from collections import Counter
6
+ from copy import deepcopy
7
+ from typing import IO, Any
8
+
9
+ from .exporters import to_plain
10
+
11
+
12
+ class SystemInfo(ABC):
13
+ def __init__(self, auto_combine_slots: bool = True) -> None:
14
+ self.auto_combine_slots = auto_combine_slots
15
+
16
+ self._system_info: dict[str, Any] = {}
17
+ self._system_info['motherboard'] = {}
18
+ self._system_info['motherboard']['vendor'] = ''
19
+ self._system_info['motherboard']['model'] = ''
20
+ # self._system_info['motherboard']['revision'] = ''
21
+ self._system_info['bios'] = {}
22
+ self._system_info['bios']['vendor'] = ''
23
+ self._system_info['bios']['version'] = ''
24
+ self._system_info['bios']['date'] = ''
25
+ self._system_info['cpu'] = []
26
+ self._system_info['ram'] = {}
27
+ self._system_info['ram']['size'] = ''
28
+ self._system_info['ram']['slots'] = [] # 'type', 'bandwidth', 'size', 'manufacturer'
29
+ self._system_info['gpu'] = []
30
+ self._system_info['os'] = []
31
+
32
+ def update_system_info(self, *args, **kwargs) -> None:
33
+ return self._system_info.update(*args, **kwargs)
34
+
35
+ def __str__(self) -> str:
36
+ return to_plain(self)
37
+
38
+ @property
39
+ def system_info(self) -> dict:
40
+ si = deepcopy(self._system_info)
41
+ if self.auto_combine_slots:
42
+ si['ram']['slots'] = self.combine_ram_slots(si['ram']['slots'])
43
+ return si
44
+
45
+ @staticmethod
46
+ def combine_ram_slots(old_slots) -> list:
47
+ # TODO: old_slots: list[RamSlotDict]
48
+ slots_counter = Counter([frozenset(x.items()) for x in old_slots])
49
+ new_slots = []
50
+ for key, amount in slots_counter.items():
51
+ slot_values = dict(key) # RamSlotDict
52
+ new_slots.append(
53
+ f'{amount}x '
54
+ + ' '.join([
55
+ slot_values['type'],
56
+ slot_values['bandwidth'],
57
+ slot_values['size'],
58
+ slot_values['manufacturer'],
59
+ ])
60
+ )
61
+ return sorted(new_slots)
62
+
63
+
64
+ class CpuzTxtParser(SystemInfo):
65
+ # Pre-compiled regexes.
66
+ # Sub-sections in CPU-Z reports indent all their fields with tabs/spaces, so matching
67
+ # `(?:[ \t]+[^\n]*\n)*?` keeps each search strictly inside its own block
68
+ # (preventing cross-section bleed and excessive backtracking over trailing hex dumps).
69
+
70
+ _REGEX_MOTHERBOARD = re.compile(
71
+ r"""
72
+ ^DMI[ ]Baseboard[ \t]*\n # Sub-header line
73
+ (?:[ \t]+[^\n]*\n)*? # Any preceding indented lines in this block
74
+ [ \t]+vendor[ \t]+(?P<vendor>[^\n]*)\n # Board manufacturer
75
+ [ \t]+model[ \t]+(?P<model>[^\n]*) # Board model (works with or without trailing newline)
76
+ # [ \t]+revision[ \t]+(?P<revision>[^\n]*) # Board revision
77
+ """,
78
+ re.MULTILINE | re.VERBOSE,
79
+ )
80
+
81
+ _REGEX_BIOS = re.compile(
82
+ r"""
83
+ ^DMI[ ]BIOS[ \t]*\n # Sub-header line
84
+ (?:[ \t]+[^\n]*\n)*? # Any preceding indented lines in this block
85
+ [ \t]+vendor[ \t]+(?P<vendor>[^\n]*)\n # BIOS vendor
86
+ [ \t]+version[ \t]+(?P<version>[^\n]*)\n # BIOS version
87
+ [ \t]+date[ \t]+(?P<date>[^\n]*) # BIOS release date
88
+ """,
89
+ re.MULTILINE | re.VERBOSE,
90
+ )
91
+
92
+ _REGEX_CPU = re.compile(
93
+ r"""
94
+ ^(?:Socket|Processor)[ ]\d+[ \t]+ID[ ]=[ ]\d+[ \t]*\n # CPU block header (Socket or Processor)
95
+ (?:[ \t]+[^\n]*\n)*? # Indented fields before Specification
96
+ [ \t]+Specification[ \t]+(?P<cpu>[^\n]*) # Full CPU model specification
97
+ """,
98
+ re.MULTILINE | re.VERBOSE,
99
+ )
100
+
101
+ _REGEX_RAM_SIZE = re.compile(
102
+ r"""
103
+ ^Chipset\n-+\n # Top-level Chipset section header and divider
104
+ (?:(?!^-+$)[^\n]*\n)*? # Lines within Chipset (stops at the next ---... divider)
105
+ ^Memory[ ]Size[ \t]+(?P<size>[^\n]*) # Total installed memory (e.g., '16 GBytes')
106
+ """,
107
+ re.MULTILINE | re.VERBOSE,
108
+ )
109
+
110
+ _REGEX_RAM_SLOTS = re.compile(
111
+ r"""
112
+ ^DIMM[ ]\#[ \t]+\d+[ \t]*\n # DIMM slot header (supports 2+ digits)
113
+ (?:[ \t]+[^\n]*\n)*? # Indented lines before Memory type
114
+ [ \t]+Memory[ ]type[ \t]+(?P<type>[^\n]*)\n # e.g., DDR3, DDR4, DDR5
115
+ (?:[ \t]+[^\n]*\n)*? # Indented lines before Manufacturer
116
+ [ \t]+(?:Module[ ])?Manufacturer[ ]?\(ID\)[ \t]+(?P<manufacturer>[^\n]*)\n # Module/Manufacturer (ID)
117
+ (?:[ \t]+[^\n]*\n)*? # Indented lines before Size
118
+ [ \t]+Size[ \t]+(?P<size>[^\n]*)\n # Module size (e.g., '8192 MBytes')
119
+ (?:[ \t]+[^\n]*\n)*? # Indented lines before Max bandwidth
120
+ [ \t]+Max[ ]bandwidth[ \t]+(?P<bandwidth>[^\n]*) # Rated speed (e.g., 'DDR4-2666 (1333 MHz)')
121
+ """,
122
+ re.MULTILINE | re.VERBOSE,
123
+ )
124
+
125
+ # Trailing parenthesized JEDEC ID on RAM manufacturer names (e.g., 'Corsair (7F7F)' -> 'Corsair')
126
+ _REGEX_RAM_MANUFACTURER = re.compile(
127
+ r'[ ]?[(]\w+[)]$'
128
+ )
129
+
130
+ # Rated RAM bandwidth strings (e.g., 'PC4-21300 (1333 MHz)', 'PC3L-12800 (800 MHz)', 'DDR4-2666 (1333 MHz)').
131
+ # Captures the single-rate clock in ASCII digits ([0-9]+), so int(...) is guaranteed safe
132
+ _REGEX_RAM_BANDWIDTH = re.compile(
133
+ r'^(?:PC|DDR)\w*-[0-9]+.* [(](?P<bandwidth>[0-9]+) MHz[)]$'
134
+ )
135
+
136
+ _REGEX_GPU = re.compile(
137
+ r"""
138
+ ^Display[ ]adapter[ ]\d+(?:[ ]\([a-z]+\))?[ \t]*\n # Display adapter header (optional '(primary)' suffix)
139
+ (?:[ \t]+[^\n]*\n)*? # Indented fields before Name
140
+ [ \t]+Name[ \t]+(?P<gpu>[^\n]*) # GPU adapter name
141
+ """,
142
+ re.MULTILINE | re.VERBOSE,
143
+ )
144
+
145
+ # Top-level Windows Version line under the Software section
146
+ _REGEX_OS = re.compile(
147
+ r'^Windows[ ]Version[ \t]+(?P<os>[^\n]*)', re.MULTILINE
148
+ )
149
+
150
+ def __init__(
151
+ self,
152
+ txt_file: IO | str | None = None,
153
+ ram_freq_translate: dict[str, str] | None = None,
154
+ auto_combine_slots: bool = True,
155
+ ) -> None:
156
+ super().__init__(auto_combine_slots=auto_combine_slots)
157
+
158
+ # ram_freqs_single_mul2_to_friendly_dict
159
+ if ram_freq_translate is not None:
160
+ self.ram_freq_translate = ram_freq_translate
161
+ else:
162
+ self.ram_freq_translate = {}
163
+
164
+ if txt_file is not None:
165
+ if hasattr(txt_file, 'read'):
166
+ self.txt_content = txt_file.read().decode('cp1252').replace('\r\n', '\n')
167
+ else:
168
+ with open(txt_file, 'rb') as f:
169
+ self.txt_content = f.read().decode('cp1252').replace('\r\n', '\n')
170
+
171
+ self.parse_motherboard()
172
+ self.parse_bios()
173
+ self.parse_cpu()
174
+ self.parse_ram()
175
+ self.parse_gpu()
176
+ self.parse_os()
177
+
178
+ def parse_motherboard(self) -> None:
179
+ match = self._REGEX_MOTHERBOARD.search(self.txt_content)
180
+ if match:
181
+ self._system_info['motherboard']['vendor'] = match.group('vendor').strip()
182
+ self._system_info['motherboard']['model'] = match.group('model').strip()
183
+ # self._system_info['motherboard']['revision'] = match.group('revision').strip()
184
+
185
+ def parse_bios(self) -> None:
186
+ match = self._REGEX_BIOS.search(self.txt_content)
187
+ if match:
188
+ self._system_info['bios']['vendor'] = match.group('vendor').strip()
189
+ self._system_info['bios']['version'] = match.group('version').strip()
190
+ self._system_info['bios']['date'] = match.group('date').strip()
191
+
192
+ def parse_cpu(self) -> None:
193
+ self._system_info['cpu'] = [
194
+ match.group('cpu').strip()
195
+ for match in self._REGEX_CPU.finditer(self.txt_content)
196
+ ]
197
+
198
+ def parse_ram(self) -> None:
199
+ match = self._REGEX_RAM_SIZE.search(self.txt_content)
200
+ if match:
201
+ self._system_info['ram']['size'] = match.group('size').strip().replace(' GBytes', 'GB')
202
+
203
+ self._system_info['ram']['slots'] = [
204
+ self._format_ram_slot({
205
+ 'type': match_slot.group('type').strip(),
206
+ 'bandwidth': match_slot.group('bandwidth').strip(),
207
+ 'size': match_slot.group('size').strip(),
208
+ 'manufacturer': match_slot.group('manufacturer').strip(),
209
+ })
210
+ for match_slot in self._REGEX_RAM_SLOTS.finditer(self.txt_content)
211
+ ]
212
+
213
+ # TODO: TypedDict RamSlotDict (dict[str, str | bytes | None])
214
+ # TODO: e definir também um TypedDict (ou dataclass) para `.system_info` e `._system_info`
215
+ def _format_ram_slot(self, slot: dict) -> dict:
216
+ # Format 'size': convert '<integer> MBytes' to '<value>GB'
217
+ if slot['size'].endswith(' MBytes'):
218
+ size_mb_str = slot['size'].removesuffix(' MBytes')
219
+ # isascii() + isdigit() ensures pure ASCII 0-9 (rejecting Unicode digits like '²', negatives, 'inf'/'nan'),
220
+ # so int(...) is guaranteed safe
221
+ if size_mb_str.isascii() and size_mb_str.isdigit():
222
+ size_gb_str = str(int(size_mb_str) / 1024).removesuffix('.0')
223
+ slot['size'] = f'{size_gb_str}GB'
224
+
225
+ # Format 'manufacturer': strip trailing parenthesized JEDEC ID
226
+ slot['manufacturer'] = self._REGEX_RAM_MANUFACTURER.sub('', slot['manufacturer'])
227
+
228
+ # Format 'bandwidth': double single-rate MHz clock (validated as ASCII digits by [0-9]+)
229
+ # and apply optional friendly frequency mapping
230
+ match_bandwidth = self._REGEX_RAM_BANDWIDTH.match(slot['bandwidth'])
231
+ if match_bandwidth:
232
+ freq = str(int(match_bandwidth.group('bandwidth')) * 2)
233
+ slot['bandwidth'] = f'{self.ram_freq_translate.get(freq, freq)}MHz'
234
+
235
+ return slot
236
+
237
+ def parse_gpu(self) -> None:
238
+ self._system_info['gpu'] = [
239
+ match.group('gpu').strip()
240
+ for match in self._REGEX_GPU.finditer(self.txt_content)
241
+ ]
242
+
243
+ def parse_os(self) -> None:
244
+ match = self._REGEX_OS.search(self.txt_content)
245
+ if match:
246
+ # self._system_info['os'] = [match.group('os').replace(' ', ' ').replace(' ', ' ')]
247
+ # Keep raw internal spacing (e.g., before '(Build ...)') as reported by CPU-Z;
248
+ # collapsing spaces like `.replace(' ', ' ')` is intentionally not applied.
249
+ self._system_info['os'] = [match.group('os').strip()]
cpuz_parser/py.typed ADDED
File without changes
@@ -0,0 +1,48 @@
1
+ Metadata-Version: 2.5
2
+ Name: cpuz_parser
3
+ Version: v0.2.0-beta
4
+ Summary: Parse CPU-Z TXT report file into a structured object and a human-readable string
5
+ Project-URL: Home Page, https://github.com/Eliasdns/cpuz_parser
6
+ Project-URL: GitHub, https://github.com/Eliasdns/cpuz_parser
7
+ Project-URL: Repository, https://github.com/Eliasdns/cpuz_parser.git
8
+ Project-URL: Issues, https://github.com/Eliasdns/cpuz_parser/issues
9
+ Author-email: Elias De Nadai Nalesso Silva <pro.eliasdns@gmail.com>
10
+ License-Expression: MIT
11
+ Keywords: cpu,cpu-z,cpuz,human-readable,parser,processing,report,structured,txt,z
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Information Technology
16
+ Classifier: Intended Audience :: System Administrators
17
+ Classifier: License :: OSI Approved :: MIT License
18
+ Classifier: Natural Language :: English
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3 :: Only
22
+ Classifier: Programming Language :: Python :: Implementation :: CPython
23
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
24
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
+ Classifier: Topic :: System :: Hardware
26
+ Classifier: Topic :: System :: Systems Administration
27
+ Classifier: Topic :: Text Processing
28
+ Classifier: Topic :: Utilities
29
+ Classifier: Typing :: Typed
30
+ Requires-Python: >=3.11
31
+ Requires-Dist: click
32
+ Provides-Extra: all
33
+ Requires-Dist: pyyaml; extra == 'all'
34
+ Requires-Dist: rich; extra == 'all'
35
+ Requires-Dist: rich-click; extra == 'all'
36
+ Requires-Dist: tomli-w; extra == 'all'
37
+ Provides-Extra: rich
38
+ Requires-Dist: rich; extra == 'rich'
39
+ Requires-Dist: rich-click; extra == 'rich'
40
+ Provides-Extra: toml
41
+ Requires-Dist: tomli-w; extra == 'toml'
42
+ Provides-Extra: yaml
43
+ Requires-Dist: pyyaml; extra == 'yaml'
44
+ Description-Content-Type: text/markdown
45
+
46
+ # cpuz_parser
47
+
48
+ Parse CPU-Z TXT report file into a structured object and a human-readable string
@@ -0,0 +1,11 @@
1
+ cpuz_parser/__init__.py,sha256=qdqhPBfgn6PHwb7sHERrSipB8ln8dboeTw4c-c16ziU,78
2
+ cpuz_parser/__main__.py,sha256=schE67JzeF4uYozHtlKcYr0M1jCJWk6gBqdC4FvH-A8,62
3
+ cpuz_parser/cli.py,sha256=tCj3pPm_Vk7o5KisLt1Pnn9SoKuIgKCo8u9PMkRTu4U,7093
4
+ cpuz_parser/exporters.py,sha256=XUza3z1P6Yqr2GRXxE3WKQ4daRrrdNcBV6DX17Pj8kE,6131
5
+ cpuz_parser/features.py,sha256=JXBAGHb6OZnQlePK2IxHbAJvq8B8v_54bMubBjw7pmc,1455
6
+ cpuz_parser/parsers.py,sha256=OtObwW9N9SjuWg8aioYHBOv4TgbLC8FkuTpadZf3-Ls,10961
7
+ cpuz_parser/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ cpuz_parser-0.2.0b0.dist-info/METADATA,sha256=2gazDQunxVYL3O6RrJ4nNrQYmh8lUz0f_d00OJWwrLw,2045
9
+ cpuz_parser-0.2.0b0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ cpuz_parser-0.2.0b0.dist-info/entry_points.txt,sha256=CEYoEBT37-Z2B2ksY1h51eaDxIABlOMomR9o7x_MRAE,53
11
+ cpuz_parser-0.2.0b0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ cpuz_parser = cpuz_parser.cli:main