Corpus pipeline

The pipeline turns a Python repository into sentence-level comment units (SCCUs) in three stages:

  1. Extraction (stage 01) walks the LibCST tree and emits one CommentRecord per docstring, inline comment, or contiguous block comment.

  2. Segmentation (stage 02) splits each comment into sentence-level semantic blocks, with a dedicated path for Sphinx/reST docstrings.

  3. SCCU assembly (stage 03) joins the segments back to their comment type, entity scope, file path, and source context.

The package facade is lazy: cc4q.pipeline.segment_docstring-style attributes are resolved on first access. The canonical functions live in the submodules below.

Extraction

Stage-01 extraction: Python source -> comment/code pairs (CCPs).

The extractor walks the LibCST tree once and emits one record for every module/class/function docstring, every inline comment, and every contiguous block comment. Code context is attached to each record so later stages and the annotation UI can show where a comment lives.

cc4q.pipeline.extract.python_extract_comment_pairs(source_code: str, rel_path: str, sdk: str, id_gen: Iterator[str], version: str, host_language: str = 'python', clean_mode: str = 'full') → List[CommentRecord][source]

Extract comment/code pairs from one Python source file.

Parameters:
  • source_code – Complete source text of the file.

  • rel_path – File path relative to the repository root. Stored in the record as dirPath (split on the platform separator).

  • sdk – SDK name used for provenance, e.g. "qiskit-nature".

  • id_gen – Iterator that yields unique record ids. Pass cc4q.pipeline.ids.id_generator() for a fresh sequence.

  • version – SDK release / git ref used for provenance.

  • host_language – Source language label; only "python" is parsed by LibCST today.

  • clean_mode – How much code context to keep in code_snippet. One of "current_only", "full", or "none" (see cc4q.pipeline.clean.CodeCleanMode).

Returns:

One CommentRecord per docstring, inline comment, or contiguous block comment.

Raises:

libcst.ParserSyntaxError – If source_code is not valid Python.

class cc4q.pipeline.types.CommentRecord[source]

One comment/code pair (CCP) extracted from a Python file.

A docstring produces one record for the entire docstring; inline and block comments produce one record each. Segmentation (stage 03) later splits these records into sentence-level comment units (SCCUs).

id

Unique record id assigned by the extraction id generator.

Type:

str

SDK

SDK name, e.g. "qiskit-aer".

Type:

str

version

SDK release or git ref.

Type:

str

hostLanguage

Source language; currently "python".

Type:

str

dirPath

Source path relative to the repository root, split into path components.

Type:

List[str]

comment_type

"docstring", "inline", or "block".

Type:

str

comment_text

The comment or docstring text.

Type:

str

code_snippet

Enclosing code context, cleaned according to the configured clean_mode.

Type:

str

code_entity_type

Enclosing scope: "module", "class", "function", or "file".

Type:

str

comment_line

Inclusive [start, end] line range of the comment.

Type:

List[int]

code_line

Inclusive [start, end] line range of the code context.

Type:

List[int]

extra

Free-form metadata added by later stages (for example the docstring segment type).

Type:

List[str | dict] | dict

class cc4q.pipeline.visitor.LibCSTVisitor(source_lines: List[str], rel_path: str, sdk: str, version: str, id_gen: Iterator[str], host_language: str = 'python', clean_mode: str = 'full', wrapper=None)[source]

Collect comment/code records while walking a LibCST module.

Parameters:
  • source_lines – Source file split into physical lines.

  • rel_path – Path relative to the repository root.

  • sdk – SDK name used for provenance.

  • version – SDK release or git ref.

  • id_gen – Iterator yielding unique record ids.

  • host_language – Source language label.

  • clean_mode – Code-context cleaning policy (current_only, full, or none).

  • wrapper – Optional libcst.metadata.MetadataWrapper for the parsed module; used by the line-number diagnostic.

records

Extracted CommentRecord dictionaries, in source order.

scope_ranges

Stack of active module/class/function scopes.

get_records() → List[Dict][source]

Return the extracted records in source order.

Segmentation

Sphinx/reST-aware docstring segmentation.

Docstrings in quantum SDKs carry most of the domain knowledge, but they mix prose with directives, field lists, definition lists, code blocks, and LaTeX. This module parses a docstring into docutils nodes and emits semantic blocks (paragraph, code, params, args, note, …) so the stage-03 SCCU pipeline can label sentence-level units without losing the structure of the original documentation.

cc4q.pipeline.segment.docstring.segment_docstring(comment_text: str) → List[Dict[str, Any]][source]

Split a Sphinx/reST docstring into semantic sentence blocks.

Paragraphs are sentence-split with spaCy; field/definition lists are kept as params/args blocks; code blocks, notes, sections, and unknown Sphinx directives are preserved with their type. If docutils cannot parse the input, the whole docstring is returned as one paragraph block rather than dropping it.

Parameters:

comment_text – Raw docstring text (without the surrounding triple quotes).

Returns:

A list of {"type": str, "content": str, ...} dictionaries. List blocks may also carry desc/title/name keys.

cc4q.pipeline.segment.docstring.parse_docstring_to_blocks(docstring: str) → List[Dict[str, Any]][source]

Alias for segment_docstring() kept for older callers.

Sentence segmentation for inline # comments.

Inline comments are short but may contain several sentences (and common abbreviations). spaCy’s sentence boundary detector is used so a single comment can yield multiple SCCUs while keeping the original text intact.

cc4q.pipeline.segment.inline.segment_inline_comment(comment_text: str) → List[str][source]

Split an inline comment into sentences.

Parameters:

comment_text – Comment text without the leading #.

Returns:

Non-empty sentence strings; an empty list for blank input.

cc4q.pipeline.segment.inline.segment_inline_comment_advanced(comment_text: str, min_length: int = 5) → List[str][source]

Sentence-split an inline comment and drop very short fragments.

Parameters:
  • comment_text – Comment text without the leading #.

  • min_length – Minimum character length for a sentence to be kept.

Returns:

Filtered sentences. If every sentence is shorter than min_length, the original comment is returned as one unit so no content is lost.

Sentence segmentation for block comments.

Block comments often contain license headers, file headers, and multi-paragraph prose. Copyright/license blocks and structured file headers are kept as one unit; other text is split into paragraphs and then sentences with spaCy.

cc4q.pipeline.segment.block.segment_block_comment(comment_text: str) → List[str][source]

Split a block comment into sentence-level units.

Copyright/license blocks and structured file headers are returned as a single unit; other text is split by paragraph and then by sentence.

Parameters:

comment_text – Comment text without the leading # markers.

Returns:

Non-empty sentence strings; an empty list for blank input.

Stage-03 SCCU assembly

SCCU segmentation of comment-pair JSON files (stage 03).

Moved from scripts/03_segment_comments.py; the script is now a thin CLI over this module.

cc4q.pipeline.segment_pairs.fix_rst_definition_lists(docstring: str) → str[source]

Insert blank lines before reST definition-list items.

Google/Sphinx docstrings often put a definition-list item directly after a section header (Args: / Returns:). docutils requires a blank line in that position, so the stage-03 segmentation would otherwise parse the section as plain prose.

Parameters:

docstring – Raw docstring text.

Returns:

The docstring with the required blank lines inserted.

cc4q.pipeline.segment_pairs.segment_comment_pairs(input_file: str, output_file: str = None) → int[source]

Segment comment pairs; returns the number of output records, or -1 when the input could not be read.

Cleaning, configuration, and repository helpers

Code-context cleaning policies for extracted comment/code pairs.

A record’s code_snippet should show enough surrounding code to judge the comment without leaking unrelated comments into the training text. Three policies are available via CodeCleanMode:

current_only

Keep the comment under study and remove other comments/docstrings.

full

Keep all code and remove comments/docstrings.

none

Keep the snippet verbatim (stripped of leading/trailing whitespace).

class cc4q.pipeline.clean.CodeCleanMode(value)[source]

Supported code-context cleaning policies.

FULL

Keep all code, remove comments and docstrings.

NONE

Keep the snippet verbatim.

CURRENT_ONLY

Keep the comment under study, remove all other comments and docstrings.

cc4q.pipeline.clean.clean_code_snippet(code_lines: List[int], comment_line: List[int], mode: str, code_snippet: str, docstring_lines: List[int] | None = None) → str[source]

Clean a code context according to mode.

Parameters:
  • code_lines – Inclusive [start, end] absolute line range covered by code_snippet.

  • comment_line – Inclusive [start, end] absolute line range of the comment under study. Required by current_only.

  • mode – Cleaning policy, as a CodeCleanMode value or the equivalent string ("full", "none", "current_only").

  • code_snippet – Raw code context, one source line per line.

  • docstring_lines – Optional inclusive line range of the docstring to keep in full mode.

Returns:

The cleaned snippet with blank lines and leading/trailing whitespace removed.

Raises:

ValueError – If mode is unknown, or if current_only is used without comment_line.

YAML configuration loading for the corpus-construction scripts.

A config file pins the repository/project metadata and the input/output directories used by the build stage. See config/examples.yaml for a complete example.

cc4q.pipeline.config.read_config(config_path: str) → Dict[str, Any][source]

Read a YAML configuration file.

Expected keys include project, version, language, input_dir, output_dir, include_dirs, clean_mode, and an optional pipeline mapping (analyze / segment flags).

Parameters:

config_path – Path to a UTF-8 YAML file.

Returns:

The parsed configuration mapping.

Raises:
  • FileNotFoundError – If config_path does not exist.

  • yaml.YAMLError – If the file is not valid YAML.

Repository download helpers (git clone –depth 1, optional pinned ref).

cc4q.pipeline.download.clone_repo(repo, output_dir)[source]

Clone one repo entry into output_dir.

repo is either a plain URL (default branch) or a mapping with url and an optional ref (tag/branch/commit). Existing checkouts are skipped when they match the requested ref. Returns True when the checkout satisfies the request, False otherwise.

Raises subprocess.CalledProcessError when git clone fails.

Filesystem discovery helpers for repository checkouts.

cc4q.pipeline.files.get_files_from_dir(directory: str, include_dirs: List[str] | None = None) → List[str][source]

.py files under directory, restricted to include_dirs.

Paths in include_dirs are relative to directory. Empty or None include_dirs means the whole tree.

Matching uses an exact-or-path-boundary rule, so a package dir like qiskit_aer does not swallow a sibling qiskit_aer_extra. Results are sorted for deterministic file order.

Parameters:
  • directory – Repository checkout root.

  • include_dirs – Optional subdirectories to include.

Returns:

Absolute paths to matching .py files.

Deterministic id generation for extracted records.

cc4q.pipeline.ids.id_generator(start: int = 1) → Iterator[str][source]

Yield incrementing string ids, starting at start.

Parameters:

start – First integer in the sequence.

Yields:

"1", "2", … as strings, matching the id type used by CommentRecord.

Repository/path helpers shared by the pipeline and the model hub.

cc4q.pipeline.paths.get_project_path() → str[source]

Repository root of a source checkout (editable install).

In a plain site-packages install there is no repository root; this still returns the directory that contains the installed cc4q package, which is where relative config paths are expected to live.

Returns:

Absolute path to the repository/package parent directory.

cc4q.pipeline.paths.split_path(path: str) → List[str][source]

Normalize a path and split it into components.

Parameters:

path – Relative or absolute path.

Returns:

Path components produced by os.path.normpath() and os.path.split() semantics.

Repository metrics

These helpers compute the comment-density and quantum-residence statistics reported by the Workbench. They intentionally avoid torch/Streamlit imports.

Repository-level metrics shared by the live pipeline, the demo app, and the demo-data build. No heavy imports (no torch/streamlit).

Comment density definition (mirrors RQ2 of the companion paper): comment lines / code lines over the repository checkout, restricted to the same include_dirs the corpus pipeline uses. A physical line is a comment line if it carries a # comment token (inline or full-line, per Python’s tokenize); code lines are all other non-blank lines. Files that fail to tokenize fall back to a simple lstrip().startswith('#') scan.

cc4q.pipeline.metrics.iter_py_files(root, include_dirs=None)[source]

Yield .py files under root, restricted to include_dirs.

Parameters:
  • root – Repository checkout root.

  • include_dirs – Optional subdirectories (relative names) to scan.

Yields:

Absolute paths to Python files, sorted per directory.

cc4q.pipeline.metrics.count_comment_code_lines(path)[source]

Count comment and code lines in one Python file.

Parameters:

path – Path to a Python source file.

Returns:

A (comment_lines, code_lines) tuple. A physical line counts as a comment line when it carries a # token; blank lines count as neither. Files that fail to tokenize fall back to a prefix scan.

cc4q.pipeline.metrics.compute_comment_density(root, include_dirs=None)[source]

Aggregate comment density over a repository checkout.

Parameters:
  • root – Repository checkout root.

  • include_dirs – Optional subdirectories (relative names) to scan.

Returns:

{"comment_lines": int, "code_lines": int, "value": float} where value = comment_lines / code_lines (0.0 if there are no code lines).

cc4q.pipeline.metrics.quantum_residence(units)[source]

Count quantum SCCUs per (comment_type, entity_level).

Parameters:

units – Lean unit dicts/DataFrame records with comment_type, code_entity_type, and quantum_related keys.

Returns:

{comment_type: {entity_level: count}} over quantum units only.