cpscribe 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.
cpscribe/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
cpscribe/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from cpscribe.cli import main
2
+
3
+ main()
cpscribe/cli.py ADDED
@@ -0,0 +1,73 @@
1
+ import argparse
2
+ import subprocess
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ from cpscribe import __version__, generator, scraper
7
+ from cpscribe import config as cfg
8
+
9
+
10
+ def cmd_init(_args) -> None:
11
+ cfg.init_interactive()
12
+
13
+
14
+ def cmd_post(args) -> None:
15
+ conf = cfg.load()
16
+ if not conf["blog_root"]:
17
+ sys.exit("blog_root not configured -- run `cpscribe init` first")
18
+
19
+ if args.input.endswith(".cpp"):
20
+ cpp_file = Path(args.input)
21
+ if not cpp_file.exists():
22
+ sys.exit(f"file not found: {cpp_file}")
23
+ url = scraper.extract_url_from_cpp(cpp_file.read_text())
24
+ if not url:
25
+ sys.exit(f"no Codeforces URL found in {cpp_file}")
26
+ else:
27
+ url = args.input
28
+ cpp_file = Path(args.solution) if args.solution else None
29
+
30
+ contest_id, index = scraper.parse_url(url)
31
+
32
+ if cpp_file is None:
33
+ cpp_file = Path(f"{index}.cpp")
34
+ cpp_code = cpp_file.read_text().strip() if cpp_file.exists() else "// paste your solution here"
35
+
36
+ print(f"fetching CF{contest_id}{index}...")
37
+ problem = scraper.scrape(contest_id, index)
38
+ print(f" {index}. {problem['name']} {problem['rating']} {problem['contest']}")
39
+ print(f" {len(problem['samples'])} sample(s) {problem['time_lim']} {problem['mem_lim']}")
40
+
41
+ out_dir = Path(conf["blog_root"]) / contest_id
42
+ out_file = out_dir / f"{index}.md"
43
+ out_dir.mkdir(parents=True, exist_ok=True)
44
+
45
+ if out_file.exists() and not args.force:
46
+ sys.exit(f"already exists: {out_file} (--force to overwrite)")
47
+
48
+ out_file.write_text(generator.build(contest_id, index, problem, cpp_code, conf["author"]))
49
+ print(f"created: {out_file}")
50
+
51
+ editor = args.editor or conf["editor"]
52
+ if editor:
53
+ subprocess.Popen([editor, str(out_file)])
54
+
55
+
56
+ def main() -> None:
57
+ parser = argparse.ArgumentParser(
58
+ prog="cpscribe",
59
+ description="Generate blog posts for competitive programming solutions",
60
+ )
61
+ parser.add_argument("-v", "--version", action="version", version=f"cpscribe {__version__}")
62
+ sub = parser.add_subparsers(dest="command", required=True)
63
+
64
+ sub.add_parser("init", help="Configure cpscribe interactively")
65
+
66
+ post = sub.add_parser("post", help="Generate a blog post for a Codeforces problem")
67
+ post.add_argument("input", metavar="URL|file.cpp")
68
+ post.add_argument("solution", nargs="?", metavar="solution.cpp")
69
+ post.add_argument("--force", action="store_true", help="overwrite existing post")
70
+ post.add_argument("--editor", metavar="CMD")
71
+
72
+ args = parser.parse_args()
73
+ {"init": cmd_init, "post": cmd_post}[args.command](args)
cpscribe/config.py ADDED
@@ -0,0 +1,49 @@
1
+ import os
2
+ from configparser import ConfigParser
3
+ from pathlib import Path
4
+
5
+ CONFIG_DIR = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "cpscribe"
6
+ CONFIG_FILE = CONFIG_DIR / "config"
7
+
8
+ DEFAULTS: dict[str, str] = {
9
+ "blog_root": "",
10
+ "author": "Shravan Goswami",
11
+ "editor": "subl",
12
+ }
13
+
14
+
15
+ def load() -> dict[str, str]:
16
+ cfg = dict(DEFAULTS)
17
+ if CONFIG_FILE.exists():
18
+ parser = ConfigParser()
19
+ parser.read(CONFIG_FILE)
20
+ if "cpscribe" in parser:
21
+ cfg.update(parser["cpscribe"])
22
+ if v := os.environ.get("CPSCRIBE_BLOG_ROOT"):
23
+ cfg["blog_root"] = v
24
+ if v := os.environ.get("CPSCRIBE_AUTHOR"):
25
+ cfg["author"] = v
26
+ return cfg
27
+
28
+
29
+ def save(cfg: dict[str, str]) -> None:
30
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
31
+ parser = ConfigParser()
32
+ parser["cpscribe"] = cfg
33
+ with open(CONFIG_FILE, "w") as f:
34
+ parser.write(f)
35
+
36
+
37
+ def init_interactive() -> None:
38
+ cfg = load()
39
+ print("cpscribe config\n")
40
+ blog_root = input(f"Blog root [{cfg['blog_root'] or 'required'}]: ").strip()
41
+ author = input(f"Author [{cfg['author']}]: ").strip()
42
+ editor = input(f"Editor [{cfg['editor']}]: ").strip()
43
+ cfg["blog_root"] = blog_root or cfg["blog_root"]
44
+ cfg["author"] = author or cfg["author"]
45
+ cfg["editor"] = editor or cfg["editor"]
46
+ if not cfg["blog_root"]:
47
+ raise SystemExit("blog_root is required")
48
+ save(cfg)
49
+ print(f"\nconfig saved to {CONFIG_FILE}")
cpscribe/generator.py ADDED
@@ -0,0 +1,94 @@
1
+ import re
2
+ from datetime import datetime, timezone
3
+
4
+
5
+ def _slug(name: str) -> str:
6
+ return re.sub(r"[^A-Za-z0-9]+", "-", name).strip("-")
7
+
8
+
9
+ def _fmt_examples(samples: list[tuple[str, str]]) -> str:
10
+ if not samples:
11
+ return "<!-- paste sample inputs/outputs here -->"
12
+ parts = []
13
+ for i, (inp, out) in enumerate(samples, 1):
14
+ label = f"**Example {i}**" if len(samples) > 1 else "**Example**"
15
+ parts.append(f"{label}\n\nInput:\n```\n{inp}\n```\nOutput:\n```\n{out}\n```")
16
+ return "\n\n".join(parts)
17
+
18
+
19
+ def build(
20
+ contest_id: str,
21
+ index: str,
22
+ problem: dict,
23
+ cpp_code: str,
24
+ author: str,
25
+ ) -> str:
26
+ name = problem["name"]
27
+ rating = problem["rating"]
28
+ contest = problem["contest"]
29
+ note_block = f"\n\n### Note\n\n{problem['note']}" if problem.get("note") else ""
30
+ pub_dt = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
31
+ cf_url = f"https://codeforces.com/problemset/problem/{contest_id}/{index}"
32
+
33
+ return f"""\
34
+ ---
35
+ author: {author}
36
+ pubDatetime: {pub_dt}
37
+ title: "{index}. {name} (CF{contest_id} {rating} RATED)"
38
+ slug: cp/codeforces/{contest_id}/{index}
39
+ tags: [CPP, Codeforces, CF{rating}]
40
+ description: "{index}. {name}, {rating} RATED - {contest}"
41
+ aliases:
42
+ - /writing/{contest_id}-{index}-{_slug(name)}
43
+ ---
44
+
45
+ Problem Link: [{index}. {name}, {rating} RATED - {contest}]({cf_url})
46
+
47
+ | Time Limit | Memory Limit |
48
+ | --- | --- |
49
+ | {problem["time_lim"]} | {problem["mem_lim"]} |
50
+
51
+ ## Problem Statement
52
+
53
+ {problem["body"]}
54
+
55
+ ### Input
56
+
57
+ {problem["input_spec"]}
58
+
59
+ ### Output
60
+
61
+ {problem["output_spec"]}{note_block}
62
+
63
+ ## Examples
64
+
65
+ {_fmt_examples(problem["samples"])}
66
+
67
+ ## My Understanding
68
+
69
+ <!-- How do you model or restate this problem in your own words? -->
70
+
71
+ ## Key Observations
72
+
73
+ - <!-- Observation 1 -->
74
+ - <!-- Observation 2 -->
75
+
76
+ ## Approach
77
+
78
+ <!-- Walk through your full solution strategy -->
79
+
80
+ ## Complexity
81
+
82
+ - **Time:** $O()$
83
+ - **Space:** $O()$
84
+
85
+ ## Solution
86
+
87
+ ```cpp
88
+ {cpp_code}
89
+ ```
90
+
91
+ ## What I Learned
92
+
93
+ <!-- Key takeaway, trick, or pattern from this problem -->
94
+ """
cpscribe/scraper.py ADDED
@@ -0,0 +1,118 @@
1
+ import re
2
+ import sys
3
+
4
+ import cloudscraper
5
+ from bs4 import BeautifulSoup, NavigableString
6
+
7
+ CF_URL_RE = re.compile(
8
+ r"https://codeforces\.com/(?:contest|problemset/problem)/\d+/(?:problem/)?[A-Za-z]\d*"
9
+ )
10
+
11
+
12
+ def parse_url(url: str) -> tuple[str, str]:
13
+ m = re.search(r"/(?:contest|problemset/problem)/(\d+)/(?:problem/)?([A-Za-z]\d*)", url)
14
+ if not m:
15
+ sys.exit(f"could not parse URL: {url}")
16
+ return m.group(1), m.group(2).upper()
17
+
18
+
19
+ def extract_url_from_cpp(text: str) -> str | None:
20
+ m = CF_URL_RE.search(text)
21
+ return m.group(0) if m else None
22
+
23
+
24
+ def _fix_math(text: str) -> str:
25
+ return re.sub(r"\$\$\$(.+?)\$\$\$", r"$\1$", text, flags=re.DOTALL)
26
+
27
+
28
+ def _node_to_md(node) -> str:
29
+ if isinstance(node, NavigableString):
30
+ return _fix_math(str(node))
31
+ tag = node.name
32
+ inner = "".join(_node_to_md(c) for c in node.children)
33
+ match tag:
34
+ case "p":
35
+ return inner.strip() + "\n\n"
36
+ case "strong" | "b":
37
+ return f"**{inner}**"
38
+ case "em" | "i":
39
+ return f"*{inner}*"
40
+ case "ul" | "ol":
41
+ return inner
42
+ case "li":
43
+ return f"- {inner.strip()}\n"
44
+ case "br":
45
+ return "\n"
46
+ case "div" if "section-title" in node.get("class", []):
47
+ return ""
48
+ case _:
49
+ return inner
50
+
51
+
52
+ def _section_md(div) -> str:
53
+ if not div:
54
+ return ""
55
+ return "".join(_node_to_md(c) for c in div.children).strip()
56
+
57
+
58
+ def _sample_pre(div) -> str:
59
+ pre = div.find("pre")
60
+ if not pre:
61
+ return ""
62
+ lines = pre.find_all("div", class_="test-example-line")
63
+ if lines:
64
+ return "\n".join(d.get_text() for d in lines).strip()
65
+ for br in pre.find_all("br"):
66
+ br.replace_with("\n")
67
+ return pre.get_text().strip()
68
+
69
+
70
+ def scrape(contest_id: str, index: str) -> dict:
71
+ url = f"https://codeforces.com/problemset/problem/{contest_id}/{index}"
72
+ resp = cloudscraper.create_scraper().get(url, timeout=15)
73
+ if resp.status_code != 200:
74
+ sys.exit(f"problem page returned {resp.status_code}")
75
+
76
+ soup = BeautifulSoup(resp.content, "html.parser")
77
+ ps = soup.find("div", class_="problem-statement")
78
+
79
+ header = ps.find("div", class_="header")
80
+ title_div = header.find("div", class_="title") if header else None
81
+ name = re.sub(r"^[A-Z]\d*\.\s*", "", title_div.text.strip()) if title_div else "Unknown"
82
+
83
+ rating_tag = soup.find("span", class_="tag-box", title="Difficulty")
84
+ rating = rating_tag.text.strip().replace("*", "") if rating_tag else "Unrated"
85
+
86
+ rtable = soup.find("table", class_="rtable")
87
+ link = rtable.find("a") if rtable else None
88
+ contest = link.text.strip() if link else f"Codeforces Contest {contest_id}"
89
+
90
+ time_tag = soup.find("div", class_="time-limit")
91
+ mem_tag = soup.find("div", class_="memory-limit")
92
+ time_lim = time_tag.text.replace("time limit per test", "").strip() if time_tag else "2 seconds"
93
+ mem_lim = (
94
+ mem_tag.text.replace("memory limit per test", "").strip() if mem_tag else "256 megabytes"
95
+ )
96
+
97
+ body_div = next((c for c in ps.children if hasattr(c, "get") and not c.get("class")), None)
98
+
99
+ samples = []
100
+ for block in soup.find_all("div", class_="sample-test"):
101
+ for inp_div, out_div in zip(
102
+ block.find_all("div", class_="input"),
103
+ block.find_all("div", class_="output"),
104
+ ):
105
+ samples.append((_sample_pre(inp_div), _sample_pre(out_div)))
106
+
107
+ return {
108
+ "name": name,
109
+ "rating": rating,
110
+ "contest": contest,
111
+ "time_lim": time_lim,
112
+ "mem_lim": mem_lim,
113
+ "body": _section_md(body_div),
114
+ "input_spec": _section_md(ps.find("div", class_="input-specification")),
115
+ "output_spec": _section_md(ps.find("div", class_="output-specification")),
116
+ "note": _section_md(ps.find("div", class_="note")),
117
+ "samples": samples,
118
+ }
@@ -0,0 +1,68 @@
1
+ Metadata-Version: 2.4
2
+ Name: cpscribe
3
+ Version: 0.1.0
4
+ Summary: Generate blog posts for competitive programming solutions
5
+ Project-URL: Repository, https://github.com/shravanngoswamii/cpscribe
6
+ Project-URL: Issues, https://github.com/shravanngoswamii/cpscribe/issues
7
+ Author-email: Shravan Goswami <contact@shravangoswami.com>
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: blog,cli,codeforces,competitive-programming
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Utilities
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: beautifulsoup4>=4.12.0
19
+ Requires-Dist: cloudscraper>=1.2.71
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest>=8.0; extra == 'dev'
22
+ Requires-Dist: ruff>=0.4.0; extra == 'dev'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # cpscribe
26
+
27
+ Generate structured blog posts for Codeforces solutions.
28
+
29
+ ## Install
30
+
31
+ ```sh
32
+ pipx install cpscribe
33
+ ```
34
+
35
+ ## Setup
36
+
37
+ ```sh
38
+ cpscribe init
39
+ ```
40
+
41
+ This creates `~/.config/cpscribe/config` with your blog root and author name.
42
+ You can also set `CPSCRIBE_BLOG_ROOT` and `CPSCRIBE_AUTHOR` as environment variables.
43
+
44
+ ## Usage
45
+
46
+ ```sh
47
+ # from a URL
48
+ cpscribe post https://codeforces.com/contest/1903/problem/B
49
+
50
+ # from a .cpp file with a URL in a comment
51
+ cpscribe post B.cpp
52
+
53
+ # with an explicit solution file
54
+ cpscribe post https://codeforces.com/contest/1903/problem/B B.cpp
55
+ ```
56
+
57
+ The generated post includes the full problem statement, sample I/O, and structured
58
+ sections for your approach, complexity, solution, and takeaways.
59
+
60
+ ## Update
61
+
62
+ ```sh
63
+ pipx upgrade cpscribe
64
+ ```
65
+
66
+ ## License
67
+
68
+ MIT
@@ -0,0 +1,11 @@
1
+ cpscribe/__init__.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
2
+ cpscribe/__main__.py,sha256=EUYOOdGKiEr8UCmFelFBMgqdFuqfbp7xtqXCzzUFYXE,38
3
+ cpscribe/cli.py,sha256=0tSwHGTDDu-l-I9wSjxDylV5kdOZtL97OrdSZg1U8Dg,2611
4
+ cpscribe/config.py,sha256=Uf9b_t2lq7rYL5roHczzAEYTtkSJGDA2WIf7nb4IUPo,1472
5
+ cpscribe/generator.py,sha256=VV_QxQZL3LQVRgSsDSVN0LJ467VjWvWTrTTcePOWd4w,2028
6
+ cpscribe/scraper.py,sha256=poj8BGzqnHU41ymqG1PnUuCQW-xMJLqMXEbWFD5OwRc,3909
7
+ cpscribe-0.1.0.dist-info/METADATA,sha256=YpW5tQKdIOTEt4HcEs_PbzFL-08rIXsVTmq-jrb6QmI,1690
8
+ cpscribe-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
9
+ cpscribe-0.1.0.dist-info/entry_points.txt,sha256=zv8i3OChkxD2Ah8K__1NcdsndadZpTW4X7jfRH4gp3Y,47
10
+ cpscribe-0.1.0.dist-info/licenses/LICENSE,sha256=KzILKCsAx6H42NOCu2eJASd3ecLwthV9Vy_VoZ4D8LI,1072
11
+ cpscribe-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ cpscribe = cpscribe.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shravan Goswami
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.