Spaces:
Running
Running
feat: add daily social requirements sync workflow to this repo
Browse files- .github/workflows/daily-social-requirements.yml +82 -0
- .gitignore +3 -0
- README.md +12 -0
- requirements-social.txt +1 -0
- scripts/post_requirements_to_demandsolution.py +261 -0
- scripts/publish_requirements_page.py +159 -0
- src/__init__.py +2 -0
- src/web_user_summary/__init__.py +2 -0
- src/web_user_summary/cli.py +110 -0
- src/web_user_summary/demand_extractor.py +316 -0
- src/web_user_summary/llm_requirement_filter.py +293 -0
- src/web_user_summary/models.py +58 -0
- src/web_user_summary/reddit_client.py +135 -0
- src/web_user_summary/reporting.py +102 -0
.github/workflows/daily-social-requirements.yml
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: Daily Social Requirements Sync
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
schedule:
|
| 5 |
+
- cron: "15 13 * * *"
|
| 6 |
+
workflow_dispatch:
|
| 7 |
+
|
| 8 |
+
permissions:
|
| 9 |
+
contents: write
|
| 10 |
+
|
| 11 |
+
jobs:
|
| 12 |
+
sync:
|
| 13 |
+
runs-on: ubuntu-latest
|
| 14 |
+
env:
|
| 15 |
+
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
| 16 |
+
OPENAI_MODEL: gpt-4o-mini
|
| 17 |
+
SITE_URL: ${{ vars.DEMANDSOLUTION_SITE_URL }}
|
| 18 |
+
steps:
|
| 19 |
+
- name: Checkout
|
| 20 |
+
uses: actions/checkout@v4
|
| 21 |
+
|
| 22 |
+
- name: Setup Python
|
| 23 |
+
uses: actions/setup-python@v5
|
| 24 |
+
with:
|
| 25 |
+
python-version: "3.11"
|
| 26 |
+
|
| 27 |
+
- name: Install dependencies
|
| 28 |
+
run: python -m pip install --upgrade pip && pip install -r requirements-social.txt
|
| 29 |
+
|
| 30 |
+
- name: Validate required secrets and vars
|
| 31 |
+
run: |
|
| 32 |
+
if [ -z "${OPENAI_API_KEY}" ]; then
|
| 33 |
+
echo "Missing required secret: OPENAI_API_KEY"
|
| 34 |
+
exit 1
|
| 35 |
+
fi
|
| 36 |
+
if [ -z "${SITE_URL}" ]; then
|
| 37 |
+
echo "Missing required repository variable: DEMANDSOLUTION_SITE_URL"
|
| 38 |
+
exit 1
|
| 39 |
+
fi
|
| 40 |
+
|
| 41 |
+
- name: Collect Reddit demand signals
|
| 42 |
+
run: |
|
| 43 |
+
python -m src.web_user_summary.cli \
|
| 44 |
+
--subreddits SaaS,startups,SideProject,Entrepreneur,smallbusiness,productivity,webdev \
|
| 45 |
+
--sort new \
|
| 46 |
+
--per-subreddit 50 \
|
| 47 |
+
--search-per-query 15 \
|
| 48 |
+
--hours 48
|
| 49 |
+
|
| 50 |
+
- name: Resolve latest run directory
|
| 51 |
+
id: run_dir
|
| 52 |
+
run: |
|
| 53 |
+
latest="$(ls -1dt data/reddit_requirements/*_utc | head -n 1)"
|
| 54 |
+
echo "run_dir=${latest}" >> "${GITHUB_OUTPUT}"
|
| 55 |
+
|
| 56 |
+
- name: LLM filter clear requirements
|
| 57 |
+
run: |
|
| 58 |
+
python -m src.web_user_summary.llm_requirement_filter \
|
| 59 |
+
--provider openai \
|
| 60 |
+
--openai-model "${OPENAI_MODEL}" \
|
| 61 |
+
--input-dir "${{ steps.run_dir.outputs.run_dir }}"
|
| 62 |
+
|
| 63 |
+
- name: Auto-post requirements to DemandSolution
|
| 64 |
+
run: |
|
| 65 |
+
python scripts/post_requirements_to_demandsolution.py \
|
| 66 |
+
--site-url "${SITE_URL}" \
|
| 67 |
+
--input-dir "${{ steps.run_dir.outputs.run_dir }}"
|
| 68 |
+
|
| 69 |
+
- name: Cleanup run artifacts
|
| 70 |
+
run: rm -rf "${{ steps.run_dir.outputs.run_dir }}"
|
| 71 |
+
|
| 72 |
+
- name: Commit and push state updates
|
| 73 |
+
run: |
|
| 74 |
+
git config user.name "github-actions[bot]"
|
| 75 |
+
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
| 76 |
+
git add data/reddit_requirements/posting_state.json
|
| 77 |
+
if git diff --cached --quiet; then
|
| 78 |
+
echo "No changes to commit."
|
| 79 |
+
exit 0
|
| 80 |
+
fi
|
| 81 |
+
git commit -m "chore: daily social requirements sync"
|
| 82 |
+
git push
|
.gitignore
CHANGED
|
@@ -4,3 +4,6 @@ node_modules
|
|
| 4 |
prisma/dev.db
|
| 5 |
prisma/dev.db-journal
|
| 6 |
.DS_Store
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
prisma/dev.db
|
| 5 |
prisma/dev.db-journal
|
| 6 |
.DS_Store
|
| 7 |
+
__pycache__/
|
| 8 |
+
*.pyc
|
| 9 |
+
data/reddit_requirements/*_utc/
|
README.md
CHANGED
|
@@ -81,3 +81,15 @@ This repo includes a `Dockerfile` for Spaces. `DATABASE_URL` is required at runt
|
|
| 81 |
For OIDC in Spaces, set `AUTH_URL` to your direct Space domain (for this app: `https://jacksuyu-demandsolution-codex.hf.space`) and configure Google callback URL:
|
| 82 |
|
| 83 |
- `https://jacksuyu-demandsolution-codex.hf.space/api/auth/callback/google`
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
For OIDC in Spaces, set `AUTH_URL` to your direct Space domain (for this app: `https://jacksuyu-demandsolution-codex.hf.space`) and configure Google callback URL:
|
| 82 |
|
| 83 |
- `https://jacksuyu-demandsolution-codex.hf.space/api/auth/callback/google`
|
| 84 |
+
|
| 85 |
+
## Daily Social Requirement Sync (GitHub Actions)
|
| 86 |
+
|
| 87 |
+
This repo includes a daily workflow to collect user requirements from Reddit, LLM-filter to clear software requirements, and auto-post accepted requirements into the live DemandSolution board (tagged `_social_`).
|
| 88 |
+
|
| 89 |
+
- Workflow file: `/Users/jacksu/projects/demandsolution_codex/.github/workflows/daily-social-requirements.yml`
|
| 90 |
+
- Schedule: daily at `13:15 UTC`
|
| 91 |
+
|
| 92 |
+
Required GitHub repository settings:
|
| 93 |
+
|
| 94 |
+
- Secret: `OPENAI_API_KEY`
|
| 95 |
+
- Variable: `DEMANDSOLUTION_SITE_URL` (example: `https://jacksuyu-demandsolution-codex.hf.space/`)
|
requirements-social.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
requests
|
scripts/post_requirements_to_demandsolution.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
import uuid
|
| 8 |
+
from datetime import datetime, timezone
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Dict, List, Tuple
|
| 11 |
+
|
| 12 |
+
import requests
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def parse_args() -> argparse.Namespace:
|
| 16 |
+
parser = argparse.ArgumentParser(description="Auto-post curated social requirements to DemandSolution.")
|
| 17 |
+
parser.add_argument(
|
| 18 |
+
"--site-url",
|
| 19 |
+
default="https://jacksuyu-demandsolution-codex.hf.space",
|
| 20 |
+
help="Base URL of deployed DemandSolution site.",
|
| 21 |
+
)
|
| 22 |
+
parser.add_argument(
|
| 23 |
+
"--input-dir",
|
| 24 |
+
default="",
|
| 25 |
+
help="Run directory with llm_requirement_accepted_curated.json (default: latest under data/reddit_requirements).",
|
| 26 |
+
)
|
| 27 |
+
parser.add_argument(
|
| 28 |
+
"--state-file",
|
| 29 |
+
default="data/reddit_requirements/posting_state.json",
|
| 30 |
+
help="Path to posting state file for dedupe.",
|
| 31 |
+
)
|
| 32 |
+
parser.add_argument("--timeout-s", type=int, default=60)
|
| 33 |
+
parser.add_argument("--dry-run", action="store_true")
|
| 34 |
+
return parser.parse_args()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def latest_run_dir(base: Path) -> Path:
|
| 38 |
+
runs = sorted([p for p in base.iterdir() if p.is_dir() and p.name.endswith("_utc")], key=lambda p: p.name)
|
| 39 |
+
if not runs:
|
| 40 |
+
raise FileNotFoundError(f"No run directories found in {base}")
|
| 41 |
+
return runs[-1]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def load_accepted_requirements(run_dir: Path) -> List[Dict]:
|
| 45 |
+
curated = run_dir / "llm_requirement_accepted_curated.json"
|
| 46 |
+
raw = run_dir / "llm_requirement_accepted.json"
|
| 47 |
+
if curated.exists():
|
| 48 |
+
return json.loads(curated.read_text(encoding="utf-8")).get("accepted", [])
|
| 49 |
+
if raw.exists():
|
| 50 |
+
return json.loads(raw.read_text(encoding="utf-8")).get("accepted", [])
|
| 51 |
+
raise FileNotFoundError(f"No accepted requirements JSON found in {run_dir}")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def load_state(path: Path) -> Dict:
|
| 55 |
+
if path.exists():
|
| 56 |
+
return json.loads(path.read_text(encoding="utf-8"))
|
| 57 |
+
return {"anon_id": str(uuid.uuid4()), "posted_keys": {}, "runs": []}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def save_state(path: Path, state: Dict) -> None:
|
| 61 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 62 |
+
path.write_text(json.dumps(state, indent=2, ensure_ascii=False), encoding="utf-8")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def requirement_key(item: Dict) -> str:
|
| 66 |
+
material = "|".join(
|
| 67 |
+
[
|
| 68 |
+
str(item.get("cluster_id", "")),
|
| 69 |
+
str(item.get("requirement", item.get("normalized_requirement", ""))),
|
| 70 |
+
]
|
| 71 |
+
)
|
| 72 |
+
return hashlib.sha256(material.encode("utf-8")).hexdigest()
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def build_raw_input_text(item: Dict) -> str:
|
| 76 |
+
requirement = str(item.get("requirement", item.get("normalized_requirement", ""))).strip()
|
| 77 |
+
reason = str(item.get("reason", "")).strip()
|
| 78 |
+
mentions = item.get("demand_count", 1)
|
| 79 |
+
examples = item.get("examples", [])
|
| 80 |
+
source_link = ""
|
| 81 |
+
source_title = ""
|
| 82 |
+
if examples:
|
| 83 |
+
source_link = str(examples[0].get("permalink", "")).strip()
|
| 84 |
+
source_title = str(examples[0].get("title", "")).strip()
|
| 85 |
+
|
| 86 |
+
lines = [
|
| 87 |
+
f"User requirement from social community: {requirement}",
|
| 88 |
+
"",
|
| 89 |
+
"Context:",
|
| 90 |
+
f"- Source: Reddit",
|
| 91 |
+
f"- Mention count in this run: {mentions}",
|
| 92 |
+
]
|
| 93 |
+
if reason:
|
| 94 |
+
lines.append(f"- LLM acceptance reason: {reason}")
|
| 95 |
+
if source_title:
|
| 96 |
+
lines.append(f"- Evidence title: {source_title}")
|
| 97 |
+
if source_link:
|
| 98 |
+
lines.append(f"- Evidence link: {source_link}")
|
| 99 |
+
lines.append("")
|
| 100 |
+
lines.append("Please generate a buildable product spec from this requirement.")
|
| 101 |
+
text = "\n".join(lines).strip()
|
| 102 |
+
if len(text) < 20:
|
| 103 |
+
text = (text + " " + requirement).strip()
|
| 104 |
+
return text[:2900]
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def post_idea(session: requests.Session, site_url: str, anon_id: str, payload: Dict, timeout_s: int) -> Tuple[int, Dict]:
|
| 108 |
+
endpoint = site_url.rstrip("/") + "/api/ideas"
|
| 109 |
+
headers = {"x-anon-id": anon_id, "Content-Type": "application/json"}
|
| 110 |
+
resp = session.post(endpoint, headers=headers, json=payload, timeout=timeout_s)
|
| 111 |
+
try:
|
| 112 |
+
body = resp.json()
|
| 113 |
+
except Exception:
|
| 114 |
+
body = {"raw": resp.text[:600]}
|
| 115 |
+
return resp.status_code, body
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def render_report(run_dir: Path, results: List[Dict]) -> None:
|
| 119 |
+
out_json = run_dir / "posted_to_demandsolution.json"
|
| 120 |
+
out_md = run_dir / "posted_to_demandsolution.md"
|
| 121 |
+
out_json.write_text(json.dumps({"results": results}, indent=2, ensure_ascii=False), encoding="utf-8")
|
| 122 |
+
|
| 123 |
+
lines = [
|
| 124 |
+
"# Posted Requirements to DemandSolution",
|
| 125 |
+
"",
|
| 126 |
+
f"- Generated at: {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}",
|
| 127 |
+
f"- Total processed: {len(results)}",
|
| 128 |
+
f"- Posted/merged: {sum(1 for r in results if r['status'] in {'posted', 'merged', 'already_posted'})}",
|
| 129 |
+
"",
|
| 130 |
+
"## Details",
|
| 131 |
+
"",
|
| 132 |
+
]
|
| 133 |
+
for idx, result in enumerate(results, start=1):
|
| 134 |
+
lines.append(f"{idx}. `{result['cluster_id']}` - **{result['status']}**")
|
| 135 |
+
lines.append(f" - requirement: {result['requirement']}")
|
| 136 |
+
if result.get("message"):
|
| 137 |
+
lines.append(f" - message: {result['message']}")
|
| 138 |
+
if result.get("idea_id"):
|
| 139 |
+
lines.append(f" - idea_id: `{result['idea_id']}`")
|
| 140 |
+
out_md.write_text("\n".join(lines).strip() + "\n", encoding="utf-8")
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def main() -> None:
|
| 144 |
+
args = parse_args()
|
| 145 |
+
root = Path(__file__).resolve().parents[1]
|
| 146 |
+
base_data = root / "data" / "reddit_requirements"
|
| 147 |
+
run_dir = Path(args.input_dir) if args.input_dir else latest_run_dir(base_data)
|
| 148 |
+
state_file = root / args.state_file if not Path(args.state_file).is_absolute() else Path(args.state_file)
|
| 149 |
+
|
| 150 |
+
accepted = load_accepted_requirements(run_dir)
|
| 151 |
+
state = load_state(state_file)
|
| 152 |
+
anon_id = state.get("anon_id") or str(uuid.uuid4())
|
| 153 |
+
state["anon_id"] = anon_id
|
| 154 |
+
posted_keys = state.setdefault("posted_keys", {})
|
| 155 |
+
results: List[Dict] = []
|
| 156 |
+
|
| 157 |
+
session = requests.Session()
|
| 158 |
+
session.headers.update({"User-Agent": "youtube-trend-skill-codex/requirements-poster/0.1"})
|
| 159 |
+
try:
|
| 160 |
+
session.get(args.site_url.rstrip("/") + "/", timeout=min(20, args.timeout_s))
|
| 161 |
+
except Exception:
|
| 162 |
+
pass
|
| 163 |
+
|
| 164 |
+
for item in accepted:
|
| 165 |
+
cluster_id = str(item.get("cluster_id", ""))
|
| 166 |
+
requirement = str(item.get("requirement", item.get("normalized_requirement", ""))).strip()
|
| 167 |
+
key = requirement_key(item)
|
| 168 |
+
if key in posted_keys:
|
| 169 |
+
results.append(
|
| 170 |
+
{
|
| 171 |
+
"cluster_id": cluster_id,
|
| 172 |
+
"requirement": requirement,
|
| 173 |
+
"status": "already_posted",
|
| 174 |
+
"idea_id": posted_keys[key].get("idea_id"),
|
| 175 |
+
"message": "Skipped because this requirement key already exists in posting_state.",
|
| 176 |
+
}
|
| 177 |
+
)
|
| 178 |
+
continue
|
| 179 |
+
|
| 180 |
+
payload = {
|
| 181 |
+
"raw_input_text": build_raw_input_text(item),
|
| 182 |
+
"target_users": "People asking for practical productivity and workflow software tools",
|
| 183 |
+
"platform": "Any",
|
| 184 |
+
"constraints": "Prefer simple setup and low friction.",
|
| 185 |
+
"source_tag": "_social_",
|
| 186 |
+
"show_name": False,
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
if args.dry_run:
|
| 190 |
+
results.append(
|
| 191 |
+
{
|
| 192 |
+
"cluster_id": cluster_id,
|
| 193 |
+
"requirement": requirement,
|
| 194 |
+
"status": "dry_run",
|
| 195 |
+
"message": "Prepared payload only; not submitted.",
|
| 196 |
+
}
|
| 197 |
+
)
|
| 198 |
+
continue
|
| 199 |
+
|
| 200 |
+
status, body = post_idea(session, args.site_url, anon_id, payload, args.timeout_s)
|
| 201 |
+
|
| 202 |
+
if status == 201:
|
| 203 |
+
idea_id = body.get("idea", {}).get("id")
|
| 204 |
+
posted_keys[key] = {"idea_id": idea_id, "cluster_id": cluster_id, "posted_at": datetime.now(timezone.utc).isoformat()}
|
| 205 |
+
results.append(
|
| 206 |
+
{
|
| 207 |
+
"cluster_id": cluster_id,
|
| 208 |
+
"requirement": requirement,
|
| 209 |
+
"status": "posted",
|
| 210 |
+
"idea_id": idea_id,
|
| 211 |
+
"message": "Created new idea.",
|
| 212 |
+
}
|
| 213 |
+
)
|
| 214 |
+
elif status == 200 and body.get("merged"):
|
| 215 |
+
idea_id = body.get("idea", {}).get("id")
|
| 216 |
+
posted_keys[key] = {"idea_id": idea_id, "cluster_id": cluster_id, "posted_at": datetime.now(timezone.utc).isoformat()}
|
| 217 |
+
results.append(
|
| 218 |
+
{
|
| 219 |
+
"cluster_id": cluster_id,
|
| 220 |
+
"requirement": requirement,
|
| 221 |
+
"status": "merged",
|
| 222 |
+
"idea_id": idea_id,
|
| 223 |
+
"message": body.get("message", "Merged into existing idea."),
|
| 224 |
+
}
|
| 225 |
+
)
|
| 226 |
+
else:
|
| 227 |
+
results.append(
|
| 228 |
+
{
|
| 229 |
+
"cluster_id": cluster_id,
|
| 230 |
+
"requirement": requirement,
|
| 231 |
+
"status": "failed",
|
| 232 |
+
"message": f"HTTP {status}: {body}",
|
| 233 |
+
}
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
state.setdefault("runs", []).append(
|
| 237 |
+
{
|
| 238 |
+
"run_dir": str(run_dir),
|
| 239 |
+
"posted_at": datetime.now(timezone.utc).isoformat(),
|
| 240 |
+
"results_count": len(results),
|
| 241 |
+
"posted_count": sum(1 for r in results if r["status"] in {"posted", "merged"}),
|
| 242 |
+
}
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
save_state(state_file, state)
|
| 246 |
+
render_report(run_dir, results)
|
| 247 |
+
|
| 248 |
+
print(f"Source run: {run_dir}")
|
| 249 |
+
print(f"Target site: {args.site_url}")
|
| 250 |
+
print(f"Processed requirements: {len(results)}")
|
| 251 |
+
print(f"Posted or merged: {sum(1 for r in results if r['status'] in {'posted', 'merged', 'already_posted'})}")
|
| 252 |
+
print(f"State file: {state_file}")
|
| 253 |
+
print(f"Report JSON: {run_dir / 'posted_to_demandsolution.json'}")
|
| 254 |
+
print(f"Report MD: {run_dir / 'posted_to_demandsolution.md'}")
|
| 255 |
+
|
| 256 |
+
for idx, result in enumerate(results, start=1):
|
| 257 |
+
print(f"{idx:>2}. [{result['cluster_id']}] {result['status']} - {result['requirement'][:120]}")
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
if __name__ == "__main__":
|
| 261 |
+
main()
|
scripts/publish_requirements_page.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import argparse
|
| 5 |
+
import json
|
| 6 |
+
import re
|
| 7 |
+
from datetime import datetime, timezone
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Dict, List
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def parse_args() -> argparse.Namespace:
|
| 13 |
+
parser = argparse.ArgumentParser(description="Publish accepted Reddit requirements to markdown/html pages.")
|
| 14 |
+
parser.add_argument(
|
| 15 |
+
"--input-dir",
|
| 16 |
+
default="",
|
| 17 |
+
help="Directory under data/reddit_requirements containing llm_requirement_accepted_curated.json",
|
| 18 |
+
)
|
| 19 |
+
return parser.parse_args()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def latest_run_dir(base: Path) -> Path:
|
| 23 |
+
dirs = [p for p in base.iterdir() if p.is_dir() and re.match(r"^\d{8}_\d{6}_utc$", p.name)]
|
| 24 |
+
if not dirs:
|
| 25 |
+
raise FileNotFoundError(f"No run directories found in {base}")
|
| 26 |
+
return sorted(dirs, key=lambda p: p.name)[-1]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def load_accepted(input_dir: Path) -> List[Dict]:
|
| 30 |
+
curated = input_dir / "llm_requirement_accepted_curated.json"
|
| 31 |
+
raw = input_dir / "llm_requirement_accepted.json"
|
| 32 |
+
if curated.exists():
|
| 33 |
+
payload = json.loads(curated.read_text(encoding="utf-8"))
|
| 34 |
+
return payload.get("accepted", [])
|
| 35 |
+
if raw.exists():
|
| 36 |
+
payload = json.loads(raw.read_text(encoding="utf-8"))
|
| 37 |
+
return payload.get("accepted", [])
|
| 38 |
+
raise FileNotFoundError(f"No accepted requirements file found in {input_dir}")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def render_markdown(run_dir: Path, accepted: List[Dict]) -> str:
|
| 42 |
+
lines: List[str] = []
|
| 43 |
+
lines.append("# Reddit User Requirements (LLM Curated)")
|
| 44 |
+
lines.append("")
|
| 45 |
+
lines.append(f"- Source run: `{run_dir.name}`")
|
| 46 |
+
lines.append(f"- Generated at: `{datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC')}`")
|
| 47 |
+
lines.append(f"- Accepted requirements: **{len(accepted)}**")
|
| 48 |
+
lines.append("")
|
| 49 |
+
lines.append("## Requirements")
|
| 50 |
+
lines.append("")
|
| 51 |
+
for idx, item in enumerate(accepted, start=1):
|
| 52 |
+
cid = item.get("cluster_id", "")
|
| 53 |
+
req = str(item.get("requirement", item.get("normalized_requirement", ""))).strip()
|
| 54 |
+
reason = str(item.get("reason", "")).strip()
|
| 55 |
+
count = item.get("demand_count", 0)
|
| 56 |
+
lines.append(f"### {idx}. {req}")
|
| 57 |
+
lines.append(f"- Cluster: `{cid}`")
|
| 58 |
+
lines.append(f"- Mentions: {count}")
|
| 59 |
+
if reason:
|
| 60 |
+
lines.append(f"- Why accepted: {reason}")
|
| 61 |
+
examples = item.get("examples", [])
|
| 62 |
+
if examples:
|
| 63 |
+
ex = examples[0]
|
| 64 |
+
title = ex.get("title", "source post")
|
| 65 |
+
link = ex.get("permalink", "#")
|
| 66 |
+
lines.append(f"- Evidence: [{title}]({link})")
|
| 67 |
+
lines.append("")
|
| 68 |
+
return "\n".join(lines).strip() + "\n"
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def render_html(run_dir: Path, accepted: List[Dict]) -> str:
|
| 72 |
+
cards: List[str] = []
|
| 73 |
+
for idx, item in enumerate(accepted, start=1):
|
| 74 |
+
cid = item.get("cluster_id", "")
|
| 75 |
+
req = str(item.get("requirement", item.get("normalized_requirement", ""))).strip()
|
| 76 |
+
reason = str(item.get("reason", "")).strip()
|
| 77 |
+
count = item.get("demand_count", 0)
|
| 78 |
+
examples = item.get("examples", [])
|
| 79 |
+
evidence_html = ""
|
| 80 |
+
if examples:
|
| 81 |
+
ex = examples[0]
|
| 82 |
+
title = ex.get("title", "source post")
|
| 83 |
+
link = ex.get("permalink", "#")
|
| 84 |
+
evidence_html = f'<p class="meta">Evidence: <a href="{link}" target="_blank" rel="noreferrer">{title}</a></p>'
|
| 85 |
+
cards.append(
|
| 86 |
+
f"""
|
| 87 |
+
<article class="card">
|
| 88 |
+
<h3>{idx}. {req}</h3>
|
| 89 |
+
<p class="meta">Cluster: {cid} | Mentions: {count}</p>
|
| 90 |
+
<p>{reason}</p>
|
| 91 |
+
{evidence_html}
|
| 92 |
+
</article>
|
| 93 |
+
"""
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
stamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
|
| 97 |
+
return f"""<!doctype html>
|
| 98 |
+
<html lang="en">
|
| 99 |
+
<head>
|
| 100 |
+
<meta charset="utf-8" />
|
| 101 |
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
| 102 |
+
<title>Reddit User Requirements</title>
|
| 103 |
+
<style>
|
| 104 |
+
:root {{
|
| 105 |
+
--bg: #0b1020;
|
| 106 |
+
--panel: #121a30;
|
| 107 |
+
--text: #e8eefc;
|
| 108 |
+
--muted: #9cb0d8;
|
| 109 |
+
--line: #2b3b63;
|
| 110 |
+
--accent: #5db0ff;
|
| 111 |
+
}}
|
| 112 |
+
body {{ margin: 0; padding: 32px; background: linear-gradient(180deg, #0b1020, #151f38); color: var(--text); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }}
|
| 113 |
+
.wrap {{ max-width: 980px; margin: 0 auto; }}
|
| 114 |
+
h1 {{ margin: 0 0 8px 0; font-size: 34px; }}
|
| 115 |
+
.meta {{ color: var(--muted); font-size: 14px; }}
|
| 116 |
+
.grid {{ display: grid; grid-template-columns: 1fr; gap: 12px; margin-top: 20px; }}
|
| 117 |
+
.card {{ background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 16px; }}
|
| 118 |
+
.card h3 {{ margin: 0 0 8px 0; font-size: 20px; color: #f2f6ff; }}
|
| 119 |
+
a {{ color: var(--accent); text-decoration: none; }}
|
| 120 |
+
a:hover {{ text-decoration: underline; }}
|
| 121 |
+
</style>
|
| 122 |
+
</head>
|
| 123 |
+
<body>
|
| 124 |
+
<main class="wrap">
|
| 125 |
+
<h1>Reddit User Requirements (LLM Curated)</h1>
|
| 126 |
+
<p class="meta">Source run: {run_dir.name} | Generated: {stamp} | Accepted: {len(accepted)}</p>
|
| 127 |
+
<section class="grid">
|
| 128 |
+
{''.join(cards)}
|
| 129 |
+
</section>
|
| 130 |
+
</main>
|
| 131 |
+
</body>
|
| 132 |
+
</html>
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def main() -> None:
|
| 137 |
+
args = parse_args()
|
| 138 |
+
root = Path(__file__).resolve().parents[1]
|
| 139 |
+
base = root / "data" / "reddit_requirements"
|
| 140 |
+
run_dir = Path(args.input_dir) if args.input_dir else latest_run_dir(base)
|
| 141 |
+
accepted = load_accepted(run_dir)
|
| 142 |
+
|
| 143 |
+
out_dir = root / "pages" / "requirements"
|
| 144 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 145 |
+
md_path = out_dir / "reddit_user_requirements.md"
|
| 146 |
+
html_path = out_dir / "reddit_user_requirements.html"
|
| 147 |
+
|
| 148 |
+
md_path.write_text(render_markdown(run_dir, accepted), encoding="utf-8")
|
| 149 |
+
html_path.write_text(render_html(run_dir, accepted), encoding="utf-8")
|
| 150 |
+
|
| 151 |
+
print(f"Source: {run_dir}")
|
| 152 |
+
print(f"Accepted requirements: {len(accepted)}")
|
| 153 |
+
print(f"Markdown page: {md_path}")
|
| 154 |
+
print(f"HTML page: {html_path}")
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
if __name__ == "__main__":
|
| 158 |
+
main()
|
| 159 |
+
|
src/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Root package for local Python module execution.
|
| 2 |
+
|
src/web_user_summary/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reddit-first user demand summarizer."""
|
| 2 |
+
|
src/web_user_summary/cli.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import os
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import List
|
| 7 |
+
|
| 8 |
+
from .demand_extractor import build_meta_summary, cluster_demands, extract_demand_candidates
|
| 9 |
+
from .reddit_client import RedditClient
|
| 10 |
+
from .reporting import (
|
| 11 |
+
build_demandsolution_seed,
|
| 12 |
+
serialize_candidates,
|
| 13 |
+
serialize_clusters,
|
| 14 |
+
serialize_posts,
|
| 15 |
+
timestamped_output_dir,
|
| 16 |
+
write_json,
|
| 17 |
+
write_jsonl,
|
| 18 |
+
write_markdown_report,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
DEFAULT_SUBREDDITS = "SaaS,startups,SideProject,Entrepreneur,smallbusiness,productivity,webdev"
|
| 22 |
+
DEFAULT_USER_AGENT = "web-user-summary/0.1 (contact: jacksuyu@gmail.com)"
|
| 23 |
+
DEFAULT_SEARCH_QUERIES = "need app,looking for tool,wish there was,how do i automate,any software for,struggling with"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def parse_args() -> argparse.Namespace:
|
| 27 |
+
parser = argparse.ArgumentParser(description="Collect and summarize user demand from Reddit.")
|
| 28 |
+
parser.add_argument("--subreddits", default=DEFAULT_SUBREDDITS, help="Comma-separated subreddit list.")
|
| 29 |
+
parser.add_argument("--sort", default="new", choices=["new", "hot", "top"], help="Reddit listing type.")
|
| 30 |
+
parser.add_argument("--per-subreddit", type=int, default=80, help="Maximum posts fetched per subreddit.")
|
| 31 |
+
parser.add_argument("--hours", type=int, default=168, help="Only include posts newer than this many hours.")
|
| 32 |
+
parser.add_argument("--min-score", type=int, default=2, help="Minimum demand confidence score.")
|
| 33 |
+
parser.add_argument("--similarity-threshold", type=float, default=0.62, help="Fuzzy grouping threshold (0-1).")
|
| 34 |
+
parser.add_argument("--output-dir", default="data/reddit_requirements", help="Base output directory.")
|
| 35 |
+
parser.add_argument("--user-agent", default=os.getenv("REDDIT_USER_AGENT", DEFAULT_USER_AGENT), help="HTTP User-Agent.")
|
| 36 |
+
parser.add_argument("--search-queries", default=DEFAULT_SEARCH_QUERIES, help="Comma-separated query terms for /search.json.")
|
| 37 |
+
parser.add_argument("--search-per-query", type=int, default=20, help="Posts fetched per query per subreddit.")
|
| 38 |
+
parser.add_argument(
|
| 39 |
+
"--include-self-promo",
|
| 40 |
+
action="store_true",
|
| 41 |
+
help="Include self-promotional founder posts (default excludes them).",
|
| 42 |
+
)
|
| 43 |
+
return parser.parse_args()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def parse_subreddits(raw: str) -> List[str]:
|
| 47 |
+
return [s.strip() for s in raw.split(",") if s.strip()]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def parse_csv_terms(raw: str) -> List[str]:
|
| 51 |
+
return [s.strip() for s in raw.split(",") if s.strip()]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def main() -> None:
|
| 55 |
+
args = parse_args()
|
| 56 |
+
subreddits = parse_subreddits(args.subreddits)
|
| 57 |
+
if not subreddits:
|
| 58 |
+
raise ValueError("At least one subreddit is required.")
|
| 59 |
+
|
| 60 |
+
client = RedditClient(user_agent=args.user_agent)
|
| 61 |
+
search_queries = parse_csv_terms(args.search_queries)
|
| 62 |
+
all_posts = []
|
| 63 |
+
for subreddit in subreddits:
|
| 64 |
+
posts = client.fetch_subreddit_posts(subreddit=subreddit, sort=args.sort, limit=args.per_subreddit)
|
| 65 |
+
all_posts.extend(posts)
|
| 66 |
+
print(f"Fetched {len(posts):>3} posts from r/{subreddit}")
|
| 67 |
+
for query in search_queries:
|
| 68 |
+
q_posts = client.fetch_subreddit_search(
|
| 69 |
+
subreddit=subreddit, query=query, sort=args.sort, limit=args.search_per_query
|
| 70 |
+
)
|
| 71 |
+
all_posts.extend(q_posts)
|
| 72 |
+
print(f" + search '{query}': {len(q_posts):>3} posts")
|
| 73 |
+
|
| 74 |
+
# Deduplicate by post ID
|
| 75 |
+
dedup = {}
|
| 76 |
+
for post in all_posts:
|
| 77 |
+
dedup[post.id] = post
|
| 78 |
+
posts = list(dedup.values())
|
| 79 |
+
|
| 80 |
+
candidates = extract_demand_candidates(
|
| 81 |
+
posts=posts,
|
| 82 |
+
max_age_hours=args.hours,
|
| 83 |
+
min_score=args.min_score,
|
| 84 |
+
exclude_self_promo=not args.include_self_promo,
|
| 85 |
+
)
|
| 86 |
+
clusters = cluster_demands(candidates=candidates, threshold=args.similarity_threshold)
|
| 87 |
+
meta = build_meta_summary(posts=posts, candidates=candidates, clusters=clusters)
|
| 88 |
+
|
| 89 |
+
out_dir = timestamped_output_dir(Path(args.output_dir))
|
| 90 |
+
write_jsonl(out_dir / "raw_posts.jsonl", serialize_posts(posts))
|
| 91 |
+
write_jsonl(out_dir / "demand_candidates.jsonl", serialize_candidates(candidates))
|
| 92 |
+
write_json(
|
| 93 |
+
out_dir / "demand_clusters.json",
|
| 94 |
+
{
|
| 95 |
+
"meta": meta,
|
| 96 |
+
"clusters": serialize_clusters(clusters),
|
| 97 |
+
},
|
| 98 |
+
)
|
| 99 |
+
write_json(out_dir / "demandsolution_seed_ideas.json", build_demandsolution_seed(clusters))
|
| 100 |
+
write_markdown_report(out_dir / "report.md", meta=meta, clusters=clusters)
|
| 101 |
+
|
| 102 |
+
print("")
|
| 103 |
+
print(f"Saved outputs to: {out_dir}")
|
| 104 |
+
print(f"Total posts: {meta['total_posts']}")
|
| 105 |
+
print(f"Demand candidates: {meta['total_candidates']}")
|
| 106 |
+
print(f"Demand clusters: {meta['total_clusters']}")
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
if __name__ == "__main__":
|
| 110 |
+
main()
|
src/web_user_summary/demand_extractor.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
import time
|
| 5 |
+
from collections import Counter, defaultdict
|
| 6 |
+
from difflib import SequenceMatcher
|
| 7 |
+
from typing import Dict, List, Sequence, Tuple
|
| 8 |
+
|
| 9 |
+
from .models import DemandCandidate, DemandCluster, RedditPost
|
| 10 |
+
|
| 11 |
+
DEMAND_PATTERNS = [
|
| 12 |
+
r"\bi need\b",
|
| 13 |
+
r"\bi wish\b",
|
| 14 |
+
r"\blooking for\b",
|
| 15 |
+
r"\bdoes anyone know\b",
|
| 16 |
+
r"\bany app\b",
|
| 17 |
+
r"\bany tool\b",
|
| 18 |
+
r"\bhow do i\b",
|
| 19 |
+
r"\bstruggling with\b",
|
| 20 |
+
r"\bproblem with\b",
|
| 21 |
+
r"\bfrustrat(?:e|ed|ing)\b",
|
| 22 |
+
r"\bwant (?:an|a) (?:app|tool|way)\b",
|
| 23 |
+
r"\bthere should be\b",
|
| 24 |
+
]
|
| 25 |
+
|
| 26 |
+
ASK_INTENT_PATTERNS = [
|
| 27 |
+
r"\bi need\b",
|
| 28 |
+
r"\blooking for\b",
|
| 29 |
+
r"\bdoes anyone know\b",
|
| 30 |
+
r"\bneed advice\b",
|
| 31 |
+
r"\bany recommendation\b",
|
| 32 |
+
r"\bany app\b",
|
| 33 |
+
r"\bany tool\b",
|
| 34 |
+
r"\bany software\b",
|
| 35 |
+
r"\bis there (?:any|a)\b",
|
| 36 |
+
r"\bhow do i\b",
|
| 37 |
+
r"\bcan anyone\b",
|
| 38 |
+
]
|
| 39 |
+
|
| 40 |
+
PRODUCT_INTENT_PATTERNS = [
|
| 41 |
+
r"\bapp\b",
|
| 42 |
+
r"\btool\b",
|
| 43 |
+
r"\bsoftware\b",
|
| 44 |
+
r"\bplatform\b",
|
| 45 |
+
r"\bautomation\b",
|
| 46 |
+
r"\bautomate\b",
|
| 47 |
+
r"\bworkflow\b",
|
| 48 |
+
r"\bintegration\b",
|
| 49 |
+
r"\bplugin\b",
|
| 50 |
+
r"\bdashboard\b",
|
| 51 |
+
r"\bextension\b",
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
EXCLUDE_PATTERNS = [
|
| 55 |
+
r"\bi will not promote\b",
|
| 56 |
+
r"\blooking for (?:cofounder|co-founder|founder|partner|job)\b",
|
| 57 |
+
r"\blooking for feedback\b",
|
| 58 |
+
r"\broast my\b",
|
| 59 |
+
r"\brate my\b",
|
| 60 |
+
]
|
| 61 |
+
|
| 62 |
+
SELF_PROMO_PATTERNS = [
|
| 63 |
+
r"\bi built\b",
|
| 64 |
+
r"\bi'm building\b",
|
| 65 |
+
r"\bwe built\b",
|
| 66 |
+
r"\blaunched\b",
|
| 67 |
+
r"\blaunching\b",
|
| 68 |
+
r"\bmvp\b",
|
| 69 |
+
r"\bwaitlist\b",
|
| 70 |
+
r"\bcofounder\b",
|
| 71 |
+
r"\bco-founder\b",
|
| 72 |
+
]
|
| 73 |
+
|
| 74 |
+
URGENCY_PATTERNS = [
|
| 75 |
+
r"\burgent\b",
|
| 76 |
+
r"\basap\b",
|
| 77 |
+
r"\bright now\b",
|
| 78 |
+
r"\bimmediately\b",
|
| 79 |
+
r"\bdeadline\b",
|
| 80 |
+
r"\bblocked\b",
|
| 81 |
+
]
|
| 82 |
+
|
| 83 |
+
STOP_WORDS = {
|
| 84 |
+
"a",
|
| 85 |
+
"an",
|
| 86 |
+
"and",
|
| 87 |
+
"are",
|
| 88 |
+
"as",
|
| 89 |
+
"at",
|
| 90 |
+
"be",
|
| 91 |
+
"by",
|
| 92 |
+
"for",
|
| 93 |
+
"from",
|
| 94 |
+
"how",
|
| 95 |
+
"i",
|
| 96 |
+
"if",
|
| 97 |
+
"in",
|
| 98 |
+
"is",
|
| 99 |
+
"it",
|
| 100 |
+
"my",
|
| 101 |
+
"of",
|
| 102 |
+
"on",
|
| 103 |
+
"or",
|
| 104 |
+
"that",
|
| 105 |
+
"the",
|
| 106 |
+
"this",
|
| 107 |
+
"to",
|
| 108 |
+
"we",
|
| 109 |
+
"what",
|
| 110 |
+
"with",
|
| 111 |
+
"you",
|
| 112 |
+
"your",
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _compact_text(text: str) -> str:
|
| 117 |
+
text = re.sub(r"https?://\S+", " ", text)
|
| 118 |
+
text = re.sub(r"\s+", " ", text).strip()
|
| 119 |
+
return text
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _split_sentences(text: str) -> List[str]:
|
| 123 |
+
clean = _compact_text(text)
|
| 124 |
+
if not clean:
|
| 125 |
+
return []
|
| 126 |
+
return [s.strip() for s in re.split(r"(?<=[.!?])\s+", clean) if s.strip()]
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _normalize_phrase(text: str) -> str:
|
| 130 |
+
lower = text.lower()
|
| 131 |
+
lower = re.sub(r"[^a-z0-9\s]", " ", lower)
|
| 132 |
+
tokens = [t for t in lower.split() if len(t) > 2 and t not in STOP_WORDS]
|
| 133 |
+
# Keep a deterministic set-style view to improve fuzzy grouping across paraphrases.
|
| 134 |
+
unique_tokens = sorted(set(tokens))
|
| 135 |
+
return " ".join(unique_tokens[:24]).strip()
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _keyword_tokens(text: str, max_tokens: int = 8) -> List[str]:
|
| 139 |
+
norm = _normalize_phrase(text)
|
| 140 |
+
if not norm:
|
| 141 |
+
return []
|
| 142 |
+
counts = Counter(norm.split())
|
| 143 |
+
return [w for w, _ in counts.most_common(max_tokens)]
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _pattern_hits(text: str, patterns: Sequence[str]) -> int:
|
| 147 |
+
return sum(1 for pattern in patterns if re.search(pattern, text, flags=re.IGNORECASE))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _confidence_score(title: str, body: str) -> int:
|
| 151 |
+
combined = f"{title} {body}".strip()
|
| 152 |
+
score = _pattern_hits(combined, DEMAND_PATTERNS)
|
| 153 |
+
if "?" in combined:
|
| 154 |
+
score += 1
|
| 155 |
+
if re.search(r"\b(i|we)\b", combined, flags=re.IGNORECASE) and re.search(
|
| 156 |
+
r"\b(need|wish|want|looking)\b", combined, flags=re.IGNORECASE
|
| 157 |
+
):
|
| 158 |
+
score += 1
|
| 159 |
+
if len(combined) > 220:
|
| 160 |
+
score += 1
|
| 161 |
+
return score
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def _urgency_score(title: str, body: str) -> int:
|
| 165 |
+
return _pattern_hits(f"{title} {body}", URGENCY_PATTERNS)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _extract_best_demand_sentence(title: str, body: str) -> str:
|
| 169 |
+
sentences = _split_sentences(f"{title}. {body}".strip())
|
| 170 |
+
if not sentences:
|
| 171 |
+
return _compact_text(title)
|
| 172 |
+
for sentence in sentences:
|
| 173 |
+
if _pattern_hits(sentence, DEMAND_PATTERNS) > 0:
|
| 174 |
+
return sentence
|
| 175 |
+
return sentences[0]
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def _shorten(text: str, max_len: int = 170) -> str:
|
| 179 |
+
txt = _compact_text(text)
|
| 180 |
+
if len(txt) <= max_len:
|
| 181 |
+
return txt
|
| 182 |
+
return txt[: max_len - 3].rstrip() + "..."
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def extract_demand_candidates(
|
| 186 |
+
posts: Sequence[RedditPost], max_age_hours: int, min_score: int, exclude_self_promo: bool = True
|
| 187 |
+
) -> List[DemandCandidate]:
|
| 188 |
+
now = time.time()
|
| 189 |
+
cutoff = now - max_age_hours * 3600
|
| 190 |
+
out: List[DemandCandidate] = []
|
| 191 |
+
|
| 192 |
+
for post in posts:
|
| 193 |
+
if post.created_utc < cutoff:
|
| 194 |
+
continue
|
| 195 |
+
if _pattern_hits(f"{post.title} {post.selftext}", EXCLUDE_PATTERNS) > 0:
|
| 196 |
+
continue
|
| 197 |
+
if exclude_self_promo and _pattern_hits(f"{post.title} {post.selftext}", SELF_PROMO_PATTERNS) > 0:
|
| 198 |
+
continue
|
| 199 |
+
confidence = _confidence_score(post.title, post.selftext)
|
| 200 |
+
if confidence < min_score:
|
| 201 |
+
continue
|
| 202 |
+
|
| 203 |
+
demand_text = _extract_best_demand_sentence(post.title, post.selftext)
|
| 204 |
+
if _pattern_hits(f"{post.title} {demand_text}", ASK_INTENT_PATTERNS) == 0:
|
| 205 |
+
continue
|
| 206 |
+
if _pattern_hits(f"{post.title} {demand_text}", PRODUCT_INTENT_PATTERNS) == 0:
|
| 207 |
+
continue
|
| 208 |
+
normalized = _normalize_phrase(demand_text or post.title)
|
| 209 |
+
if not normalized:
|
| 210 |
+
continue
|
| 211 |
+
|
| 212 |
+
candidate = DemandCandidate(
|
| 213 |
+
post_id=post.id,
|
| 214 |
+
subreddit=post.subreddit,
|
| 215 |
+
created_utc=post.created_utc,
|
| 216 |
+
title=post.title,
|
| 217 |
+
demand_text=_shorten(demand_text),
|
| 218 |
+
normalized_text=normalized,
|
| 219 |
+
confidence_score=confidence,
|
| 220 |
+
urgency_score=_urgency_score(post.title, post.selftext),
|
| 221 |
+
keyword_tokens=_keyword_tokens(demand_text),
|
| 222 |
+
permalink=post.permalink,
|
| 223 |
+
url=post.url,
|
| 224 |
+
)
|
| 225 |
+
out.append(candidate)
|
| 226 |
+
|
| 227 |
+
return out
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def _similarity(a: str, b: str) -> float:
|
| 231 |
+
seq = SequenceMatcher(a=a, b=b).ratio()
|
| 232 |
+
a_set = set(a.split())
|
| 233 |
+
b_set = set(b.split())
|
| 234 |
+
if not a_set or not b_set:
|
| 235 |
+
return seq
|
| 236 |
+
inter = len(a_set & b_set)
|
| 237 |
+
union = len(a_set | b_set)
|
| 238 |
+
jaccard = inter / union if union else 0.0
|
| 239 |
+
return max(seq, jaccard)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def cluster_demands(candidates: Sequence[DemandCandidate], threshold: float = 0.72) -> List[DemandCluster]:
|
| 243 |
+
clusters: List[DemandCluster] = []
|
| 244 |
+
|
| 245 |
+
for candidate in sorted(candidates, key=lambda x: x.confidence_score, reverse=True):
|
| 246 |
+
best_idx = -1
|
| 247 |
+
best_sim = 0.0
|
| 248 |
+
for idx, cluster in enumerate(clusters):
|
| 249 |
+
sim = _similarity(candidate.normalized_text, cluster.normalized_anchor)
|
| 250 |
+
if sim > best_sim:
|
| 251 |
+
best_sim = sim
|
| 252 |
+
best_idx = idx
|
| 253 |
+
|
| 254 |
+
if best_idx >= 0 and best_sim >= threshold:
|
| 255 |
+
cluster = clusters[best_idx]
|
| 256 |
+
cluster.demand_count += 1
|
| 257 |
+
cluster.confidence_avg += candidate.confidence_score
|
| 258 |
+
cluster.urgency_avg += candidate.urgency_score
|
| 259 |
+
cluster.examples.append(
|
| 260 |
+
{
|
| 261 |
+
"title": candidate.title,
|
| 262 |
+
"demand_text": candidate.demand_text,
|
| 263 |
+
"subreddit": candidate.subreddit,
|
| 264 |
+
"permalink": candidate.permalink,
|
| 265 |
+
"confidence_score": candidate.confidence_score,
|
| 266 |
+
"urgency_score": candidate.urgency_score,
|
| 267 |
+
}
|
| 268 |
+
)
|
| 269 |
+
cluster.examples = cluster.examples[:5]
|
| 270 |
+
cluster.subreddits.append(candidate.subreddit)
|
| 271 |
+
cluster.keywords.extend(candidate.keyword_tokens)
|
| 272 |
+
else:
|
| 273 |
+
cluster = DemandCluster(
|
| 274 |
+
cluster_id=f"demand_{len(clusters) + 1:03d}",
|
| 275 |
+
summary_demand=candidate.demand_text,
|
| 276 |
+
normalized_anchor=candidate.normalized_text,
|
| 277 |
+
demand_count=1,
|
| 278 |
+
confidence_avg=float(candidate.confidence_score),
|
| 279 |
+
urgency_avg=float(candidate.urgency_score),
|
| 280 |
+
keywords=list(candidate.keyword_tokens),
|
| 281 |
+
subreddits=[candidate.subreddit],
|
| 282 |
+
examples=[
|
| 283 |
+
{
|
| 284 |
+
"title": candidate.title,
|
| 285 |
+
"demand_text": candidate.demand_text,
|
| 286 |
+
"subreddit": candidate.subreddit,
|
| 287 |
+
"permalink": candidate.permalink,
|
| 288 |
+
"confidence_score": candidate.confidence_score,
|
| 289 |
+
"urgency_score": candidate.urgency_score,
|
| 290 |
+
}
|
| 291 |
+
],
|
| 292 |
+
)
|
| 293 |
+
clusters.append(cluster)
|
| 294 |
+
|
| 295 |
+
for cluster in clusters:
|
| 296 |
+
cluster.confidence_avg = round(cluster.confidence_avg / max(cluster.demand_count, 1), 2)
|
| 297 |
+
cluster.urgency_avg = round(cluster.urgency_avg / max(cluster.demand_count, 1), 2)
|
| 298 |
+
cluster.subreddits = sorted(set(cluster.subreddits))
|
| 299 |
+
keyword_counts = Counter(cluster.keywords)
|
| 300 |
+
cluster.keywords = [word for word, _ in keyword_counts.most_common(8)]
|
| 301 |
+
|
| 302 |
+
clusters.sort(key=lambda c: (c.demand_count, c.confidence_avg, c.urgency_avg), reverse=True)
|
| 303 |
+
return clusters
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def build_meta_summary(posts: Sequence[RedditPost], candidates: Sequence[DemandCandidate], clusters: Sequence[DemandCluster]) -> Dict:
|
| 307 |
+
sub_counts: Dict[str, int] = defaultdict(int)
|
| 308 |
+
for post in posts:
|
| 309 |
+
sub_counts[post.subreddit] += 1
|
| 310 |
+
|
| 311 |
+
return {
|
| 312 |
+
"total_posts": len(posts),
|
| 313 |
+
"total_candidates": len(candidates),
|
| 314 |
+
"total_clusters": len(clusters),
|
| 315 |
+
"subreddit_post_counts": dict(sorted(sub_counts.items(), key=lambda x: x[1], reverse=True)),
|
| 316 |
+
}
|
src/web_user_summary/llm_requirement_filter.py
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Dict, List, Tuple
|
| 9 |
+
|
| 10 |
+
import requests
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
SYSTEM_PROMPT = """You are a strict product requirement triage reviewer.
|
| 14 |
+
|
| 15 |
+
Goal:
|
| 16 |
+
- Keep ONLY items that are clearly user requirements for a product/software capability.
|
| 17 |
+
|
| 18 |
+
Accept ONLY when:
|
| 19 |
+
- It expresses a concrete need/problem and implies a software/tool/app/workflow solution.
|
| 20 |
+
- It is actionable enough for a product team to build against.
|
| 21 |
+
|
| 22 |
+
Reject when:
|
| 23 |
+
- Self-promotion, launch announcement, or "I built X".
|
| 24 |
+
- Hiring/cofounder/job-seeking.
|
| 25 |
+
- Generic discussion, opinion, storytelling, motivation, or reflection.
|
| 26 |
+
- Feedback/roast requests without a real user requirement.
|
| 27 |
+
- Too vague to infer a buildable requirement.
|
| 28 |
+
|
| 29 |
+
Return JSON only.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def parse_args() -> argparse.Namespace:
|
| 34 |
+
parser = argparse.ArgumentParser(description="LLM-filter demand clusters to clear user requirements.")
|
| 35 |
+
parser.add_argument("--input-dir", default="", help="Directory containing demand_clusters.json (default: latest in data/).")
|
| 36 |
+
parser.add_argument("--batch-size", type=int, default=15)
|
| 37 |
+
parser.add_argument("--provider", choices=["auto", "ollama", "openai"], default="auto")
|
| 38 |
+
parser.add_argument("--ollama-model", default="qwen2.5:0.5b")
|
| 39 |
+
parser.add_argument("--openai-model", default=os.getenv("OPENAI_MODEL", "gpt-4o-mini"))
|
| 40 |
+
return parser.parse_args()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def latest_data_dir(base: Path) -> Path:
|
| 44 |
+
dirs = [p for p in base.iterdir() if p.is_dir() and re.match(r"^\d{8}_\d{6}_utc$", p.name)]
|
| 45 |
+
if not dirs:
|
| 46 |
+
raise FileNotFoundError(f"No run directories found under {base}")
|
| 47 |
+
return sorted(dirs, key=lambda p: p.name)[-1]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def parse_first_json(text: str) -> Dict:
|
| 51 |
+
text = text.strip()
|
| 52 |
+
if not text:
|
| 53 |
+
raise ValueError("LLM returned empty content")
|
| 54 |
+
try:
|
| 55 |
+
return json.loads(text)
|
| 56 |
+
except Exception:
|
| 57 |
+
pass
|
| 58 |
+
|
| 59 |
+
match = re.search(r"\{.*\}", text, flags=re.DOTALL)
|
| 60 |
+
if not match:
|
| 61 |
+
raise ValueError(f"Could not parse JSON from LLM output: {text[:200]}")
|
| 62 |
+
return json.loads(match.group(0))
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def build_user_prompt(items: List[Dict]) -> str:
|
| 66 |
+
payload = {"items": items}
|
| 67 |
+
return json.dumps(payload, ensure_ascii=False)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def call_ollama_single(model: str, item: Dict) -> Dict:
|
| 71 |
+
url = "http://127.0.0.1:11434/api/chat"
|
| 72 |
+
system_prompt = (
|
| 73 |
+
SYSTEM_PROMPT
|
| 74 |
+
+ "\nFor this request, return ONE JSON object with keys:\n"
|
| 75 |
+
+ "cluster_id (string), accept (boolean), normalized_requirement (string), reason (string), confidence (0..1).\n"
|
| 76 |
+
+ "No extra keys."
|
| 77 |
+
)
|
| 78 |
+
body = {
|
| 79 |
+
"model": model,
|
| 80 |
+
"stream": False,
|
| 81 |
+
"format": "json",
|
| 82 |
+
"options": {"temperature": 0.0, "num_predict": 400},
|
| 83 |
+
"messages": [
|
| 84 |
+
{"role": "system", "content": system_prompt},
|
| 85 |
+
{"role": "user", "content": json.dumps(item, ensure_ascii=False)},
|
| 86 |
+
],
|
| 87 |
+
}
|
| 88 |
+
response = requests.post(url, json=body, timeout=90)
|
| 89 |
+
response.raise_for_status()
|
| 90 |
+
payload = response.json()
|
| 91 |
+
content = payload.get("message", {}).get("content", "")
|
| 92 |
+
return parse_first_json(content)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def call_openai(model: str, items: List[Dict]) -> Dict:
|
| 96 |
+
api_key = os.getenv("OPENAI_API_KEY")
|
| 97 |
+
if not api_key:
|
| 98 |
+
raise RuntimeError("OPENAI_API_KEY is not set")
|
| 99 |
+
|
| 100 |
+
url = "https://api.openai.com/v1/chat/completions"
|
| 101 |
+
body = {
|
| 102 |
+
"model": model,
|
| 103 |
+
"temperature": 0,
|
| 104 |
+
"response_format": {"type": "json_object"},
|
| 105 |
+
"messages": [
|
| 106 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 107 |
+
{"role": "user", "content": build_user_prompt(items)},
|
| 108 |
+
],
|
| 109 |
+
}
|
| 110 |
+
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
|
| 111 |
+
response = requests.post(url, headers=headers, json=body, timeout=180)
|
| 112 |
+
response.raise_for_status()
|
| 113 |
+
payload = response.json()
|
| 114 |
+
content = payload["choices"][0]["message"]["content"]
|
| 115 |
+
return parse_first_json(content)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def choose_provider(requested: str) -> str:
|
| 119 |
+
if requested in {"ollama", "openai"}:
|
| 120 |
+
return requested
|
| 121 |
+
return "openai" if os.getenv("OPENAI_API_KEY") else "ollama"
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def llm_classify_all(clusters: List[Dict], provider: str, model: str, batch_size: int) -> List[Dict]:
|
| 125 |
+
results: List[Dict] = []
|
| 126 |
+
if provider == "openai":
|
| 127 |
+
for i in range(0, len(clusters), batch_size):
|
| 128 |
+
batch = clusters[i : i + batch_size]
|
| 129 |
+
items = [
|
| 130 |
+
{
|
| 131 |
+
"cluster_id": c.get("cluster_id"),
|
| 132 |
+
"summary_demand": c.get("summary_demand", ""),
|
| 133 |
+
"keywords": c.get("keywords", []),
|
| 134 |
+
"mention_count": c.get("demand_count", 0),
|
| 135 |
+
"examples": c.get("examples", [])[:2],
|
| 136 |
+
}
|
| 137 |
+
for c in batch
|
| 138 |
+
]
|
| 139 |
+
payload = call_openai(model=model, items=items)
|
| 140 |
+
batch_results = payload.get("results", payload.get("items", []))
|
| 141 |
+
if not isinstance(batch_results, list):
|
| 142 |
+
raise RuntimeError(f"Unexpected LLM payload: {payload}")
|
| 143 |
+
results.extend(batch_results)
|
| 144 |
+
else:
|
| 145 |
+
total = len(clusters)
|
| 146 |
+
for idx, c in enumerate(clusters, start=1):
|
| 147 |
+
item = {
|
| 148 |
+
"cluster_id": c.get("cluster_id"),
|
| 149 |
+
"summary_demand": c.get("summary_demand", ""),
|
| 150 |
+
"keywords": c.get("keywords", []),
|
| 151 |
+
"mention_count": c.get("demand_count", 0),
|
| 152 |
+
"examples": c.get("examples", [])[:2],
|
| 153 |
+
}
|
| 154 |
+
print(f"LLM reviewing {idx}/{total} - {item['cluster_id']}", flush=True)
|
| 155 |
+
results.append(call_ollama_single(model=model, item=item))
|
| 156 |
+
return results
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def render_review_md(path: Path, accepted: List[Dict], rejected: List[Dict]) -> None:
|
| 160 |
+
lines: List[str] = []
|
| 161 |
+
lines.append("# LLM Requirement Review")
|
| 162 |
+
lines.append("")
|
| 163 |
+
lines.append(f"- Accepted: {len(accepted)}")
|
| 164 |
+
lines.append(f"- Rejected: {len(rejected)}")
|
| 165 |
+
lines.append("")
|
| 166 |
+
lines.append("## Accepted")
|
| 167 |
+
for idx, item in enumerate(accepted, start=1):
|
| 168 |
+
lines.append(f"{idx}. `{item['cluster_id']}` - {item.get('normalized_requirement', '').strip()}")
|
| 169 |
+
lines.append(f" - reason: {item.get('reason', '')}")
|
| 170 |
+
lines.append(f" - confidence: {item.get('confidence', 0)}")
|
| 171 |
+
lines.append("")
|
| 172 |
+
lines.append("## Rejected")
|
| 173 |
+
for idx, item in enumerate(rejected, start=1):
|
| 174 |
+
lines.append(f"{idx}. `{item['cluster_id']}` - {item.get('reason', '')}")
|
| 175 |
+
lines.append(f" - confidence: {item.get('confidence', 0)}")
|
| 176 |
+
path.write_text("\n".join(lines).strip() + "\n", encoding="utf-8")
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def normalize_result(result: Dict) -> Dict:
|
| 180 |
+
accept_raw = result.get("accept", False)
|
| 181 |
+
if isinstance(accept_raw, bool):
|
| 182 |
+
accept = accept_raw
|
| 183 |
+
elif isinstance(accept_raw, (int, float)):
|
| 184 |
+
accept = bool(accept_raw)
|
| 185 |
+
else:
|
| 186 |
+
accept = str(accept_raw).strip().lower() in {"true", "yes", "accept", "accepted", "1"}
|
| 187 |
+
|
| 188 |
+
conf_raw = result.get("confidence", result.get("confidence_score", 0.0))
|
| 189 |
+
try:
|
| 190 |
+
confidence = float(conf_raw)
|
| 191 |
+
except Exception:
|
| 192 |
+
confidence = 0.0
|
| 193 |
+
if confidence > 1.0:
|
| 194 |
+
confidence = min(1.0, confidence / 10.0)
|
| 195 |
+
|
| 196 |
+
return {
|
| 197 |
+
"cluster_id": str(result.get("cluster_id", "")).strip(),
|
| 198 |
+
"accept": accept,
|
| 199 |
+
"normalized_requirement": str(result.get("normalized_requirement", "")).strip(),
|
| 200 |
+
"reason": str(result.get("reason", "")).strip(),
|
| 201 |
+
"confidence": confidence,
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def main() -> None:
|
| 206 |
+
args = parse_args()
|
| 207 |
+
root = Path(__file__).resolve().parents[2]
|
| 208 |
+
base_data = root / "data" / "reddit_requirements"
|
| 209 |
+
input_dir = Path(args.input_dir) if args.input_dir else latest_data_dir(base_data)
|
| 210 |
+
clusters_path = input_dir / "demand_clusters.json"
|
| 211 |
+
|
| 212 |
+
if not clusters_path.exists():
|
| 213 |
+
raise FileNotFoundError(f"Missing {clusters_path}")
|
| 214 |
+
|
| 215 |
+
obj = json.loads(clusters_path.read_text(encoding="utf-8"))
|
| 216 |
+
clusters = obj.get("clusters", [])
|
| 217 |
+
if not isinstance(clusters, list) or not clusters:
|
| 218 |
+
raise RuntimeError(f"No clusters found in {clusters_path}")
|
| 219 |
+
|
| 220 |
+
provider = choose_provider(args.provider)
|
| 221 |
+
model = args.openai_model if provider == "openai" else args.ollama_model
|
| 222 |
+
|
| 223 |
+
raw_results = llm_classify_all(clusters=clusters, provider=provider, model=model, batch_size=args.batch_size)
|
| 224 |
+
cleaned = [normalize_result(r) for r in raw_results if r.get("cluster_id")]
|
| 225 |
+
|
| 226 |
+
# Ensure one output row per cluster, default to reject if missing.
|
| 227 |
+
by_id = {r["cluster_id"]: r for r in cleaned}
|
| 228 |
+
final_results: List[Dict] = []
|
| 229 |
+
for c in clusters:
|
| 230 |
+
cid = str(c.get("cluster_id", "")).strip()
|
| 231 |
+
if cid in by_id:
|
| 232 |
+
final_results.append(by_id[cid])
|
| 233 |
+
else:
|
| 234 |
+
final_results.append(
|
| 235 |
+
{
|
| 236 |
+
"cluster_id": cid,
|
| 237 |
+
"accept": False,
|
| 238 |
+
"normalized_requirement": "",
|
| 239 |
+
"reason": "No classifier output for this cluster",
|
| 240 |
+
"confidence": 0.0,
|
| 241 |
+
}
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
cluster_lookup = {c.get("cluster_id"): c for c in clusters}
|
| 245 |
+
accepted = [r for r in final_results if r["accept"]]
|
| 246 |
+
rejected = [r for r in final_results if not r["accept"]]
|
| 247 |
+
|
| 248 |
+
accepted_enriched = []
|
| 249 |
+
for r in accepted:
|
| 250 |
+
c = cluster_lookup.get(r["cluster_id"], {})
|
| 251 |
+
item = dict(r)
|
| 252 |
+
item["demand_count"] = c.get("demand_count", 0)
|
| 253 |
+
item["summary_demand"] = c.get("summary_demand", "")
|
| 254 |
+
item["keywords"] = c.get("keywords", [])
|
| 255 |
+
item["examples"] = c.get("examples", [])[:3]
|
| 256 |
+
accepted_enriched.append(item)
|
| 257 |
+
|
| 258 |
+
review_path = input_dir / "llm_requirement_review.json"
|
| 259 |
+
accepted_path = input_dir / "llm_requirement_accepted.json"
|
| 260 |
+
report_path = input_dir / "llm_requirement_review.md"
|
| 261 |
+
|
| 262 |
+
review_payload = {
|
| 263 |
+
"provider": provider,
|
| 264 |
+
"model": model,
|
| 265 |
+
"input_dir": str(input_dir),
|
| 266 |
+
"total_clusters": len(clusters),
|
| 267 |
+
"accepted_count": len(accepted),
|
| 268 |
+
"rejected_count": len(rejected),
|
| 269 |
+
"results": final_results,
|
| 270 |
+
}
|
| 271 |
+
review_path.write_text(json.dumps(review_payload, indent=2, ensure_ascii=False), encoding="utf-8")
|
| 272 |
+
accepted_path.write_text(json.dumps({"accepted": accepted_enriched}, indent=2, ensure_ascii=False), encoding="utf-8")
|
| 273 |
+
render_review_md(report_path, accepted=accepted, rejected=rejected)
|
| 274 |
+
|
| 275 |
+
print(f"Input directory: {input_dir}")
|
| 276 |
+
print(f"Provider/model: {provider}/{model}")
|
| 277 |
+
print(f"Accepted: {len(accepted)} / {len(clusters)}")
|
| 278 |
+
print("")
|
| 279 |
+
print("Accepted requirements:")
|
| 280 |
+
for idx, item in enumerate(accepted_enriched, start=1):
|
| 281 |
+
print(f"{idx:>2}. [{item['cluster_id']}] {item['normalized_requirement']}")
|
| 282 |
+
print(f" mentions={item['demand_count']} confidence={item['confidence']:.2f}")
|
| 283 |
+
if item.get("reason"):
|
| 284 |
+
print(f" reason: {item['reason']}")
|
| 285 |
+
|
| 286 |
+
print("")
|
| 287 |
+
print(f"Saved review: {review_path}")
|
| 288 |
+
print(f"Saved accepted: {accepted_path}")
|
| 289 |
+
print(f"Saved report: {report_path}")
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
if __name__ == "__main__":
|
| 293 |
+
main()
|
src/web_user_summary/models.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import asdict, dataclass, field
|
| 4 |
+
from typing import Dict, List
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@dataclass
|
| 8 |
+
class RedditPost:
|
| 9 |
+
id: str
|
| 10 |
+
subreddit: str
|
| 11 |
+
title: str
|
| 12 |
+
selftext: str
|
| 13 |
+
author: str
|
| 14 |
+
created_utc: float
|
| 15 |
+
score: int
|
| 16 |
+
num_comments: int
|
| 17 |
+
upvote_ratio: float
|
| 18 |
+
permalink: str
|
| 19 |
+
url: str
|
| 20 |
+
sort_source: str
|
| 21 |
+
|
| 22 |
+
def to_dict(self) -> Dict:
|
| 23 |
+
return asdict(self)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass
|
| 27 |
+
class DemandCandidate:
|
| 28 |
+
post_id: str
|
| 29 |
+
subreddit: str
|
| 30 |
+
created_utc: float
|
| 31 |
+
title: str
|
| 32 |
+
demand_text: str
|
| 33 |
+
normalized_text: str
|
| 34 |
+
confidence_score: int
|
| 35 |
+
urgency_score: int
|
| 36 |
+
keyword_tokens: List[str]
|
| 37 |
+
permalink: str
|
| 38 |
+
url: str
|
| 39 |
+
|
| 40 |
+
def to_dict(self) -> Dict:
|
| 41 |
+
return asdict(self)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@dataclass
|
| 45 |
+
class DemandCluster:
|
| 46 |
+
cluster_id: str
|
| 47 |
+
summary_demand: str
|
| 48 |
+
normalized_anchor: str
|
| 49 |
+
demand_count: int = 0
|
| 50 |
+
urgency_avg: float = 0.0
|
| 51 |
+
confidence_avg: float = 0.0
|
| 52 |
+
keywords: List[str] = field(default_factory=list)
|
| 53 |
+
subreddits: List[str] = field(default_factory=list)
|
| 54 |
+
examples: List[Dict] = field(default_factory=list)
|
| 55 |
+
|
| 56 |
+
def to_dict(self) -> Dict:
|
| 57 |
+
return asdict(self)
|
| 58 |
+
|
src/web_user_summary/reddit_client.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import time
|
| 4 |
+
from typing import Dict, List, Optional
|
| 5 |
+
|
| 6 |
+
import requests
|
| 7 |
+
|
| 8 |
+
from .models import RedditPost
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class RedditClient:
|
| 12 |
+
def __init__(self, user_agent: str, timeout_s: int = 20, max_retries: int = 4) -> None:
|
| 13 |
+
self.timeout_s = timeout_s
|
| 14 |
+
self.max_retries = max_retries
|
| 15 |
+
self.session = requests.Session()
|
| 16 |
+
self.session.headers.update(
|
| 17 |
+
{
|
| 18 |
+
"User-Agent": user_agent,
|
| 19 |
+
"Accept": "application/json",
|
| 20 |
+
}
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
def _request_json(self, url: str, params: Dict) -> Dict:
|
| 24 |
+
last_error: Optional[Exception] = None
|
| 25 |
+
for attempt in range(1, self.max_retries + 1):
|
| 26 |
+
try:
|
| 27 |
+
response = self.session.get(url, params=params, timeout=self.timeout_s)
|
| 28 |
+
if response.status_code == 429:
|
| 29 |
+
sleep_s = min(12, 2 * attempt)
|
| 30 |
+
time.sleep(sleep_s)
|
| 31 |
+
continue
|
| 32 |
+
response.raise_for_status()
|
| 33 |
+
return response.json()
|
| 34 |
+
except Exception as exc:
|
| 35 |
+
last_error = exc
|
| 36 |
+
if attempt < self.max_retries:
|
| 37 |
+
time.sleep(1.3 * attempt)
|
| 38 |
+
else:
|
| 39 |
+
raise RuntimeError(f"Reddit request failed after retries: {url}") from last_error
|
| 40 |
+
raise RuntimeError(f"Unexpected request failure: {url}")
|
| 41 |
+
|
| 42 |
+
def fetch_subreddit_posts(self, subreddit: str, sort: str = "new", limit: int = 100) -> List[RedditPost]:
|
| 43 |
+
if sort not in {"new", "hot", "top"}:
|
| 44 |
+
raise ValueError("sort must be one of: new, hot, top")
|
| 45 |
+
|
| 46 |
+
out: List[RedditPost] = []
|
| 47 |
+
after: Optional[str] = None
|
| 48 |
+
remaining = max(1, limit)
|
| 49 |
+
|
| 50 |
+
while remaining > 0:
|
| 51 |
+
page_limit = min(100, remaining)
|
| 52 |
+
params = {"limit": page_limit, "raw_json": 1}
|
| 53 |
+
if after:
|
| 54 |
+
params["after"] = after
|
| 55 |
+
|
| 56 |
+
url = f"https://www.reddit.com/r/{subreddit}/{sort}.json"
|
| 57 |
+
payload = self._request_json(url, params=params)
|
| 58 |
+
data = payload.get("data", {})
|
| 59 |
+
children = data.get("children", [])
|
| 60 |
+
|
| 61 |
+
for child in children:
|
| 62 |
+
item = child.get("data", {})
|
| 63 |
+
post = RedditPost(
|
| 64 |
+
id=str(item.get("id", "")),
|
| 65 |
+
subreddit=str(item.get("subreddit", subreddit)),
|
| 66 |
+
title=str(item.get("title", "")).strip(),
|
| 67 |
+
selftext=str(item.get("selftext", "")).strip(),
|
| 68 |
+
author=str(item.get("author", "")),
|
| 69 |
+
created_utc=float(item.get("created_utc", 0.0)),
|
| 70 |
+
score=int(item.get("score", 0)),
|
| 71 |
+
num_comments=int(item.get("num_comments", 0)),
|
| 72 |
+
upvote_ratio=float(item.get("upvote_ratio", 0.0) or 0.0),
|
| 73 |
+
permalink=f"https://www.reddit.com{item.get('permalink', '')}",
|
| 74 |
+
url=str(item.get("url", "")),
|
| 75 |
+
sort_source=sort,
|
| 76 |
+
)
|
| 77 |
+
if post.id and post.title:
|
| 78 |
+
out.append(post)
|
| 79 |
+
|
| 80 |
+
after = data.get("after")
|
| 81 |
+
if not after or not children:
|
| 82 |
+
break
|
| 83 |
+
remaining -= len(children)
|
| 84 |
+
time.sleep(0.6)
|
| 85 |
+
|
| 86 |
+
return out
|
| 87 |
+
|
| 88 |
+
def fetch_subreddit_search(self, subreddit: str, query: str, sort: str = "new", limit: int = 50) -> List[RedditPost]:
|
| 89 |
+
out: List[RedditPost] = []
|
| 90 |
+
after: Optional[str] = None
|
| 91 |
+
remaining = max(1, limit)
|
| 92 |
+
|
| 93 |
+
while remaining > 0:
|
| 94 |
+
page_limit = min(100, remaining)
|
| 95 |
+
params = {
|
| 96 |
+
"q": query,
|
| 97 |
+
"restrict_sr": "1",
|
| 98 |
+
"sort": sort,
|
| 99 |
+
"limit": page_limit,
|
| 100 |
+
"raw_json": 1,
|
| 101 |
+
}
|
| 102 |
+
if after:
|
| 103 |
+
params["after"] = after
|
| 104 |
+
|
| 105 |
+
url = f"https://www.reddit.com/r/{subreddit}/search.json"
|
| 106 |
+
payload = self._request_json(url, params=params)
|
| 107 |
+
data = payload.get("data", {})
|
| 108 |
+
children = data.get("children", [])
|
| 109 |
+
|
| 110 |
+
for child in children:
|
| 111 |
+
item = child.get("data", {})
|
| 112 |
+
post = RedditPost(
|
| 113 |
+
id=str(item.get("id", "")),
|
| 114 |
+
subreddit=str(item.get("subreddit", subreddit)),
|
| 115 |
+
title=str(item.get("title", "")).strip(),
|
| 116 |
+
selftext=str(item.get("selftext", "")).strip(),
|
| 117 |
+
author=str(item.get("author", "")),
|
| 118 |
+
created_utc=float(item.get("created_utc", 0.0)),
|
| 119 |
+
score=int(item.get("score", 0)),
|
| 120 |
+
num_comments=int(item.get("num_comments", 0)),
|
| 121 |
+
upvote_ratio=float(item.get("upvote_ratio", 0.0) or 0.0),
|
| 122 |
+
permalink=f"https://www.reddit.com{item.get('permalink', '')}",
|
| 123 |
+
url=str(item.get("url", "")),
|
| 124 |
+
sort_source=f"search:{query}",
|
| 125 |
+
)
|
| 126 |
+
if post.id and post.title:
|
| 127 |
+
out.append(post)
|
| 128 |
+
|
| 129 |
+
after = data.get("after")
|
| 130 |
+
if not after or not children:
|
| 131 |
+
break
|
| 132 |
+
remaining -= len(children)
|
| 133 |
+
time.sleep(0.6)
|
| 134 |
+
|
| 135 |
+
return out
|
src/web_user_summary/reporting.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from datetime import datetime, timezone
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Dict, Iterable, List
|
| 7 |
+
|
| 8 |
+
from .models import DemandCandidate, DemandCluster, RedditPost
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def timestamped_output_dir(base_dir: Path) -> Path:
|
| 12 |
+
stamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S_utc")
|
| 13 |
+
out = base_dir / stamp
|
| 14 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 15 |
+
return out
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def write_jsonl(path: Path, rows: Iterable[Dict]) -> None:
|
| 19 |
+
with path.open("w", encoding="utf-8") as f:
|
| 20 |
+
for row in rows:
|
| 21 |
+
f.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def write_json(path: Path, payload: Dict) -> None:
|
| 25 |
+
path.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def write_markdown_report(path: Path, meta: Dict, clusters: List[DemandCluster], top_n: int = 25) -> None:
|
| 29 |
+
lines: List[str] = []
|
| 30 |
+
lines.append("# Reddit User Demand Summary")
|
| 31 |
+
lines.append("")
|
| 32 |
+
lines.append("## Run Metrics")
|
| 33 |
+
lines.append(f"- Total posts scanned: {meta.get('total_posts', 0)}")
|
| 34 |
+
lines.append(f"- Demand candidates: {meta.get('total_candidates', 0)}")
|
| 35 |
+
lines.append(f"- Demand clusters: {meta.get('total_clusters', 0)}")
|
| 36 |
+
lines.append("")
|
| 37 |
+
lines.append("## Subreddit Coverage")
|
| 38 |
+
for sub, count in meta.get("subreddit_post_counts", {}).items():
|
| 39 |
+
lines.append(f"- r/{sub}: {count} posts")
|
| 40 |
+
lines.append("")
|
| 41 |
+
lines.append("## Top Demand Themes")
|
| 42 |
+
|
| 43 |
+
for idx, cluster in enumerate(clusters[:top_n], start=1):
|
| 44 |
+
lines.append(f"### {idx}. {cluster.summary_demand}")
|
| 45 |
+
lines.append(f"- Cluster ID: `{cluster.cluster_id}`")
|
| 46 |
+
lines.append(f"- Mentions: {cluster.demand_count}")
|
| 47 |
+
lines.append(f"- Avg confidence: {cluster.confidence_avg}")
|
| 48 |
+
lines.append(f"- Avg urgency: {cluster.urgency_avg}")
|
| 49 |
+
lines.append(f"- Subreddits: {', '.join(cluster.subreddits)}")
|
| 50 |
+
lines.append(f"- Keywords: {', '.join(cluster.keywords)}")
|
| 51 |
+
if cluster.examples:
|
| 52 |
+
ex = cluster.examples[0]
|
| 53 |
+
lines.append(f"- Example post: [{ex.get('title', 'post')}]({ex.get('permalink', '#')})")
|
| 54 |
+
lines.append("")
|
| 55 |
+
|
| 56 |
+
path.write_text("\n".join(lines).strip() + "\n", encoding="utf-8")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def serialize_posts(posts: Iterable[RedditPost]) -> List[Dict]:
|
| 60 |
+
return [p.to_dict() for p in posts]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def serialize_candidates(candidates: Iterable[DemandCandidate]) -> List[Dict]:
|
| 64 |
+
return [c.to_dict() for c in candidates]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def serialize_clusters(clusters: Iterable[DemandCluster]) -> List[Dict]:
|
| 68 |
+
return [c.to_dict() for c in clusters]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _title_from_demand(text: str) -> str:
|
| 72 |
+
clean = " ".join(text.strip().split())
|
| 73 |
+
if not clean:
|
| 74 |
+
return "Community demand"
|
| 75 |
+
clean = clean.rstrip(".?!")
|
| 76 |
+
words = clean.split()
|
| 77 |
+
if len(words) <= 12:
|
| 78 |
+
return clean[:1].upper() + clean[1:]
|
| 79 |
+
short = " ".join(words[:12]).rstrip(",;:")
|
| 80 |
+
return short[:1].upper() + short[1:] + "..."
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def build_demandsolution_seed(clusters: List[DemandCluster], source_name: str = "reddit") -> Dict:
|
| 84 |
+
ideas: List[Dict] = []
|
| 85 |
+
for cluster in clusters:
|
| 86 |
+
ideas.append(
|
| 87 |
+
{
|
| 88 |
+
"source": source_name,
|
| 89 |
+
"source_cluster_id": cluster.cluster_id,
|
| 90 |
+
"title": _title_from_demand(cluster.summary_demand),
|
| 91 |
+
"problem_statement": cluster.summary_demand,
|
| 92 |
+
"tags": cluster.keywords[:6],
|
| 93 |
+
"signal_strength": {
|
| 94 |
+
"mention_count": cluster.demand_count,
|
| 95 |
+
"confidence_avg": cluster.confidence_avg,
|
| 96 |
+
"urgency_avg": cluster.urgency_avg,
|
| 97 |
+
"subreddits": cluster.subreddits,
|
| 98 |
+
},
|
| 99 |
+
"evidence_posts": cluster.examples[:5],
|
| 100 |
+
}
|
| 101 |
+
)
|
| 102 |
+
return {"ideas": ideas}
|