Spaces:
Sleeping
Sleeping
Phase 2: CPC search, sort options, pagination, keyword highlighting, citation trail
Browse files- Add CPC code extraction to analyze and filter in search
- Add sort by date or citations (most cited first)
- Increase results to 25 with Load more pagination
- Highlight search keywords in prior art results
- Add /api/patent/{id}/citations and Related patents UI
- Pin dependency versions in requirements.txt
Co-authored-by: Cursor <cursoragent@cursor.com>
Files changed (3)
- backend/requirements.txt+6-6
- backend/server.py+97-13
- eddison-app.html+211-19
123456fastapiuvicornhttpxpython-dotenvpydanticgoogle-generativeai123456fastapi==0.123.5uvicorn==0.38.0httpx==0.28.1python-dotenv==1.2.1pydantic==2.12.5google-generativeai==0.8.6
13 unmodified lines14151617181916 unmodified lines36373839404119 unmodified lines616263646566676810 unmodified lines7980818283848586875 unmodified lines9394959697989910010110210310414 unmodified lines11912012112212312412512612712812913013113213313413513613729 unmodified lines16716816917017117217313 unmodified linesGEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")PATENTSVIEW_API_KEY = os.getenv("PATENTSVIEW_API_KEY", "")PATENTSVIEW_BASE = "https://search.patentsview.org/api/v1/patent"if GEMINI_API_KEY:genai.configure(api_key=GEMINI_API_KEY)16 unmodified linesclass SearchRequest(BaseModel):keywords: list[str]kind_codes: list[str] = []class ClaimRequest(BaseModel):invention_text: str19 unmodified linesraise HTTPException(502, f"Gemini API error: {error_msg}")def build_patentsview_query(keywords: list[str], kind_codes: list[str]) -> dict:"""Build a PatentsView API query from keywords and kind codes.Each keyword phrase is matched with _text_all (all words must appear)against title OR abstract. A patent matches if ANY keyword phrase hits.10 unmodified lineselse:text_clause = keyword_clauses[0]if kind_codes:return {"_and": [text_clause, {"wipo_kind": kind_codes}]}return text_clause5 unmodified linessystem_prompt = """You are a USPTO patent expert. Given an invention description, extract:1. 8-12 specific technical keywords/phrases for prior art search (precise, domain-specific)2. 4-6 relevant USPTO Kind Codes with a one-line reason eachRespond ONLY with valid JSON in this exact format, no markdown:{"keywords": ["keyword1", "keyword2"],"kindCodes": [{"code": "A1", "label": "Published Application", "reason": "relevant because..."}]}"""raw = await call_gemini(system_prompt, f"Invention: {req.text}")14 unmodified linesif not PATENTSVIEW_API_KEY:raise HTTPException(503, "PatentsView API key not configured. Add PATENTSVIEW_API_KEY to your .env file β request one at https://patentsview.org/apis/keyrequest")query = build_patentsview_query(req.keywords, req.kind_codes)headers = {"X-Api-Key": PATENTSVIEW_API_KEY, "Content-Type": "application/json"}params = {"q": query,"f": ["patent_id", "patent_title", "patent_abstract", "patent_date","patent_type", "wipo_kind","assignees.assignee_organization","cpc_at_issue.cpc_group_id", "cpc_at_issue.cpc_group",],"s": [{"patent_date": "desc"}],"o": {"size": 10},}async with httpx.AsyncClient(timeout=30) as client:29 unmodified lines"cpc": cpc_str,})return {"results": results, "source": "patentsview", "total": data.get("total_hits", len(results))}@app.post("/api/generate-claim")13 unmodified lines1415161718192016 unmodified lines37383940414243444519 unmodified lines656667686970717210 unmodified lines83848586878889909192939495965 unmodified lines10210310410510610710810911011111211311411511611714 unmodified lines13213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216329 unmodified lines19319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625713 unmodified linesGEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")PATENTSVIEW_API_KEY = os.getenv("PATENTSVIEW_API_KEY", "")PATENTSVIEW_BASE = "https://search.patentsview.org/api/v1/patent"PATENTSVIEW_CITATIONS = "https://search.patentsview.org/api/v1/patent/us_patent_citation"if GEMINI_API_KEY:genai.configure(api_key=GEMINI_API_KEY)16 unmodified linesclass SearchRequest(BaseModel):keywords: list[str]kind_codes: list[str] = []cpc_codes: list[str] = []sort_by: str = "date"after: list | None = Noneclass ClaimRequest(BaseModel):invention_text: str19 unmodified linesraise HTTPException(502, f"Gemini API error: {error_msg}")def build_patentsview_query(keywords: list[str], kind_codes: list[str], cpc_codes: list[str]) -> dict:"""Build a PatentsView API query from keywords, kind codes, and CPC codes.Each keyword phrase is matched with _text_all (all words must appear)against title OR abstract. A patent matches if ANY keyword phrase hits.10 unmodified lineselse:text_clause = keyword_clauses[0]clauses = [text_clause]if kind_codes:clauses.append({"wipo_kind": kind_codes})if cpc_codes:clauses.append({"cpc_at_issue.cpc_group_id": cpc_codes})if len(clauses) > 1:return {"_and": clauses}return text_clause5 unmodified linessystem_prompt = """You are a USPTO patent expert. Given an invention description, extract:1. 8-12 specific technical keywords/phrases for prior art search (precise, domain-specific)2. 4-6 relevant USPTO Kind Codes with a one-line reason each3. 3-5 relevant CPC (Cooperative Patent Classification) codes, e.g. G06F40/30, G06N20/00, with a one-line reason eachRespond ONLY with valid JSON in this exact format, no markdown:{"keywords": ["keyword1", "keyword2"],"kindCodes": [{"code": "A1", "label": "Published Application", "reason": "relevant because..."}],"cpcCodes": [{"code": "G06F40/30", "reason": "relevant because..."}]}"""raw = await call_gemini(system_prompt, f"Invention: {req.text}")14 unmodified linesif not PATENTSVIEW_API_KEY:raise HTTPException(503, "PatentsView API key not configured. Add PATENTSVIEW_API_KEY to your .env file β request one at https://patentsview.org/apis/keyrequest")query = build_patentsview_query(req.keywords, req.kind_codes, req.cpc_codes)fields = ["patent_id", "patent_title", "patent_abstract", "patent_date","patent_type", "wipo_kind","assignees.assignee_organization","cpc_at_issue.cpc_group_id", "cpc_at_issue.cpc_group",]if req.sort_by == "citations":fields.append("patent_num_times_cited_by_us_patents")sort = ([{"patent_num_times_cited_by_us_patents": "desc"}, {"patent_id": "asc"}]if req.sort_by == "citations"else [{"patent_date": "desc"}, {"patent_id": "asc"}])options = {"size": 25}if req.after:options["after"] = req.afterheaders = {"X-Api-Key": PATENTSVIEW_API_KEY, "Content-Type": "application/json"}params = {"q": query,"f": fields,"s": sort,"o": options,}async with httpx.AsyncClient(timeout=30) as client:29 unmodified lines"cpc": cpc_str,})last = patents[-1] if patents else Noneafter_cursor = Noneif last and len(patents) >= 25:if req.sort_by == "citations":after_cursor = [last.get("patent_num_times_cited_by_us_patents") or 0, last.get("patent_id")]else:after_cursor = [last.get("patent_date", ""), last.get("patent_id")]return {"results": results,"source": "patentsview","total": data.get("total_hits", len(results)),"after": after_cursor,}@app.get("/api/patent/{patent_id}/citations")async def get_patent_citations(patent_id: str):"""Fetch patents that cite this one (forward) and patents this one cites (backward)."""if not PATENTSVIEW_API_KEY:raise HTTPException(503, "PatentsView API key not configured")pid = patent_id.replace("US", "").replace(",", "").replace(" ", "").strip()if not pid or not pid.replace("0", ""):raise HTTPException(400, "Invalid patent ID")headers = {"X-Api-Key": PATENTSVIEW_API_KEY, "Content-Type": "application/json"}citing = []cited = []async with httpx.AsyncClient(timeout=30) as client:resp_forward = await client.post(PATENTSVIEW_CITATIONS,headers=headers,json={"q": {"citation_patent_id": pid},"f": ["patent_id"],"o": {"size": 10},},)if resp_forward.status_code == 200:data = resp_forward.json()for r in data.get("us_patent_citations", []):citing.append({"patent_id": r.get("patent_id", "")})resp_backward = await client.post(PATENTSVIEW_CITATIONS,headers=headers,json={"q": {"patent_id": pid},"f": ["citation_patent_id"],"o": {"size": 10},},)if resp_backward.status_code == 200:data = resp_backward.json()for r in data.get("us_patent_citations", []):cited.append({"patent_id": r.get("citation_patent_id", "")})return {"citing": citing, "cited": cited}@app.post("/api/generate-claim")
261 unmodified lines262263264265266267233 unmodified lines50150250350450550660 unmodified lines56756856957057157230 unmodified lines6036046056066076086096106116126137 unmodified lines62162262362462562666 unmodified lines693694695696697698699700701702124 unmodified lines82782882983083183283383483583620 unmodified lines85785885986086186220 unmodified lines8838848858868878889 unmodified lines89889990090190290390490590690790890914 unmodified lines9249259269279289299309319329335 unmodified lines9399409419429439449459469472 unmodified lines9509519529539549559563 unmodified lines9609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899906 unmodified lines99799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103597 unmodified lines1133113411351136113711381 unmodified line114011411142114311441145261 unmodified linesborder-color: #3B82F6;color: #60A5FA;}.tag-remove {width: 14px; height: 14px;display: flex; align-items: center; justify-content: center;233 unmodified linesborder-color: var(--red);}/* βββ COPY BUTTON FEEDBACK βββ */.copied { color: var(--accent) !important; }</style>60 unmodified lines</div></div><div class="card section-gap"><div class="card-label">Suggested USPTO Kind Codes<span style="font-size:10px;color:var(--muted);margin-left:8px;text-transform:none;letter-spacing:0">30 unmodified lines</div></div><div class="card"><div class="card-label">Kind Codes to Include</div><div class="tags-area" id="searchKindCodes"></div></div><div class="btn-row"><button class="btn btn-primary" id="searchBtn" onclick="runPriorArtSearch()">β Search Prior Art7 unmodified lines<div class="approved-count" id="approvedCount"></div></div><div class="prior-art-list" id="paList"></div><div class="btn-row" style="margin-top:24px"><button class="btn btn-primary" id="proceedBtn" onclick="goToStep(3)">66 unmodified linesselectedKeywords: [],kindCodes: [],selectedKindCodes: [],priorArt: [],approvedArt: [],claimDraft: '',currentStep: 1};function saveState() {124 unmodified linesstate.keywords = parsed.keywords || [];state.kindCodes = parsed.kindCodes || [];state.selectedKeywords = [...state.keywords];state.selectedKindCodes = state.kindCodes.map(k => k.code);renderKeywords();renderKindCodes();document.getElementById('extractedSection').style.display = 'block';document.getElementById('extractedSection').scrollIntoView({ behavior: 'smooth', block: 'start' });20 unmodified lines});}function renderKindCodes() {const container = document.getElementById('kindCodeTags');container.innerHTML = '';20 unmodified lineselse { state.selectedKindCodes.push(code); el.classList.add('selected'); }saveState();}function removeTag(e, type, i) {e.stopPropagation();state.keywords.splice(i, 1);9 unmodified linesrenderKindCodes();saveState();}function addTagOnEnter(e, type) { if (e.key === 'Enter') addTag(type); }function addTag(type) {if (type === 'keyword') {const val = document.getElementById('kwInput').value.trim();if (val && !state.keywords.includes(val)) { state.keywords.push(val); state.selectedKeywords.push(val); renderKeywords(); }document.getElementById('kwInput').value = '';} else {const val = document.getElementById('kcInput').value.trim().toUpperCase();if (val && !state.kindCodes.find(k => k.code === val)) {14 unmodified linesconst tag = document.createElement('div');tag.className = 'tag selected';tag.dataset.kw = kw;tag.innerHTML = `${kw}<span class="tag-remove" onclick="removeSearchKw(event,'${kw}')">Γ</span>`;kwContainer.appendChild(tag);});const kcContainer = document.getElementById('searchKindCodes');kcContainer.innerHTML = '';state.selectedKindCodes.forEach(code => {5 unmodified lines});}function removeSearchKw(e, kw) {e.stopPropagation();e.target.closest('.tag').remove();}function addSearchTagOnEnter(e, type) { if (e.key === 'Enter') addSearchTag(type); }function addSearchTag(type) {2 unmodified linesconst kwContainer = document.getElementById('searchKeywords');const tag = document.createElement('div');tag.className = 'tag selected';tag.innerHTML = `${val}<span class="tag-remove" onclick="this.closest('.tag').remove()">Γ</span>`;kwContainer.appendChild(tag);document.getElementById('skInput').value = '';}3 unmodified lines}// βββ STEP 2: SEARCH βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββasync function runPriorArtSearch() {const btn = document.getElementById('searchBtn');btn.disabled = true;btn.innerHTML = '<div class="spinner"></div> Searching...';document.getElementById('priorArtResults').style.display = 'none';const keywords = getSearchKeywords();const codes = state.selectedKindCodes;try {const response = await fetch(`${API_BASE}/api/search`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ keywords, kind_codes: codes })});if (!response.ok) {const err = await response.json().catch(() => ({}));throw new Error(err.detail || `Server error (HTTP ${response.status})`);}const data = await response.json();state.priorArt = data.results || [];const source = data.source || 'unknown';if (source === 'patentsview') {console.log(`PatentsView returned ${data.total} total results`);}} catch(err) {state.priorArt = [];const resultsDiv = document.getElementById('priorArtResults');6 unmodified linesreturn;}state.approvedArt = [];renderPriorArt();document.getElementById('priorArtResults').style.display = 'block';document.getElementById('priorArtResults').scrollIntoView({ behavior: 'smooth' });saveState();btn.disabled = false;btn.innerHTML = 'β Re-Search';}function renderPriorArt() {const list = document.getElementById('paList');list.innerHTML = '';state.priorArt.forEach((pa, i) => {const div = document.createElement('div');div.className = 'prior-art-item';div.id = `pa-${i}`;div.innerHTML = `<div class="pa-header"><div class="pa-title">${pa.title}</div><a class="pa-num" href="https://patents.google.com/patent/${pa.patentNumber.replace(/[,\s\/]/g, '')}" target="_blank" rel="noopener" onclick="event.stopPropagation()">${pa.patentNumber}</a></div><div class="pa-meta">${pa.assignee} Β· ${pa.year} Β· Kind Code: <strong>${pa.kindCode}</strong></div><div class="pa-abstract">${pa.abstract}</div><div class="pa-actions"><button class="approve-btn" id="approve-${i}" onclick="approvePA(${i})">β Approve</button><button class="reject-btn" id="reject-${i}" onclick="rejectPA(${i})">β Reject</button></div>`;list.appendChild(div);});updateApprovedCount();}function approvePA(i) {const item = document.getElementById(`pa-${i}`);const approveBtn = document.getElementById(`approve-${i}`);97 unmodified linesif (state.keywords.length > 0) {renderKeywords();renderKindCodes();document.getElementById('extractedSection').style.display = 'block';document.getElementById('analyzeBtn').innerHTML = 'β¦ Re-analyze';1 unmodified lineif (state.priorArt.length > 0) {renderPriorArt();state.approvedArt.forEach(i => {const item = document.getElementById(`pa-${i}`);const btn = document.getElementById(`approve-${i}`);261 unmodified lines262263264265266267268269270271272273274275276277233 unmodified lines51151251351451551651751851952052152252360 unmodified lines58458558658758858959059159259359459559659759859960060160230 unmodified lines6336346356366376386396406416426436446456466476486496506516526536546556567 unmodified lines66466566666766866967067167266 unmodified lines739740741742743744745746747748749750751752753124 unmodified lines87887988088188288388488588688788888989020 unmodified lines91191291391491591691791891992092192292392492592692792892993093120 unmodified lines9529539549559569579589599609619629639649659669679689699709719 unmodified lines981982983984985986987988989990991992993994995996997998999100014 unmodified lines1015101610171018101910201021102210231024102510261027102810291030103110321033103410355 unmodified lines1041104210431044104510461047104810492 unmodified lines105210531054105510561057105810593 unmodified lines1063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611076 unmodified lines11141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122497 unmodified lines13221323132413251326132713281 unmodified line13301331133213331334133513361337261 unmodified linesborder-color: #3B82F6;color: #60A5FA;}.tag.cpc-code {background: rgba(168,85,247,0.1);border-color: rgba(168,85,247,0.3);color: #C084FC;}.tag.cpc-code.selected {background: rgba(168,85,247,0.2);border-color: #A855F7;color: #D8B4FE;}.tag-remove {width: 14px; height: 14px;display: flex; align-items: center; justify-content: center;233 unmodified linesborder-color: var(--red);}/* βββ KEYWORD HIGHLIGHT βββ */.pa-highlight {background: var(--accent-dim);border-radius: 2px;padding: 0 2px;}/* βββ COPY BUTTON FEEDBACK βββ */.copied { color: var(--accent) !important; }</style>60 unmodified lines</div></div><div class="card section-gap"><div class="card-label">Suggested CPC Codes<span style="font-size:10px;color:var(--muted);margin-left:8px;text-transform:none;letter-spacing:0">(Cooperative Patent Classification β e.g. G06F40/30)</span></div><div class="tags-area" id="cpcCodeTags"></div><div class="tag-input-row"><input class="tag-input" id="cpcInput" placeholder="+ Add CPC code..." onkeydown="addTagOnEnter(event,'cpc')"><button class="btn btn-ghost" onclick="addTag('cpc')">Add</button></div></div><div class="card section-gap"><div class="card-label">Suggested USPTO Kind Codes<span style="font-size:10px;color:var(--muted);margin-left:8px;text-transform:none;letter-spacing:0">30 unmodified lines</div></div><div class="card"><div class="card-label">CPC Codes to Include</div><div class="tags-area" id="searchCpcCodes"></div></div><div class="card"><div class="card-label">Kind Codes to Include</div><div class="tags-area" id="searchKindCodes"></div></div><div class="card"><div class="card-label">Sort by</div><select id="sortSelect" style="background:var(--surface2);border:1px solid var(--border);border-radius:8px;padding:8px 14px;font-family:var(--sans);font-size:13px;color:var(--text);"><option value="date">Newest first</option><option value="citations">Most cited first</option></select></div><div class="btn-row"><button class="btn btn-primary" id="searchBtn" onclick="runPriorArtSearch()">β Search Prior Art7 unmodified lines<div class="approved-count" id="approvedCount"></div></div><div class="prior-art-list" id="paList"></div><div id="loadMoreWrap" style="margin-top:16px;display:none"><button class="btn btn-secondary" id="loadMoreBtn" onclick="loadMorePriorArt()">Load more</button></div><div class="btn-row" style="margin-top:24px"><button class="btn btn-primary" id="proceedBtn" onclick="goToStep(3)">66 unmodified linesselectedKeywords: [],kindCodes: [],selectedKindCodes: [],cpcCodes: [],selectedCpcCodes: [],priorArt: [],approvedArt: [],claimDraft: '',currentStep: 1,searchAfter: null,searchTotal: 0,searchKeywords: []};function saveState() {124 unmodified linesstate.keywords = parsed.keywords || [];state.kindCodes = parsed.kindCodes || [];state.cpcCodes = parsed.cpcCodes || [];state.selectedKeywords = [...state.keywords];state.selectedKindCodes = state.kindCodes.map(k => k.code);state.selectedCpcCodes = state.cpcCodes.map(c => c.code);renderKeywords();renderCpcCodes();renderKindCodes();document.getElementById('extractedSection').style.display = 'block';document.getElementById('extractedSection').scrollIntoView({ behavior: 'smooth', block: 'start' });20 unmodified lines});}function renderCpcCodes() {const container = document.getElementById('cpcCodeTags');if (!container) return;container.innerHTML = '';state.cpcCodes.forEach((cc, i) => {const tag = document.createElement('div');const selected = state.selectedCpcCodes.includes(cc.code);tag.className = 'tag cpc-code' + (selected ? ' selected' : '');tag.title = cc.reason || '';tag.innerHTML = `${cc.code}<span class="tag-remove" onclick="removeCpcCode(event,${i})">Γ</span>`;tag.onclick = (e) => { if (!e.target.classList.contains('tag-remove')) toggleCpcCode(cc.code, tag); };container.appendChild(tag);});}function renderKindCodes() {const container = document.getElementById('kindCodeTags');container.innerHTML = '';20 unmodified lineselse { state.selectedKindCodes.push(code); el.classList.add('selected'); }saveState();}function toggleCpcCode(code, el) {const idx = state.selectedCpcCodes.indexOf(code);if (idx > -1) { state.selectedCpcCodes.splice(idx, 1); el.classList.remove('selected'); }else { state.selectedCpcCodes.push(code); el.classList.add('selected'); }saveState();}function removeCpcCode(e, i) {e.stopPropagation();const code = state.cpcCodes[i].code;state.cpcCodes.splice(i, 1);state.selectedCpcCodes = state.selectedCpcCodes.filter(c => c !== code);renderCpcCodes();saveState();}function removeTag(e, type, i) {e.stopPropagation();state.keywords.splice(i, 1);9 unmodified linesrenderKindCodes();saveState();}function addTagOnEnter(e, type) { if (e.key === 'Enter') { e.preventDefault(); addTag(type); } }function addTag(type) {if (type === 'keyword') {const val = document.getElementById('kwInput').value.trim();if (val && !state.keywords.includes(val)) { state.keywords.push(val); state.selectedKeywords.push(val); renderKeywords(); }document.getElementById('kwInput').value = '';} else if (type === 'cpc') {const val = document.getElementById('cpcInput').value.trim();if (val && !state.cpcCodes.find(c => c.code === val)) {state.cpcCodes.push({ code: val, reason: '' });state.selectedCpcCodes.push(val);renderCpcCodes();}document.getElementById('cpcInput').value = '';} else {const val = document.getElementById('kcInput').value.trim().toUpperCase();if (val && !state.kindCodes.find(k => k.code === val)) {14 unmodified linesconst tag = document.createElement('div');tag.className = 'tag selected';tag.dataset.kw = kw;tag.innerHTML = `${escapeHtml(kw)}<span class="tag-remove" onclick="removeSearchKw(event, this)">Γ</span>`;kwContainer.appendChild(tag);});const cpcContainer = document.getElementById('searchCpcCodes');if (cpcContainer) {cpcContainer.innerHTML = '';state.selectedCpcCodes.forEach(code => {const tag = document.createElement('div');tag.className = 'tag cpc-code selected';tag.innerHTML = code;cpcContainer.appendChild(tag);});}const kcContainer = document.getElementById('searchKindCodes');kcContainer.innerHTML = '';state.selectedKindCodes.forEach(code => {5 unmodified lines});}function removeSearchKw(e, btn) {e.stopPropagation();(btn || e.target).closest('.tag').remove();}function addSearchTagOnEnter(e, type) { if (e.key === 'Enter') addSearchTag(type); }function addSearchTag(type) {2 unmodified linesconst kwContainer = document.getElementById('searchKeywords');const tag = document.createElement('div');tag.className = 'tag selected';tag.dataset.kw = val;tag.innerHTML = `${escapeHtml(val)}<span class="tag-remove" onclick="this.closest('.tag').remove()">Γ</span>`;kwContainer.appendChild(tag);document.getElementById('skInput').value = '';}3 unmodified lines}// βββ STEP 2: SEARCH βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββasync function runPriorArtSearch(append) {const btn = document.getElementById('searchBtn');btn.disabled = true;btn.innerHTML = '<div class="spinner"></div> Searching...';if (!append) document.getElementById('priorArtResults').style.display = 'none';const keywords = getSearchKeywords();const codes = state.selectedKindCodes;const cpcCodes = state.selectedCpcCodes || [];const sortBy = document.getElementById('sortSelect')?.value || 'date';const after = append ? state.searchAfter : null;try {const response = await fetch(`${API_BASE}/api/search`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({keywords,kind_codes: codes,cpc_codes: cpcCodes,sort_by: sortBy,after})});if (!response.ok) {const err = await response.json().catch(() => ({}));throw new Error(err.detail || `Server error (HTTP ${response.status})`);}const data = await response.json();const results = data.results || [];if (append) {state.priorArt = state.priorArt.concat(results);} else {state.priorArt = results;state.approvedArt = [];}state.searchAfter = data.after || null;state.searchTotal = data.total || 0;state.searchKeywords = [...keywords];} catch(err) {state.priorArt = [];const resultsDiv = document.getElementById('priorArtResults');6 unmodified linesreturn;}if (!append) state.approvedArt = [];renderPriorArt();document.getElementById('priorArtResults').style.display = 'block';if (!append) document.getElementById('priorArtResults').scrollIntoView({ behavior: 'smooth' });const loadMoreWrap = document.getElementById('loadMoreWrap');const hasMore = state.searchAfter && state.priorArt.length < state.searchTotal;if (loadMoreWrap) loadMoreWrap.style.display = hasMore ? 'block' : 'none';saveState();btn.disabled = false;btn.innerHTML = 'β Re-Search';}function loadMorePriorArt() {runPriorArtSearch(true);}function escapeHtml(s) {if (!s) return '';const div = document.createElement('div');div.textContent = s;return div.innerHTML;}function highlightKeywords(text, keywords) {if (!text || !keywords || keywords.length === 0) return escapeHtml(text);let out = escapeHtml(text);const seen = new Set();keywords.forEach(kw => {if (!kw || seen.has(kw.toLowerCase())) return;seen.add(kw.toLowerCase());const re = new RegExp(`(${kw.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');out = out.replace(re, '<mark class="pa-highlight">$1</mark>');});return out;}function renderPriorArt() {const list = document.getElementById('paList');list.innerHTML = '';const keywords = state.searchKeywords || [];state.priorArt.forEach((pa, i) => {const div = document.createElement('div');div.className = 'prior-art-item';div.id = `pa-${i}`;const titleHtml = highlightKeywords(pa.title, keywords);const abstractHtml = highlightKeywords(pa.abstract, keywords);const patentId = (pa.patentNumber || '').replace(/[,\s\/]/g, '');div.innerHTML = `<div class="pa-header"><div class="pa-title">${titleHtml}</div><a class="pa-num" href="https://patents.google.com/patent/${patentId}" target="_blank" rel="noopener" onclick="event.stopPropagation()">${escapeHtml(pa.patentNumber || '')}</a></div><div class="pa-meta">${escapeHtml(pa.assignee || '')} Β· ${escapeHtml(String(pa.year || ''))} Β· Kind Code: <strong>${escapeHtml(pa.kindCode || '')}</strong></div><div class="pa-abstract">${abstractHtml}</div><div class="pa-actions"><button class="approve-btn" id="approve-${i}" onclick="approvePA(${i})">β Approve</button><button class="reject-btn" id="reject-${i}" onclick="rejectPA(${i})">β Reject</button><button class="btn btn-ghost" style="font-size:11px;padding:4px 10px" onclick="event.stopPropagation();toggleCitations(${i})">Related patents</button></div><div id="citations-${i}" class="pa-citations" style="display:none;margin-top:12px;padding-top:12px;border-top:1px solid var(--border);font-size:12px;color:var(--muted)"></div>`;list.appendChild(div);});updateApprovedCount();}async function toggleCitations(i) {const el = document.getElementById(`citations-${i}`);if (!el) return;if (el.style.display === 'block') {el.style.display = 'none';return;}const pa = state.priorArt[i];if (!pa) return;const pid = (pa.patentNumber || '').replace(/[,\s\/]/g, '').replace(/^US/i, '');if (!pid) return;el.innerHTML = '<span>Loading...</span>';el.style.display = 'block';try {const resp = await fetch(`${API_BASE}/api/patent/${pid}/citations`);if (!resp.ok) throw new Error('Failed to load');const data = await resp.json();const citing = (data.citing || []).map(p => `US${p.patent_id}`).filter(Boolean);const cited = (data.cited || []).map(p => `US${p.patent_id}`).filter(Boolean);let html = '';if (citing.length) {html += '<div style="margin-bottom:8px"><strong>Citing this patent:</strong> ';html += citing.map(id => `<a href="https://patents.google.com/patent/${id.replace(/[,\s]/g,'')}" target="_blank" rel="noopener" style="color:var(--accent);margin-right:8px">${id}</a>`).join('');html += '</div>';}if (cited.length) {html += '<div><strong>Cited by this patent:</strong> ';html += cited.map(id => `<a href="https://patents.google.com/patent/${id.replace(/[,\s]/g,'')}" target="_blank" rel="noopener" style="color:var(--accent);margin-right:8px">${id}</a>`).join('');html += '</div>';}if (!html) html = 'No citation data found.';el.innerHTML = html;} catch (e) {el.innerHTML = 'Could not load citations.';}}function approvePA(i) {const item = document.getElementById(`pa-${i}`);const approveBtn = document.getElementById(`approve-${i}`);97 unmodified linesif (state.keywords.length > 0) {renderKeywords();if (state.cpcCodes && state.cpcCodes.length) renderCpcCodes();renderKindCodes();document.getElementById('extractedSection').style.display = 'block';document.getElementById('analyzeBtn').innerHTML = 'β¦ Re-analyze';1 unmodified lineif (state.priorArt.length > 0) {renderPriorArt();const loadMoreWrap = document.getElementById('loadMoreWrap');if (loadMoreWrap) loadMoreWrap.style.display = (state.searchAfter && state.priorArt.length < state.searchTotal) ? 'block' : 'none';state.approvedArt.forEach(i => {const item = document.getElementById(`pa-${i}`);const btn = document.getElementById(`approve-${i}`);
backend/requirements.txt+6-6
backend/server.py+97-13
eddison-app.html+211-19