샘플
charset-normalizer 3.5.1: charset_normalizer.from_path
검증된 샘플 — pypi charset-normalizer 3.5.1: charset_normalizer.from_path. python 3.12 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다.
sha256:59df8ccb30e067a102b101bf2f9b2449df740334df2562f6de428f2c213c075d
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 2
- 빌드한 서명 키
- 1
선언된 환경
python 3.12 linux 24 · ubuntu · glibc 2.39 x64 python 3.12 python pip
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962… |
2026-08-26 |
| python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104… |
2026-09-08 |
케이스
HOW- 목표
- verify charset_normalizer.from_path in pkg:pypi/charset-normalizer@3.5.1
- 심벌
-
- charset_normalizer.from_path
- 환경
- python 3.12
- 생성일
- 2026-08-26T04:36:06Z
컨트랙트
- charset_normalizer.from_path(path) detects character encoding from file path or PathLike object
- from_path(path) returns CharsetMatches containing candidate matches with best() giving optimal CharsetMatch
- best.encoding identifies utf_8 and ascii encodings accurately
- str(best) decodes file content into unicode string
- from_path(path) raises FileNotFoundError for nonexistent paths and TypeError for invalid argument types
파일
- PROMPT.md
- csx.json
- requirements.txt
- spec.json
- src/file_detector.py
- test/contract.py
소스
Clean-room public code sample — generation instructions
Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.
A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.
Goal: verify charset_normalizer.from_path in pkg:pypi/charset-normalizer@3.5.1
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:pypi/charset-normalizer@3.5.1
Demonstrate these symbols/APIs:
- charset_normalizer.from_path
Rules:
- One focused purpose; the smallest project that proves the goal.
- Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
- Pin every dependency with a lockfile so resolution is reproducible.
- No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
- No personal names, emails, company names, or project identifiers of any kind.
- No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
- Keep it under 200 files and 256KB packed.
{"case":{"caseId":"case:sha256:fca59a65aad4476e7298686ed3e723a23d61786a6b21cc13ce1554a19b09b826","contract":["charset_normalizer.from_path(path) detects character encoding from file path or PathLike object","from_path(path) returns CharsetMatches containing candidate matches with best() giving optimal CharsetMatch","best.encoding identifies utf_8 and ascii encodings accurately","str(best) decodes file content into unicode string","from_path(path) raises FileNotFoundError for nonexistent paths and TypeError for invalid argument types"],"goal":"verify charset_normalizer.from_path in pkg:pypi/charset-normalizer@3.5.1","kind":"HOW","packages":["pkg:pypi/charset-normalizer@3.5.1"],"schemaVersion":1,"symbols":["charset_normalizer.from_path"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","runtimeVersion":"3.12","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/charset-normalizer@3.5.1"],"schemaVersion":1,"subject":"pkg:pypi/charset-normalizer@3.5.1","symbols":["charset_normalizer.from_path"],"verifierAdapter":"python@1"}
charset-normalizer==3.5.1
{
"schemaVersion": 1,
"goal": "verify charset_normalizer.from_path in pkg:pypi/charset-normalizer@3.5.1",
"kind": "HOW",
"packages": [
"pkg:pypi/charset-normalizer@3.5.1"
],
"symbols": [
"charset_normalizer.from_path"
]
}
"""File charset detection module demonstrating charset_normalizer.from_path."""
from pathlib import Path
from typing import Optional, Union
import charset_normalizer
from charset_normalizer import CharsetMatch, CharsetMatches
def detect_file_encoding(file_path: Union[str, Path]) -> Optional[str]:
"""Detect the character encoding of a file using charset_normalizer.from_path.
Args:
file_path: Path to the file (str or PathLike).
Returns:
The detected encoding name (e.g. 'utf_8', 'ascii') or None if undetected.
Raises:
FileNotFoundError: If the file does not exist.
TypeError: If file_path is not a valid path-like object.
"""
matches: CharsetMatches = charset_normalizer.from_path(file_path)
best: Optional[CharsetMatch] = matches.best()
return best.encoding if best is not None else None
def read_file_with_detection(file_path: Union[str, Path]) -> str:
"""Read and decode a file's content using detected charset from charset_normalizer.from_path.
Args:
file_path: Path to the file (str or PathLike).
Returns:
Decoded text content as a unicode string.
Raises:
FileNotFoundError: If the file does not exist.
TypeError: If file_path is not a valid path-like object.
ValueError: If no charset match could be determined.
"""
matches: CharsetMatches = charset_normalizer.from_path(file_path)
best: Optional[CharsetMatch] = matches.best()
if best is None:
raise ValueError(f"Could not determine charset for {file_path}")
return str(best)
"""Contract verification test for charset_normalizer.from_path."""
import os
import pathlib
import sys
import tempfile
# Ensure repository root is on sys.path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import charset_normalizer
from charset_normalizer import CharsetMatch, CharsetMatches
from src.file_detector import detect_file_encoding, read_file_with_detection
def test_from_path_utf8():
sample_text = "Bonjour le monde! Café & thé. 안녕하세요 반갑습니다."
with tempfile.NamedTemporaryFile("wb", delete=False) as f:
f.write(sample_text.encode("utf-8"))
temp_path = f.name
try:
matches = charset_normalizer.from_path(temp_path)
assert isinstance(matches, CharsetMatches), f"Expected CharsetMatches, got {type(matches)}"
assert len(matches) >= 1, "Expected at least one match"
best = matches.best()
assert isinstance(best, CharsetMatch), f"Expected CharsetMatch, got {type(best)}"
assert best.encoding == "utf_8", f"Expected utf_8, got {best.encoding}"
assert sample_text in str(best), "Decoded content did not match original text"
detected_enc = detect_file_encoding(temp_path)
assert detected_enc == "utf_8", f"Expected utf_8 from helper, got {detected_enc}"
content = read_file_with_detection(temp_path)
assert content == sample_text, "Decoded text helper mismatch"
finally:
if os.path.exists(temp_path):
os.remove(temp_path)
def test_from_path_ascii():
sample_text = "Simple ASCII text file content for encoding verification."
with tempfile.NamedTemporaryFile("wb", delete=False) as f:
f.write(sample_text.encode("ascii"))
temp_path = f.name
try:
matches = charset_normalizer.from_path(temp_path)
assert isinstance(matches, CharsetMatches), f"Expected CharsetMatches, got {type(matches)}"
best = matches.best()
assert best is not None, "Expected best match for ASCII file"
assert best.encoding == "ascii", f"Expected ascii, got {best.encoding}"
assert str(best) == sample_text, "Decoded content mismatch"
detected_enc = detect_file_encoding(temp_path)
assert detected_enc == "ascii", f"Expected ascii from helper, got {detected_enc}"
finally:
if os.path.exists(temp_path):
os.remove(temp_path)
def test_from_path_pathlib():
sample_text = "Testing pathlib.Path input with emoji: 🚀✨"
with tempfile.NamedTemporaryFile("wb", delete=False) as f:
f.write(sample_text.encode("utf-8"))
temp_path = pathlib.Path(f.name)
try:
matches = charset_normalizer.from_path(temp_path)
best = matches.best()
assert best is not None, "Expected best match for Path object"
assert best.encoding == "utf_8", f"Expected utf_8, got {best.encoding}"
assert "🚀✨" in str(best), "Emoji content missing"
content = read_file_with_detection(temp_path)
assert content == sample_text, "Pathlib helper content mismatch"
finally:
if temp_path.exists():
temp_path.unlink()
def test_from_path_errors():
# Nonexistent path should raise FileNotFoundError
non_existent = "non_existent_file_path_xyz_12345.txt"
try:
charset_normalizer.from_path(non_existent)
assert False, "Expected FileNotFoundError for non-existent file"
except FileNotFoundError:
pass
try:
detect_file_encoding(non_existent)
assert False, "Expected FileNotFoundError from helper"
except FileNotFoundError:
pass
# Invalid argument type should raise TypeError
try:
charset_normalizer.from_path(None)
assert False, "Expected TypeError when passing None to from_path"
except TypeError:
pass
def main():
test_from_path_utf8()
test_from_path_ascii()
test_from_path_pathlib()
test_from_path_errors()
print("Contract tests for charset_normalizer.from_path passed successfully.")
return 0
if __name__ == "__main__":
sys.exit(main())
오리진 시더
익명