From 0f63d327a46414a4d62885272b33534054d66006 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Do=C4=9Fan=20Can=20Bak=C4=B1r?= Date: Sun, 1 Nov 2026 08:41:00 +0000 Subject: [PATCH 1/2] docs: add star history chart to README --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index ac5e3ab..5dfceb4 100644 --- a/README.md +++ b/README.md @@ -86,3 +86,7 @@ pytest -q ## Contribution Your contributions will help us make this project better. Please use GitHub issues for bug reports or feature requests. + +## Star History + +[![Star History Chart](https://api.star-history.com/svg?repos=HappyHackingSpace/LevelUp&type=Date)](https://star-history.com/#HappyHackingSpace/LevelUp&Date) From f68a9931d26755f7cdc1cd414c6dd297b1fbd0a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Do=C4=9Fan=20Can=20Bak=C4=B1r?= Date: Sun, 1 Nov 2026 08:47:48 +0000 Subject: [PATCH 2/2] feat: generate shareable analysis results links After a CV analysis completes, users can generate a unique shareable link so the same results can be viewed again without re-running the analysis. - Add levelup/share.py: persists completed analyses as JSON under an unguessable id (secrets.token_urlsafe, 128 bits) in a configurable SHARED_RESULTS_DIR; ids are validated against the token alphabet to prevent path traversal on lookup. - Streamlit app: keep the completed analysis in session state, add a "Generate shareable link" section with a copyable URL, and render a read-only shared report when opened with ?share_id=. - Only the analysis result, report language and target role are stored; the uploaded CV is never persisted or shared. - Add tests for the share store and the new UI helpers following the existing pytest-mock patterns. Closes #31 --- .gitignore | 3 + levelup/app.py | 69 +++++++++++++++++- levelup/config.py | 3 + levelup/share.py | 79 +++++++++++++++++++++ tests/test_share.py | 169 ++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 322 insertions(+), 1 deletion(-) create mode 100644 levelup/share.py create mode 100644 tests/test_share.py diff --git a/.gitignore b/.gitignore index c3002d8..1713c5f 100644 --- a/.gitignore +++ b/.gitignore @@ -214,3 +214,6 @@ __marimo__/ # Streamlit .streamlit/secrets.toml + +# Shared analysis results +shared_results/ diff --git a/levelup/app.py b/levelup/app.py index 965b75b..2b1f17a 100644 --- a/levelup/app.py +++ b/levelup/app.py @@ -1,6 +1,7 @@ import json import re from typing import Any, Optional, cast +from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit import google.generativeai as genai import pandas as pd # type: ignore[import-untyped] @@ -9,6 +10,7 @@ from levelup import config from levelup.prompts import get_resume_analysis_prompt +from levelup.share import load_shared_analysis, save_shared_analysis GEMINI_API_KEY = config.GEMINI_API_KEY if not GEMINI_API_KEY: @@ -281,6 +283,54 @@ def display_recommendations_tab(result: dict[str, Any]) -> None: st.info("No recommendations returned.") +def build_share_url(share_id: str) -> str: + """Builds an absolute share URL for the given share id when possible.""" + try: + base_url = str(st.context.url or "") + except Exception: + base_url = "" + if not base_url: + return f"?share_id={share_id}" + parsed = urlsplit(base_url) + query = dict(parse_qsl(parsed.query)) + query["share_id"] = share_id + return urlunsplit((parsed.scheme, parsed.netloc, parsed.path, urlencode(query), "")) + + +def display_share_section( + result: dict[str, Any], report_language: str, target_role: Optional[str] +) -> None: + """Lets the user generate and copy a shareable link for the results.""" + st.divider() + st.subheader("Share these results") + if st.button("Generate shareable link"): + try: + share_id = save_shared_analysis(result, report_language, target_role) + st.session_state["share_id"] = share_id + except OSError as e: + st.error(f"Could not create a shareable link: {e}") + stored_share_id = st.session_state.get("share_id") + if stored_share_id: + st.code(build_share_url(stored_share_id), language=None) + st.caption( + "Anyone with this link can view this analysis report. " + "The uploaded CV file is not shared." + ) + + +def render_shared_analysis(share_id: str) -> None: + """Renders a read-only view of a previously shared analysis.""" + payload = load_shared_analysis(share_id) + if not payload: + st.error("This share link is invalid or no longer available.") + return + st.caption("Shared analysis report (read-only).") + target_role = payload.get("target_role") + if target_role: + st.markdown(f"**Target Role:** {target_role}") + display_analysis_tabs(payload["result"]) + + def display_analysis_tabs(result: dict[str, Any]) -> None: display_summary_block(result) tabs = st.tabs( @@ -306,6 +356,11 @@ def display_analysis_tabs(result: dict[str, Any]) -> None: st.title("LevelUp") +shared_id = st.query_params.get("share_id") +if shared_id: + render_shared_analysis(shared_id) + st.stop() + uploaded_file = st.file_uploader("Upload your Resume (PDF)", type="pdf") if uploaded_file: text = extract_text_from_pdf(uploaded_file) @@ -398,4 +453,16 @@ def display_analysis_tabs(result: dict[str, Any]) -> None: with st.spinner("Analyzing Resume..."): result = analyzecv_pdf_withllm(text, selected_language, selected_role) if result: - display_analysis_tabs(result) + st.session_state["analysis_result"] = result + st.session_state["analysis_language"] = selected_language + st.session_state["analysis_role"] = selected_role + st.session_state.pop("share_id", None) + + analysis_result = st.session_state.get("analysis_result") + if analysis_result: + display_analysis_tabs(analysis_result) + display_share_section( + analysis_result, + st.session_state.get("analysis_language", selected_language), + st.session_state.get("analysis_role"), + ) diff --git a/levelup/config.py b/levelup/config.py index 086ddbc..d93a008 100644 --- a/levelup/config.py +++ b/levelup/config.py @@ -103,3 +103,6 @@ def get_env_tags(tag_list: list[str]) -> dict: ) GEMINI_API_KEY = config("GEMINI_API_KEY", default="", cast=str) + +# Directory where shareable analysis results are stored. +SHARED_RESULTS_DIR = config("SHARED_RESULTS_DIR", default="shared_results", cast=str) diff --git a/levelup/share.py b/levelup/share.py new file mode 100644 index 0000000..fa99606 --- /dev/null +++ b/levelup/share.py @@ -0,0 +1,79 @@ +"""Persistence for shareable CV analysis results. + +Completed analyses are stored under an unguessable identifier so they can be +viewed again through a share link without re-running the analysis. Results are +kept as JSON files inside ``config.SHARED_RESULTS_DIR``; the storage lives +behind this module so it can be swapped for a database later without touching +the UI. +""" + +import json +import re +import secrets +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Optional + +from levelup import config + +# 16 bytes -> 128 bits of entropy, rendered as a 22-char URL-safe token. +_SHARE_ID_NUM_BYTES = 16 + +# token_urlsafe alphabet only; also guards against path traversal. +_SHARE_ID_PATTERN = re.compile(r"^[A-Za-z0-9_-]{16,64}$") + + +def _share_dir() -> Path: + """Returns the directory where shared analyses are stored.""" + return Path(config.SHARED_RESULTS_DIR) + + +def is_valid_share_id(share_id: str) -> bool: + """Checks that a share id looks like one we generated.""" + return bool(_SHARE_ID_PATTERN.fullmatch(share_id)) + + +def generate_share_id() -> str: + """Generates a cryptographically unguessable share id.""" + return secrets.token_urlsafe(_SHARE_ID_NUM_BYTES) + + +def save_shared_analysis( + result: dict[str, Any], + report_language: str, + target_role: Optional[str] = None, +) -> str: + """Persists a completed analysis and returns its share id. + + Only the analysis result and the report settings are stored; the uploaded + CV itself is never persisted. + """ + share_id = generate_share_id() + payload = { + "share_id": share_id, + "result": result, + "report_language": report_language, + "target_role": target_role, + "created_at": datetime.now(timezone.utc).isoformat(), + } + share_dir = _share_dir() + share_dir.mkdir(parents=True, exist_ok=True) + path = share_dir / f"{share_id}.json" + path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8") + return share_id + + +def load_shared_analysis(share_id: str) -> dict[str, Any] | None: + """Loads a previously shared analysis, or None if it does not exist.""" + if not is_valid_share_id(share_id): + return None + path = _share_dir() / f"{share_id}.json" + if not path.is_file(): + return None + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return None + if not isinstance(payload, dict) or not isinstance(payload.get("result"), dict): + return None + return payload diff --git a/tests/test_share.py b/tests/test_share.py new file mode 100644 index 0000000..2a07578 --- /dev/null +++ b/tests/test_share.py @@ -0,0 +1,169 @@ +import json +import os +import sys +from pathlib import Path + +import pytest +from pytest_mock import MockerFixture + +sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) + +from levelup import config +from levelup.app import build_share_url, display_share_section, render_shared_analysis +from levelup.share import ( + generate_share_id, + is_valid_share_id, + load_shared_analysis, + save_shared_analysis, +) + +SAMPLE_RESULT = { + "language": "English", + "domain_scores": [{"domain": "IT", "score": 90, "justification": "Strong"}], + "overall_summary": {"overall_score": 85}, +} + + +def test_generate_share_id_is_unguessable_and_unique() -> None: + ids = {generate_share_id() for _ in range(100)} + assert len(ids) == 100 + for share_id in ids: + assert is_valid_share_id(share_id) + assert len(share_id) >= 16 + + +def test_is_valid_share_id_rejects_malicious_ids() -> None: + assert not is_valid_share_id("") + assert not is_valid_share_id("short") + assert not is_valid_share_id("../../../etc/passwd") + assert not is_valid_share_id("id with spaces 1234") + assert not is_valid_share_id("a" * 100) + assert is_valid_share_id("abcDEF123456_-789012") + + +def test_save_and_load_roundtrip( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(config, "SHARED_RESULTS_DIR", str(tmp_path)) + + share_id = save_shared_analysis(SAMPLE_RESULT, "English", "Data Scientist") + + assert is_valid_share_id(share_id) + payload = load_shared_analysis(share_id) + assert payload is not None + assert payload["result"] == SAMPLE_RESULT + assert payload["report_language"] == "English" + assert payload["target_role"] == "Data Scientist" + assert payload["share_id"] == share_id + assert payload["created_at"] + + +def test_save_without_target_role( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(config, "SHARED_RESULTS_DIR", str(tmp_path)) + + share_id = save_shared_analysis(SAMPLE_RESULT, "Turkish") + + payload = load_shared_analysis(share_id) + assert payload is not None + assert payload["target_role"] is None + assert payload["report_language"] == "Turkish" + + +def test_load_unknown_or_invalid_share_id( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(config, "SHARED_RESULTS_DIR", str(tmp_path)) + + assert load_shared_analysis("a" * 22) is None + assert load_shared_analysis("../../../etc/passwd") is None + + +def test_load_corrupted_payload( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(config, "SHARED_RESULTS_DIR", str(tmp_path)) + + bad_json_id = "a" * 22 + (tmp_path / f"{bad_json_id}.json").write_text("not json", encoding="utf-8") + assert load_shared_analysis(bad_json_id) is None + + bad_shape_id = "b" * 22 + (tmp_path / f"{bad_shape_id}.json").write_text( + json.dumps({"result": "not a dict"}), encoding="utf-8" + ) + assert load_shared_analysis(bad_shape_id) is None + + +def test_build_share_url_from_context(mocker: MockerFixture) -> None: + mock_st = mocker.patch("levelup.app.st") + mock_st.context.url = "http://localhost:8501/?foo=1" + + url = build_share_url("tok123") + + assert url == "http://localhost:8501/?foo=1&share_id=tok123" + + +def test_build_share_url_without_context(mocker: MockerFixture) -> None: + mock_st = mocker.patch("levelup.app.st") + mock_st.context.url = "" + + assert build_share_url("tok123") == "?share_id=tok123" + + +def test_render_shared_analysis_found(mocker: MockerFixture) -> None: + mock_st = mocker.patch("levelup.app.st") + mock_tabs = mocker.patch("levelup.app.display_analysis_tabs") + mocker.patch( + "levelup.app.load_shared_analysis", + return_value={ + "result": SAMPLE_RESULT, + "report_language": "English", + "target_role": "Data Scientist", + }, + ) + + render_shared_analysis("tok123") + + mock_st.error.assert_not_called() + mock_st.markdown.assert_any_call("**Target Role:** Data Scientist") + mock_tabs.assert_called_once_with(SAMPLE_RESULT) + + +def test_render_shared_analysis_not_found(mocker: MockerFixture) -> None: + mock_st = mocker.patch("levelup.app.st") + mock_tabs = mocker.patch("levelup.app.display_analysis_tabs") + mocker.patch("levelup.app.load_shared_analysis", return_value=None) + + render_shared_analysis("unknown") + + mock_st.error.assert_called_once() + mock_tabs.assert_not_called() + + +def test_display_share_section_generates_link(mocker: MockerFixture) -> None: + mock_st = mocker.patch("levelup.app.st") + mock_st.session_state = {} + mock_st.button.return_value = True + mock_st.context.url = "http://example.com/" + mocker.patch("levelup.app.save_shared_analysis", return_value="tok123") + + display_share_section(SAMPLE_RESULT, "English", None) + + assert mock_st.session_state["share_id"] == "tok123" + mock_st.code.assert_called_once_with( + "http://example.com/?share_id=tok123", language=None + ) + + +def test_display_share_section_handles_storage_error(mocker: MockerFixture) -> None: + mock_st = mocker.patch("levelup.app.st") + mock_st.session_state = {} + mock_st.button.return_value = True + mocker.patch("levelup.app.save_shared_analysis", side_effect=OSError("disk full")) + + display_share_section(SAMPLE_RESULT, "English", None) + + mock_st.error.assert_called_once() + mock_st.code.assert_not_called()