mokner99's picture
Release validated November 18 expansion and measured usage receipts
ff376c5 verified
Raw History Blame Contribute Delete
1.27 kB
"""Physical-line and Python lexical-token counts, distinct from model token usage."""
import io
import tokenize
def code_statistics(source):
if not isinstance(source, str):
raise TypeError("Source must be a string")
lines = source.splitlines()
ignored = {
tokenize.ENCODING,
tokenize.ENDMARKER,
tokenize.INDENT,
tokenize.DEDENT,
tokenize.NEWLINE,
tokenize.NL,
tokenize.COMMENT,
}
try:
tokens = list(tokenize.generate_tokens(io.StringIO(source).readline))
lexical = sum(t.type not in ignored for t in tokens)
comment_lines = {
t.start[0]
for t in tokens
if t.type == tokenize.COMMENT and not lines[t.start[0] - 1][: t.start[1]].strip()
}
except (tokenize.TokenError, IndentationError, SyntaxError):
lexical = None
comment_lines = {i + 1 for i, line in enumerate(lines) if line.lstrip().startswith("#")}
return {
"physical_lines": len(lines),
"nonblank_noncomment_lines": sum(
bool(line.strip()) and i + 1 not in comment_lines for i, line in enumerate(lines)
),
"utf8_bytes": len(source.encode()),
"python_lexical_tokens": lexical,
}