cpscribe 0.1.0__tar.gz

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,4 @@
1
+ #!/bin/bash
2
+ set -e
3
+ ruff check src/ tests/
4
+ ruff format --check src/ tests/
@@ -0,0 +1,19 @@
1
+ # Contributing
2
+
3
+ Open an issue before starting non-trivial work so we can discuss the approach.
4
+
5
+ ## Setup
6
+
7
+ ```sh
8
+ git clone https://github.com/shravanngoswamii/cpscribe
9
+ cd cpscribe
10
+ pip install -e ".[dev]"
11
+ git config core.hooksPath .githooks
12
+ ```
13
+
14
+ ## Workflow
15
+
16
+ - One commit per logical change, concise message in casual tone
17
+ - Run `ruff check src/ tests/` and `ruff format src/ tests/` before committing
18
+ - Add or update tests for any changed behavior
19
+ - Update `CHANGELOG.md` under `[Unreleased]`
@@ -0,0 +1,23 @@
1
+ name: Bug report
2
+ description: Something is broken
3
+ labels: [bug]
4
+ body:
5
+ - type: input
6
+ id: version
7
+ attributes:
8
+ label: cpscribe version
9
+ placeholder: "0.1.0"
10
+ validations:
11
+ required: true
12
+ - type: textarea
13
+ id: description
14
+ attributes:
15
+ label: What happened?
16
+ validations:
17
+ required: true
18
+ - type: textarea
19
+ id: repro
20
+ attributes:
21
+ label: Steps to reproduce
22
+ validations:
23
+ required: true
@@ -0,0 +1,16 @@
1
+ name: Feature request
2
+ description: Suggest an improvement
3
+ labels: [enhancement]
4
+ body:
5
+ - type: textarea
6
+ id: problem
7
+ attributes:
8
+ label: What problem does this solve?
9
+ validations:
10
+ required: true
11
+ - type: textarea
12
+ id: proposal
13
+ attributes:
14
+ label: Proposed solution
15
+ validations:
16
+ required: true
@@ -0,0 +1,13 @@
1
+ ## What
2
+
3
+ <!-- What does this PR change? -->
4
+
5
+ ## Why
6
+
7
+ <!-- Why is this change needed? Link to an issue if applicable. -->
8
+
9
+ ## Checklist
10
+
11
+ - [ ] Tests pass (`pytest -q`)
12
+ - [ ] Lint passes (`ruff check src/ tests/`)
13
+ - [ ] `CHANGELOG.md` updated
@@ -0,0 +1,20 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ check:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+ - uses: actions/setup-python@v5
15
+ with:
16
+ python-version: "3.12"
17
+ - run: pip install -e ".[dev]" -q
18
+ - run: ruff check src/ tests/
19
+ - run: ruff format --check src/ tests/
20
+ - run: pytest -q
@@ -0,0 +1,75 @@
1
+ name: Release trigger
2
+
3
+ on:
4
+ issue_comment:
5
+ types:
6
+ - created
7
+ workflow_dispatch:
8
+
9
+ permissions:
10
+ contents: write
11
+ issues: write
12
+
13
+ jobs:
14
+ trigger:
15
+ if: github.event_name == 'workflow_dispatch' || github.event.comment.body == '/release'
16
+ runs-on: ubuntu-latest
17
+
18
+ steps:
19
+ - name: Check write permission
20
+ if: github.event_name == 'issue_comment'
21
+ uses: actions/github-script@v8
22
+ with:
23
+ script: |
24
+ const { data } = await github.rest.repos.getCollaboratorPermissionLevel({
25
+ owner: context.repo.owner,
26
+ repo: context.repo.repo,
27
+ username: context.payload.comment.user.login,
28
+ });
29
+ if (!['admin', 'write'].includes(data.permission)) {
30
+ core.setFailed(`@${context.payload.comment.user.login} does not have write access`);
31
+ }
32
+
33
+ - name: Checkout
34
+ uses: actions/checkout@v6
35
+ with:
36
+ fetch-depth: 0
37
+ token: ${{ secrets.RELEASE_PAT }}
38
+
39
+ - name: Read version and verify tag is new
40
+ id: version
41
+ shell: bash
42
+ run: |
43
+ version="$(grep -m1 '^version = ' pyproject.toml | sed 's/version = "\(.*\)"/\1/')"
44
+ tag="v${version}"
45
+ if git rev-parse "$tag" >/dev/null 2>&1; then
46
+ echo "Tag $tag already exists -- bump the version in pyproject.toml first" >&2
47
+ exit 1
48
+ fi
49
+ echo "tag=${tag}" >> "$GITHUB_OUTPUT"
50
+
51
+ - name: Create and push tag
52
+ run: |
53
+ git config user.name "github-actions[bot]"
54
+ git config user.email "github-actions[bot]@users.noreply.github.com"
55
+ tag="${{ steps.version.outputs.tag }}"
56
+ msg="Release ${tag}"
57
+ if [[ "${{ github.event_name }}" == "issue_comment" ]]; then
58
+ msg="${msg}"$'\n'"issue=${{ github.event.issue.number }}"$'\n'"comment=${{ github.event.comment.id }}"
59
+ else
60
+ msg="${msg}"$'\n'"issue=1"
61
+ fi
62
+ git tag -a "${tag}" HEAD -m "${msg}"
63
+ git push origin "${tag}"
64
+
65
+ - name: React with rocket
66
+ if: success() && github.event_name == 'issue_comment'
67
+ uses: actions/github-script@v8
68
+ with:
69
+ script: |
70
+ await github.rest.reactions.createForIssueComment({
71
+ owner: context.repo.owner,
72
+ repo: context.repo.repo,
73
+ comment_id: context.payload.comment.id,
74
+ content: 'rocket',
75
+ });
@@ -0,0 +1,153 @@
1
+ name: Release
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - "v*.*.*"
7
+
8
+ permissions:
9
+ contents: write
10
+ issues: write
11
+
12
+ jobs:
13
+ validate:
14
+ name: Validate tag
15
+ runs-on: ubuntu-latest
16
+ outputs:
17
+ version: ${{ steps.version.outputs.version }}
18
+
19
+ steps:
20
+ - uses: actions/checkout@v6
21
+
22
+ - name: Read version
23
+ id: version
24
+ shell: bash
25
+ run: |
26
+ version="${GITHUB_REF_NAME#v}"
27
+ if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
28
+ echo "Release tag must look like v1.2.3; got ${GITHUB_REF_NAME}" >&2
29
+ exit 1
30
+ fi
31
+ pkg_version="$(grep -m1 '^version = ' pyproject.toml | sed 's/version = "\(.*\)"/\1/')"
32
+ if [[ "$version" != "$pkg_version" ]]; then
33
+ echo "Tag v$version does not match pyproject.toml version $pkg_version" >&2
34
+ exit 1
35
+ fi
36
+ echo "version=$version" >> "$GITHUB_OUTPUT"
37
+
38
+ quality:
39
+ name: Quality gate
40
+ needs: validate
41
+ runs-on: ubuntu-latest
42
+
43
+ steps:
44
+ - uses: actions/checkout@v6
45
+ - uses: actions/setup-python@v5
46
+ with:
47
+ python-version: "3.12"
48
+ - run: pip install -e ".[dev]" -q
49
+ - run: ruff check src/ tests/
50
+ - run: ruff format --check src/ tests/
51
+ - run: pytest -q
52
+
53
+ publish:
54
+ name: Publish
55
+ needs:
56
+ - validate
57
+ - quality
58
+ runs-on: ubuntu-latest
59
+ environment: pypi
60
+ permissions:
61
+ contents: write
62
+ id-token: write
63
+
64
+ steps:
65
+ - uses: actions/checkout@v6
66
+
67
+ - uses: actions/setup-python@v5
68
+ with:
69
+ python-version: "3.12"
70
+
71
+ - name: Build wheel and sdist
72
+ run: |
73
+ pip install hatchling -q
74
+ python -m hatchling build
75
+
76
+ - name: Publish to PyPI
77
+ uses: pypa/gh-action-pypi-publish@release/v1
78
+
79
+ - name: Publish GitHub release
80
+ uses: softprops/action-gh-release@v3
81
+ with:
82
+ name: v${{ needs.validate.outputs.version }}
83
+ generate_release_notes: true
84
+ files: dist/*
85
+
86
+ notify:
87
+ name: Notify release comment
88
+ if: always() && needs.validate.result == 'success'
89
+ needs:
90
+ - validate
91
+ - publish
92
+ runs-on: ubuntu-latest
93
+
94
+ steps:
95
+ - uses: actions/checkout@v6
96
+ with:
97
+ fetch-depth: 0
98
+
99
+ - name: Read trigger context from tag annotation
100
+ id: ctx
101
+ run: |
102
+ annotation=$(git tag -l "${{ github.ref_name }}" --format='%(contents)')
103
+ issue=$(printf '%s' "$annotation" | grep '^issue=' | cut -d= -f2)
104
+ comment=$(printf '%s' "$annotation" | grep '^comment=' | cut -d= -f2)
105
+ echo "issue=${issue}" >> "$GITHUB_OUTPUT"
106
+ echo "comment=${comment}" >> "$GITHUB_OUTPUT"
107
+
108
+ - name: Post release status to issue
109
+ if: steps.ctx.outputs.issue != ''
110
+ uses: actions/github-script@v8
111
+ env:
112
+ COMMENT_ID: ${{ steps.ctx.outputs.comment }}
113
+ ISSUE_NUM: ${{ steps.ctx.outputs.issue }}
114
+ PUBLISH_RESULT: ${{ needs.publish.result }}
115
+ with:
116
+ script: |
117
+ const tag = context.ref.replace('refs/tags/', '');
118
+ const version = tag.replace(/^v/, '');
119
+ const repo = `${context.repo.owner}/${context.repo.repo}`;
120
+
121
+ const status = r => ({ success: 'success', failure: 'FAILED', cancelled: 'cancelled', skipped: 'skipped' }[r] ?? r);
122
+ const publishResult = process.env.PUBLISH_RESULT;
123
+ const allGood = publishResult === 'success';
124
+
125
+ const headline = allGood
126
+ ? `**cpscribe ${tag} released**`
127
+ : `**cpscribe ${tag} -- some steps failed** -- [view run](https://github.com/${repo}/actions/runs/${context.runId})`;
128
+
129
+ const body = [
130
+ headline,
131
+ '',
132
+ '| Destination | Status |',
133
+ '| :-- | :-- |',
134
+ `| [GitHub Release](https://github.com/${repo}/releases/tag/${tag}) | ${status(publishResult)} |`,
135
+ `| [PyPI](https://pypi.org/project/cpscribe/${version}) | ${status(publishResult)} |`,
136
+ ].join('\n');
137
+
138
+ const commentId = process.env.COMMENT_ID ? parseInt(process.env.COMMENT_ID, 10) : null;
139
+ if (commentId) {
140
+ await github.rest.issues.updateComment({
141
+ owner: context.repo.owner,
142
+ repo: context.repo.repo,
143
+ comment_id: commentId,
144
+ body: '/release\n\n---\n' + body,
145
+ });
146
+ } else {
147
+ await github.rest.issues.createComment({
148
+ owner: context.repo.owner,
149
+ repo: context.repo.repo,
150
+ issue_number: parseInt(process.env.ISSUE_NUM, 10),
151
+ body,
152
+ });
153
+ }
@@ -0,0 +1,7 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ dist/
5
+ *.egg-info/
6
+ .ruff_cache/
7
+ .pytest_cache/
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
5
+
6
+ ## [Unreleased]
7
+
8
+ ## [0.1.0] - 2026-06-25
9
+
10
+ ### Added
11
+
12
+ - `cpscribe post` command: scrapes Codeforces problem page, generates a structured blog post
13
+ - `cpscribe init` command: interactive config setup
14
+ - Config file at `~/.config/cpscribe/config` with `CPSCRIBE_BLOG_ROOT` / `CPSCRIBE_AUTHOR` env overrides
15
+ - URL extraction from `.cpp` file comments
cpscribe-0.1.0/LICENSE ADDED
@@ -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.
@@ -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,44 @@
1
+ # cpscribe
2
+
3
+ Generate structured blog posts for Codeforces solutions.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pipx install cpscribe
9
+ ```
10
+
11
+ ## Setup
12
+
13
+ ```sh
14
+ cpscribe init
15
+ ```
16
+
17
+ This creates `~/.config/cpscribe/config` with your blog root and author name.
18
+ You can also set `CPSCRIBE_BLOG_ROOT` and `CPSCRIBE_AUTHOR` as environment variables.
19
+
20
+ ## Usage
21
+
22
+ ```sh
23
+ # from a URL
24
+ cpscribe post https://codeforces.com/contest/1903/problem/B
25
+
26
+ # from a .cpp file with a URL in a comment
27
+ cpscribe post B.cpp
28
+
29
+ # with an explicit solution file
30
+ cpscribe post https://codeforces.com/contest/1903/problem/B B.cpp
31
+ ```
32
+
33
+ The generated post includes the full problem statement, sample I/O, and structured
34
+ sections for your approach, complexity, solution, and takeaways.
35
+
36
+ ## Update
37
+
38
+ ```sh
39
+ pipx upgrade cpscribe
40
+ ```
41
+
42
+ ## License
43
+
44
+ MIT
@@ -0,0 +1,48 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "cpscribe"
7
+ version = "0.1.0"
8
+ description = "Generate blog posts for competitive programming solutions"
9
+ authors = [{ name = "Shravan Goswami", email = "contact@shravangoswami.com" }]
10
+ license = { text = "MIT" }
11
+ readme = "README.md"
12
+ requires-python = ">=3.10"
13
+ keywords = ["competitive-programming", "codeforces", "blog", "cli"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Environment :: Console",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Utilities",
21
+ ]
22
+ dependencies = [
23
+ "cloudscraper>=1.2.71",
24
+ "beautifulsoup4>=4.12.0",
25
+ ]
26
+
27
+ [project.urls]
28
+ Repository = "https://github.com/shravanngoswamii/cpscribe"
29
+ Issues = "https://github.com/shravanngoswamii/cpscribe/issues"
30
+
31
+ [project.scripts]
32
+ cpscribe = "cpscribe.cli:main"
33
+
34
+ [project.optional-dependencies]
35
+ dev = ["pytest>=8.0", "ruff>=0.4.0"]
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["src/cpscribe"]
39
+
40
+ [tool.ruff]
41
+ line-length = 100
42
+ src = ["src"]
43
+
44
+ [tool.ruff.lint]
45
+ select = ["E", "F", "I", "UP"]
46
+
47
+ [tool.pytest.ini_options]
48
+ testpaths = ["tests"]
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from cpscribe.cli import main
2
+
3
+ main()
@@ -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)
@@ -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}")
@@ -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
+ """
@@ -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,17 @@
1
+ import pytest
2
+
3
+
4
+ @pytest.fixture
5
+ def problem() -> dict:
6
+ return {
7
+ "name": "Consecutive Sum Riddle",
8
+ "rating": "800",
9
+ "contest": "Codeforces Round 747 (Div. 2)",
10
+ "time_lim": "2 seconds",
11
+ "mem_lim": "256 megabytes",
12
+ "body": "Find $l$ and $r$ such that $l + \\ldots + r = n$.\n\n",
13
+ "input_spec": "A single integer $n$ ($1 \\le n \\le 10^{12}$).\n\n",
14
+ "output_spec": "Print two integers $l$ and $r$.\n\n",
15
+ "note": "",
16
+ "samples": [("3\n4\n5", "1 2\n1 3\n2 3")],
17
+ }
@@ -0,0 +1,37 @@
1
+ from cpscribe import generator
2
+
3
+
4
+ def test_frontmatter(problem):
5
+ md = generator.build("1594", "A", problem, "// code", "Test Author")
6
+ assert "pubDatetime:" in md
7
+ assert 'title: "A. Consecutive Sum Riddle (CF1594 800 RATED)"' in md
8
+ assert "slug: cp/codeforces/1594/A" in md
9
+ assert "tags: [CPP, Codeforces, CF800]" in md
10
+
11
+
12
+ def test_single_alias(problem):
13
+ md = generator.build("1594", "A", problem, "", "Test Author")
14
+ assert md.count(" - /") == 1
15
+ assert "/writing/1594-A-Consecutive-Sum-Riddle" in md
16
+
17
+
18
+ def test_sections_present(problem):
19
+ md = generator.build("1594", "A", problem, "", "Test Author")
20
+ for section in ("## Problem Statement", "## Examples", "## Approach", "## Solution"):
21
+ assert section in md
22
+ assert "## What I Learned" in md
23
+
24
+
25
+ def test_solution_code_injected(problem):
26
+ code = "#include <bits/stdc++.h>\nint main(){}"
27
+ assert code in generator.build("1594", "A", problem, code, "Test Author")
28
+
29
+
30
+ def test_note_omitted_when_empty(problem):
31
+ problem["note"] = ""
32
+ assert "### Note" not in generator.build("1594", "A", problem, "", "Test Author")
33
+
34
+
35
+ def test_note_included_when_present(problem):
36
+ problem["note"] = "Constraints are tight."
37
+ assert "### Note" in generator.build("1594", "A", problem, "", "Test Author")
@@ -0,0 +1,25 @@
1
+ from cpscribe.scraper import extract_url_from_cpp, parse_url
2
+
3
+
4
+ def test_parse_contest_url():
5
+ cid, idx = parse_url("https://codeforces.com/contest/1594/problem/A")
6
+ assert (cid, idx) == ("1594", "A")
7
+
8
+
9
+ def test_parse_problemset_url():
10
+ cid, idx = parse_url("https://codeforces.com/problemset/problem/1903/B")
11
+ assert (cid, idx) == ("1903", "B")
12
+
13
+
14
+ def test_extract_url_from_line_comment():
15
+ code = "// https://codeforces.com/contest/1594/problem/A\nint main(){}"
16
+ assert extract_url_from_cpp(code) == "https://codeforces.com/contest/1594/problem/A"
17
+
18
+
19
+ def test_extract_url_from_block_comment():
20
+ code = "/* https://codeforces.com/problemset/problem/1903/B */\nint main(){}"
21
+ assert extract_url_from_cpp(code) == "https://codeforces.com/problemset/problem/1903/B"
22
+
23
+
24
+ def test_extract_url_missing():
25
+ assert extract_url_from_cpp("#include <bits/stdc++.h>\nint main(){}") is None