Spaces:
Sleeping
Add 7-step USPTO search methodology integration
Browse filesIncorporates the USPTO's structured prior art search methodology:
- Step 1-2: Invention decomposition and synonym expansion via /api/analyze-deep
- Step 3: Primary/secondary CPC classification with explanations
- Step 4: Boolean search strings (broad/intermediate/examiner-level) with Run in App
- Step 5: Seed patent strategy with citation mining
- Step 6: Examiner-level comparison framework via /api/evaluate-patent
- Step 7: Search saturation tracking with progress bar
Backend: Two new endpoints (analyze-deep, evaluate-patent) with structured Gemini prompts.
Frontend: Collapsible decomposition/synonym cards in Step 1, boolean queries/seed patent/
saturation tracker in Step 2, per-patent evaluation tables with threat level badges.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Files changed (2)
- backend/server.py+185-4
- eddison-app.html+507-4
52 unmodified lines53545556575814 unmodified lines73747576777844 unmodified lines123124125126127128129130131220 unmodified lines3523533543553563573583593607 unmodified lines36836937037137237352 unmodified linesinvention_text: strprior_art: list[dict]# ββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ14 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.44 unmodified lines]}"""raw = await call_gemini(system_prompt, f"Invention: {req.text}")clean = raw.replace("```json", "").replace("```", "").strip()try:parsed = json.loads(clean)except json.JSONDecodeError:raise HTTPException(502, "Failed to parse Gemini response as JSON")return parsed220 unmodified linesuser_msg = f"Patent Claims to Analyze:\n{req.claims}\n\nInvention Description:\n{req.invention_text}\n\nRelevant Prior Art:\n{prior_art_summary}\n\nProvide your structured analysis."raw = await call_gemini(system_prompt, user_msg)clean = raw.replace("```json", "").replace("```", "").strip()try:parsed = json.loads(clean)except json.JSONDecodeError:raise HTTPException(502, "Failed to parse Gemini claim analysis response as JSON")7 unmodified linesreturn parsed# ββ Serve the frontend βββββββββββββββββββββββββββββββββββββββββββββββββββββββFRONTEND_DIR = os.path.join(os.path.dirname(__file__), "..")52 unmodified lines535455565758596061626314 unmodified lines787980818283848586878844 unmodified lines133134135136137138139140220 unmodified lines3613623633643653663673687 unmodified lines37637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355452 unmodified linesinvention_text: strprior_art: list[dict]class EvaluatePatentRequest(BaseModel):invention_text: strpatent: dictdecomposition: dict# ββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ14 unmodified linesraise HTTPException(502, f"Gemini API error: {error_msg}")def clean_json(raw: str) -> str:"""Strip markdown fences from Gemini JSON responses."""return raw.replace("```json", "").replace("```", "").strip()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.44 unmodified lines]}"""raw = await call_gemini(system_prompt, f"Invention: {req.text}")try:parsed = json.loads(clean_json(raw))except json.JSONDecodeError:raise HTTPException(502, "Failed to parse Gemini response as JSON")return parsed220 unmodified linesuser_msg = f"Patent Claims to Analyze:\n{req.claims}\n\nInvention Description:\n{req.invention_text}\n\nRelevant Prior Art:\n{prior_art_summary}\n\nProvide your structured analysis."raw = await call_gemini(system_prompt, user_msg)try:parsed = json.loads(clean_json(raw))except json.JSONDecodeError:raise HTTPException(502, "Failed to parse Gemini claim analysis response as JSON")7 unmodified linesreturn parsed# ββ USPTO 7-Step Methodology Endpoints ββββββββββββββββββββββββββββββββββββββββSYSTEM_DECOMPOSE = """You are a USPTO patent search expert. Given an invention description, perform two tasks:TASK 1 β DECOMPOSE THE INVENTIONExtract and categorize:- core_features: 3-5 core technical features that define the invention's novelty- supporting_features: 2-4 supporting/secondary features that enable or enhance the core- claimed_improvements: 1-3 specific technical improvements over existing solutions- components: hardware/software interaction components involvedTASK 2 β SYNONYM EXPANSIONFor EACH core_feature, generate:- technical_synonyms: 2-3 precise technical synonyms (no marketing terms)- industry_terms: 1-2 industry-specific terminology equivalents- broader: 1 broader/more generic term- narrower: 1 narrower/more specific termFrom the decomposition and synonyms, also extract:- keywords: 8-12 specific search keywords/phrases combining core features and their best synonyms- kindCodes: 4-6 relevant USPTO Kind Codes with label and one-line reasonRespond ONLY with valid JSON, no markdown fences:{"decomposition": {"core_features": ["feature1", "feature2"],"supporting_features": ["feat1", "feat2"],"claimed_improvements": ["improvement1"],"components": ["component1", "component2"]},"synonyms": {"feature name here": {"technical_synonyms": ["syn1", "syn2"],"industry_terms": ["term1"],"broader": "broader_term","narrower": "narrower_term"}},"keywords": ["keyword1", "keyword2"],"kindCodes": [{"code": "A1", "label": "Published Application", "reason": "relevant because..."}]}"""SYSTEM_CPC_BOOLEAN = """You are a USPTO patent classification and search strategy expert. Given an invention description and its decomposed features, perform two tasks:TASK 1 β CPC CLASSIFICATIONIdentify likely Cooperative Patent Classification codes:- 2-3 primary CPC codes most directly relevant to the invention, with explanation- 2-3 secondary/adjacent CPC codes, with explanationPrioritize AI, data processing, memory, or hardware interaction classes when applicable.TASK 2 β BOOLEAN SEARCH STRINGSConstruct three tiers of search queries:- broad: 2 queries combining 1 core feature OR its synonyms β maximum recall- intermediate: 2 queries combining 2 core features AND 1 secondary feature β balanced- examiner: 2 queries using specific technical terms with classification restrictions β maximum precisionEach query must use Boolean operators (AND/OR), include parentheses, and combine 1-2 core features + 1 secondary feature. Avoid over-constraining.For each query, also extract keyword_sets: arrays of keyword phrases suitable for PatentsView API full-text search.Respond ONLY with valid JSON, no markdown fences:{"cpcCodes": [{"code": "G06F40/30", "type": "primary", "reason": "relevant because..."},{"code": "H04L67/00", "type": "secondary", "reason": "relevant because..."}],"booleanQueries": [{"level": "broad","label": "Broad β Maximum Recall","query": "(term1 OR term2) AND (term3)","keyword_sets": ["term1 term3", "term2 term3"]}]}"""SYSTEM_EVALUATE = """You are a USPTO patent examiner performing a prior art comparison. Given an invention and a prior art patent, evaluate using the standard examiner comparison framework.For each core feature of the invention, determine:- disclosed: Does the prior art explicitly disclose this feature? ("yes", "partial", or "no")- equivalent: Does it describe an equivalent structure or method? ("yes", "partial", or "no")- same_solution: Does it achieve the same technical solution? ("yes", "partial", or "no")- problem_only: Does it merely describe the problem without the solution? ("yes" or "no")Also provide:- overlap_summary: One sentence on how much this prior art overlaps with the invention- threat_level: "high" (blocks patentability), "medium" (requires claim narrowing), or "low" (distinguishable)- distinguishing_features: list of invention features NOT found in this prior artRespond ONLY with valid JSON, no markdown fences:{"feature_comparison": [{"feature": "the core feature text","disclosed": "yes","equivalent": "partial","same_solution": "no","problem_only": "no"}],"overlap_summary": "...","threat_level": "medium","distinguishing_features": ["feature1", "feature2"]}"""@app.post("/api/analyze-deep")async def analyze_deep(req: AnalyzeRequest):"""USPTO 7-Step: Decompose invention, expand synonyms, classify CPC, and build search queries."""# Call 1: Decomposition + Synonyms + Keywords + Kind Codes (Steps 1-2)raw1 = await call_gemini(SYSTEM_DECOMPOSE, f"Invention: {req.text}")try:parsed1 = json.loads(clean_json(raw1))except json.JSONDecodeError:raise HTTPException(502, "Failed to parse decomposition response as JSON")# Call 2: CPC Classification + Boolean Queries (Steps 3-4)decomp_context = json.dumps(parsed1.get("decomposition", {}))synonym_context = json.dumps(parsed1.get("synonyms", {}))context_msg = (f"Invention: {req.text}\n\n"f"Decomposition:\n{decomp_context}\n\n"f"Core feature synonyms:\n{synonym_context}")try:raw2 = await call_gemini(SYSTEM_CPC_BOOLEAN, context_msg)parsed2 = json.loads(clean_json(raw2))except json.JSONDecodeError:# If Call 2 fails, return Call 1 results with empty CPC/boolean fieldsparsed2 = {"cpcCodes": [], "booleanQueries": []}except HTTPException:parsed2 = {"cpcCodes": [], "booleanQueries": []}return {"decomposition": parsed1.get("decomposition"),"synonyms": parsed1.get("synonyms"),"keywords": parsed1.get("keywords", []),"kindCodes": parsed1.get("kindCodes", []),"cpcCodes": parsed2.get("cpcCodes", []),"booleanQueries": parsed2.get("booleanQueries", []),}@app.post("/api/evaluate-patent")async def evaluate_patent(req: EvaluatePatentRequest):"""USPTO Step 6: Examiner-level comparison of a prior art patent against the invention."""patent_info = (f"Patent {req.patent.get('patentNumber', 'N/A')}: "f"\"{req.patent.get('title', '')}\"\n"f"Assignee: {req.patent.get('assignee', 'Unknown')}\n"f"Abstract: {req.patent.get('abstract', '')}")features = "\n".join(f"- {f}" for f in req.decomposition.get("core_features", []))user_msg = (f"Invention: {req.invention_text}\n\n"f"Core Features to evaluate against:\n{features}\n\n"f"Prior Art to Evaluate:\n{patent_info}\n\n"f"Provide your structured comparison.")raw = await call_gemini(SYSTEM_EVALUATE, user_msg)try:parsed = json.loads(clean_json(raw))except json.JSONDecodeError:raise HTTPException(502, "Failed to parse evaluation response as JSON")return parsed# ββ Serve the frontend βββββββββββββββββββββββββββββββββββββββββββββββββββββββFRONTEND_DIR = os.path.join(os.path.dirname(__file__), "..")
591 unmodified lines59259359459559659784 unmodified lines68268368468568668736 unmodified lines7247257267277287292 unmodified lines732733734735736737105 unmodified lines843844845846847848849108 unmodified lines9589599609619629639649659669674 unmodified lines972973974975976977978979980981982983984985986987147 unmodified lines11351136113711381139114085 unmodified lines122612271228122912301231123268 unmodified lines130113021303130413051306130713081309131013111312265 unmodified lines1578157915801581158215835 unmodified lines158915901591159215931594591 unmodified lines.analysis-improve-btn:hover {background: var(--accent-dim); border-color: var(--accent);}</style></head><body>84 unmodified lines</div></div><div class="btn-row"><button class="btn btn-primary" onclick="goToStep(2)">Continue to Prior Art Search β</button></div>36 unmodified lines</select></div><div class="btn-row"><button class="btn btn-primary" id="searchBtn" onclick="runPriorArtSearch()">β Search Prior Art2 unmodified lines</div><div id="priorArtResults" class="section-gap" style="display:none"><div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px"><div style="font-family:var(--display);font-size:22px;letter-spacing:0.05em">Results</div><div class="approved-count" id="approvedCount"></div>105 unmodified linescurrentStep: 1,searchAfter: null,searchTotal: 0,searchKeywords: []};function saveState() {108 unmodified linesconst btn = document.getElementById('analyzeBtn');btn.disabled = true;btn.innerHTML = '<div class="spinner"></div> Analyzing...';try {const response = await fetch(`${API_BASE}/api/analyze`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ text })4 unmodified lines}const parsed = await response.json();state.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' });} catch (err) {147 unmodified linestag.innerHTML = `<strong>${code}</strong>${kc ? ' β ' + kc.label : ''}`;kcContainer.appendChild(tag);});}function removeSearchKw(e, btn) {85 unmodified linesconst hasMore = state.searchAfter && state.priorArt.length < state.searchTotal;if (loadMoreWrap) loadMoreWrap.style.display = hasMore ? 'block' : 'none';saveState();btn.disabled = false;btn.innerHTML = 'β Re-Search';}68 unmodified lines<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) {265 unmodified linesdocument.getElementById('claimContent').scrollIntoView({ behavior: 'smooth' });}// βββ RESTORE SESSION ON LOAD βββββββββββββββββββββββββββββββββββββββββββββββββfunction restoreSession() {loadState();5 unmodified linesrenderKeywords();if (state.cpcCodes && state.cpcCodes.length) renderCpcCodes();renderKindCodes();document.getElementById('extractedSection').style.display = 'block';document.getElementById('analyzeBtn').innerHTML = 'β¦ Re-analyze';}591 unmodified lines59259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367484 unmodified lines75976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280336 unmodified lines8408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758762 unmodified lines879880881882883884885886887888889890891892893894895896105 unmodified lines10021003100410051006100710081009101010111012101310141015108 unmodified lines11241125112611271128112911301131113211334 unmodified lines113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170147 unmodified lines131813191320132113221323132413251326132713281329133013311332133385 unmodified lines141914201421142214231424142514261427142868 unmodified lines14971498149915001501150215031504150515061507150815091510151115121513151415151516265 unmodified lines178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220835 unmodified lines208920902091209220932094209520962097591 unmodified lines.analysis-improve-btn:hover {background: var(--accent-dim); border-color: var(--accent);}/* βββ COLLAPSIBLE SECTIONS βββ */.collapsible-header {display: flex; align-items: center; justify-content: space-between;cursor: pointer; user-select: none;}.collapsible-header:hover { color: var(--text); }.collapse-icon { font-size: 10px; color: var(--muted); transition: transform 0.2s; }/* βββ DECOMPOSITION GRID βββ */.decomp-grid {display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-top: 14px;}@media (max-width: 600px) { .decomp-grid { grid-template-columns: 1fr; } }.decomp-label {font-size: 11px; font-weight: 500; color: var(--accent);letter-spacing: 0.05em; margin-bottom: 8px;}.decomp-list { list-style: none; padding: 0; margin: 0; }.decomp-list li {font-size: 13px; color: rgba(237,240,255,0.75); line-height: 1.55;padding: 3px 0 3px 14px; position: relative; font-weight: 300;}.decomp-list li::before { content: '\203A'; position: absolute; left: 0; color: var(--accent); }/* βββ SYNONYM EXPANSION βββ */.synonym-row { padding: 12px 0; border-bottom: 1px solid var(--border); }.synonym-row:last-child { border-bottom: none; }.synonym-feature { font-size: 13px; font-weight: 500; color: var(--text); margin-bottom: 8px; }.synonym-tags { display: flex; flex-wrap: wrap; gap: 6px; }/* βββ BOOLEAN QUERIES βββ */.boolean-query-item {background: var(--surface2); border: 1px solid var(--border);border-radius: 10px; padding: 16px; margin-bottom: 10px;}.boolean-query-label {font-size: 11px; font-weight: 500; color: var(--accent);letter-spacing: 0.08em; text-transform: uppercase; margin-bottom: 8px;}.boolean-query-text {font-family: var(--mono); font-size: 12px; color: rgba(237,240,255,0.7);line-height: 1.6; background: rgba(0,0,0,0.2); border-radius: 6px;padding: 10px 12px; margin-bottom: 10px; word-break: break-word;}.boolean-query-actions { display: flex; gap: 8px; }/* βββ SEED PATENT βββ */.seed-patent-summary {background: var(--surface2); border: 1px solid var(--border);border-radius: 10px; padding: 16px;}/* βββ SATURATION BAR βββ */.saturation-bar {background: var(--surface); border: 1px solid var(--border);border-radius: 10px; padding: 16px; margin-bottom: 16px;}.saturation-header {display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px;}.saturation-pct { font-family: var(--mono); font-size: 14px; font-weight: 600; color: var(--accent); }.saturation-track {width: 100%; height: 6px; background: var(--surface2);border-radius: 3px; overflow: hidden; margin-bottom: 8px;}.saturation-fill {height: 100%; background: var(--accent); border-radius: 3px;transition: width 0.4s ease; width: 0%;}.saturation-hint { font-size: 12px; color: var(--muted); font-weight: 300; }/* βββ EVALUATION TABLE βββ */.pa-evaluation table { font-family: var(--sans); }.pa-evaluation th {font-size: 10px; letter-spacing: 0.08em; text-transform: uppercase; font-weight: 500;}</style></head><body>84 unmodified lines</div></div><!-- Invention Decomposition (collapsible) --><div class="card section-gap" id="decompositionCard" style="display:none"><div class="card-label collapsible-header" onclick="toggleSection('decomposition')"><span>Invention Decomposition</span><span class="collapse-icon" id="decomposition-icon">▼</span></div><div class="collapsible-body" id="decomposition-body"><div class="decomp-grid"><div class="decomp-col"><div class="decomp-label">Core Technical Features</div><ul class="decomp-list" id="coreFeatures"></ul></div><div class="decomp-col"><div class="decomp-label">Supporting Features</div><ul class="decomp-list" id="supportingFeatures"></ul></div><div class="decomp-col"><div class="decomp-label">Claimed Improvements</div><ul class="decomp-list" id="claimedImprovements"></ul></div><div class="decomp-col"><div class="decomp-label">HW/SW Components</div><ul class="decomp-list" id="hwswComponents"></ul></div></div></div></div><!-- Synonym Expansion (collapsible) --><div class="card section-gap" id="synonymCard" style="display:none"><div class="card-label collapsible-header" onclick="toggleSection('synonym')"><span>Synonym Expansion</span><span class="collapse-icon" id="synonym-icon">▼</span></div><div class="collapsible-body" id="synonym-body"><div id="synonymGrid"></div></div></div><div class="btn-row"><button class="btn btn-primary" onclick="goToStep(2)">Continue to Prior Art Search β</button></div>36 unmodified lines</select></div><!-- Boolean Search Strings (collapsible) --><div class="card section-gap" id="booleanQueriesCard" style="display:none"><div class="card-label collapsible-header" onclick="toggleSection('boolean')"><span>Boolean Search Strings</span><span class="collapse-icon" id="boolean-icon">▼</span></div><div class="collapsible-body" id="boolean-body"><div class="panel-sub" style="margin-bottom:16px;font-size:12px">Reference queries for USPTO Full-Text search. Click "Run in App" to search with extracted keywords.</div><div id="booleanQueryList"></div></div></div><!-- Seed Patent Strategy (collapsible) --><div class="card section-gap" id="seedPatentCard" style="display:none"><div class="card-label collapsible-header" onclick="toggleSection('seed')"><span>Seed Patent Strategy</span><span class="collapse-icon" id="seed-icon">▼</span></div><div class="collapsible-body" id="seed-body"><div class="panel-sub" style="margin-bottom:12px;font-size:12px">Mark a result as your "seed patent" to mine its citations and CPC codes for expanded search.</div><div id="seedPatentInfo" style="display:none"></div><div id="seedPatentEmpty" style="font-size:12px;color:var(--muted)">No seed patent selected. After searching, click "Use as Seed" on a result to begin citation mining.</div></div></div><div class="btn-row"><button class="btn btn-primary" id="searchBtn" onclick="runPriorArtSearch()">β Search Prior Art2 unmodified lines</div><div id="priorArtResults" class="section-gap" style="display:none"><!-- Saturation Tracker --><div class="saturation-bar" id="saturationBar" style="display:none"><div class="saturation-header"><span class="card-label" style="margin:0">Search Saturation</span><span class="saturation-pct" id="saturationPct">0%</span></div><div class="saturation-track"><div class="saturation-fill" id="saturationFill"></div></div><div class="saturation-hint" id="saturationHint"></div></div><div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px"><div style="font-family:var(--display);font-size:22px;letter-spacing:0.05em">Results</div><div class="approved-count" id="approvedCount"></div>105 unmodified linescurrentStep: 1,searchAfter: null,searchTotal: 0,searchKeywords: [],// USPTO 7-Step Methodology fieldsdecomposition: null,synonyms: null,booleanQueries: null,seedPatent: null,evaluations: {},saturation: { searchesRun: 0, queriesExhausted: [] }};function saveState() {108 unmodified linesconst btn = document.getElementById('analyzeBtn');btn.disabled = true;btn.innerHTML = '<div class="spinner"></div> Analyzing (decomposing invention)...';try {const response = await fetch(`${API_BASE}/api/analyze-deep`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ text })4 unmodified lines}const parsed = await response.json();// Existing fieldsstate.keywords = parsed.keywords || [];state.kindCodes = parsed.kindCodes || [];state.cpcCodes = (parsed.cpcCodes || []).map(c => ({code: c.code, reason: c.reason || '', type: c.type || 'primary'}));state.selectedKeywords = [...state.keywords];state.selectedKindCodes = state.kindCodes.map(k => k.code);state.selectedCpcCodes = state.cpcCodes.map(c => c.code);// New 7-step methodology fieldsstate.decomposition = parsed.decomposition || null;state.synonyms = parsed.synonyms || null;state.booleanQueries = parsed.booleanQueries || null;// Clear evaluations and saturation when re-analyzingstate.evaluations = {};state.saturation = { searchesRun: 0, queriesExhausted: [] };// Render existing sectionsrenderKeywords();renderCpcCodes();renderKindCodes();// Render new methodology sectionsif (state.decomposition) renderDecomposition();if (state.synonyms) renderSynonyms();document.getElementById('extractedSection').style.display = 'block';document.getElementById('extractedSection').scrollIntoView({ behavior: 'smooth', block: 'start' });} catch (err) {147 unmodified linestag.innerHTML = `<strong>${code}</strong>${kc ? ' β ' + kc.label : ''}`;kcContainer.appendChild(tag);});// Render 7-step methodology panelsrenderBooleanQueries();if (state.seedPatent !== null) {document.getElementById('seedPatentCard').style.display = 'block';document.getElementById('seedPatentEmpty').style.display = 'none';} else {document.getElementById('seedPatentCard').style.display = 'block';}updateSaturation();}function removeSearchKw(e, btn) {85 unmodified linesconst hasMore = state.searchAfter && state.priorArt.length < state.searchTotal;if (loadMoreWrap) loadMoreWrap.style.display = hasMore ? 'block' : 'none';// Track saturationif (!append) state.saturation.searchesRun++;saveState();updateSaturation();btn.disabled = false;btn.innerHTML = 'β Re-Search';}68 unmodified lines<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><button class="btn btn-ghost" style="font-size:11px;padding:4px 10px" onclick="event.stopPropagation();evaluatePatent(${i})">⚖ Evaluate</button><button class="btn btn-ghost" style="font-size:11px;padding:4px 10px" onclick="event.stopPropagation();setSeedPatent(${i})">★ Use as Seed</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><div id="eval-${i}" style="display:none"></div>`;list.appendChild(div);});updateApprovedCount();// Re-render any cached evaluationsObject.keys(state.evaluations).forEach(idx => {const i = parseInt(idx);if (state.evaluations[i]) renderEvaluation(i, state.evaluations[i]);});}async function toggleCitations(i) {265 unmodified linesdocument.getElementById('claimContent').scrollIntoView({ behavior: 'smooth' });}// βββ USPTO 7-STEP: COLLAPSIBLE SECTIONS ββββββββββββββββββββββββββββββββββββββfunction toggleSection(name) {const body = document.getElementById(`${name}-body`);const icon = document.getElementById(`${name}-icon`);if (!body) return;if (body.style.display === 'none') {body.style.display = 'block';if (icon) icon.innerHTML = '▲';} else {body.style.display = 'none';if (icon) icon.innerHTML = '▼';}}// βββ USPTO STEP 1: RENDER DECOMPOSITION ββββββββββββββββββββββββββββββββββββββfunction renderDecomposition() {const d = state.decomposition;if (!d) return;document.getElementById('decompositionCard').style.display = 'block';const render = (id, items) => {const ul = document.getElementById(id);if (ul) ul.innerHTML = (items || []).map(f => `<li>${escapeHtml(f)}</li>`).join('');};render('coreFeatures', d.core_features);render('supportingFeatures', d.supporting_features);render('claimedImprovements', d.claimed_improvements);render('hwswComponents', d.components);}// βββ USPTO STEP 2: RENDER SYNONYMS ββββββββββββββββββββββββββββββββββββββββββfunction renderSynonyms() {const s = state.synonyms;if (!s || typeof s !== 'object') return;document.getElementById('synonymCard').style.display = 'block';const grid = document.getElementById('synonymGrid');grid.innerHTML = Object.entries(s).map(([feature, data]) => `<div class="synonym-row"><div class="synonym-feature">${escapeHtml(feature)}</div><div class="synonym-tags">${(data.technical_synonyms || []).map(t => `<span class="tag">${escapeHtml(t)}</span>`).join('')}${(data.industry_terms || []).map(t => `<span class="tag kind-code">${escapeHtml(t)}</span>`).join('')}${data.broader ? `<span class="tag cpc-code" title="Broader term">${escapeHtml(data.broader)}</span>` : ''}${data.narrower ? `<span class="tag" style="background:rgba(74,222,128,0.1);border-color:rgba(74,222,128,0.3);color:#4ade80" title="Narrower term">${escapeHtml(data.narrower)}</span>` : ''}</div></div>`).join('');}// βββ USPTO STEP 4: BOOLEAN QUERIES ββββββββββββββββββββββββββββββββββββββββββfunction renderBooleanQueries() {const queries = state.booleanQueries;if (!queries || queries.length === 0) {document.getElementById('booleanQueriesCard').style.display = 'none';return;}document.getElementById('booleanQueriesCard').style.display = 'block';const list = document.getElementById('booleanQueryList');list.innerHTML = queries.map((q, i) => `<div class="boolean-query-item"><div class="boolean-query-label">${escapeHtml(q.label || q.level)}</div><div class="boolean-query-text">${escapeHtml(q.query)}</div><div class="boolean-query-actions"><button class="btn btn-ghost" style="font-size:11px" onclick="copyBooleanQuery(${i})">Copy for USPTO</button><button class="btn btn-ghost" style="font-size:11px;color:var(--accent);border-color:rgba(200,241,53,0.3)" onclick="runBooleanQuery(${i})">Run in App</button></div></div>`).join('');}function copyBooleanQuery(index) {const q = state.booleanQueries[index];if (!q) return;navigator.clipboard.writeText(q.query).then(() => {const items = document.querySelectorAll('.boolean-query-item');if (items[index]) {const btn = items[index].querySelector('.btn-ghost');if (btn) { const orig = btn.textContent; btn.textContent = 'β Copied!'; setTimeout(() => btn.textContent = orig, 1500); }}});}function runBooleanQuery(index) {const q = state.booleanQueries[index];if (!q || !q.keyword_sets || q.keyword_sets.length === 0) return;const kwContainer = document.getElementById('searchKeywords');kwContainer.innerHTML = '';q.keyword_sets.forEach(kw => {const tag = document.createElement('div');tag.className = 'tag selected';tag.dataset.kw = kw;tag.innerHTML = `${escapeHtml(kw)}<span class="tag-remove" onclick="this.closest('.tag').remove()">Γ</span>`;kwContainer.appendChild(tag);});if (!state.saturation.queriesExhausted.includes(q.level)) {state.saturation.queriesExhausted.push(q.level);}state.saturation.searchesRun++;saveState();runPriorArtSearch();}// βββ USPTO STEP 5: SEED PATENT STRATEGY βββββββββββββββββββββββββββββββββββββfunction setSeedPatent(index) {state.seedPatent = index;saveState();document.getElementById('seedPatentCard').style.display = 'block';document.getElementById('seedPatentEmpty').style.display = 'none';loadSeedCitations(index);}async function loadSeedCitations(index) {const pa = state.priorArt[index];if (!pa) return;const pid = (pa.patentNumber || '').replace(/[,\s\/]/g, '').replace(/^US/i, '');const infoDiv = document.getElementById('seedPatentInfo');infoDiv.style.display = 'block';infoDiv.innerHTML = '<div style="font-size:13px;color:var(--muted)"><div class="spinner spinner-accent" style="display:inline-block;vertical-align:middle;margin-right:8px;width:14px;height:14px;border-width:2px"></div>Loading citations...</div>';try {const resp = await fetch(`${API_BASE}/api/patent/${pid}/citations`);if (!resp.ok) throw new Error('Failed');const data = await resp.json();const citing = (data.citing || []).map(p => `US${p.patent_id}`);const cited = (data.cited || []).map(p => `US${p.patent_id}`);const seedCpc = pa.cpc ? [pa.cpc] : [];infoDiv.innerHTML = `<div class="seed-patent-summary"><div style="font-size:14px;font-weight:500;margin-bottom:8px">${escapeHtml(pa.patentNumber)}: ${escapeHtml(pa.title)}</div><div style="font-size:12px;color:var(--muted);margin-bottom:12px">CPC: ${escapeHtml(pa.cpc || 'N/A')} | ${citing.length} patents cite this | Cites ${cited.length} patents</div><div style="font-size:12px;margin-bottom:8px;color:rgba(237,240,255,0.8)"><strong>Strategy:</strong> Search within this patent's CPC subclass and citation network for comprehensive coverage.</div><div style="display:flex;gap:8px;flex-wrap:wrap">${seedCpc.length ? `<button class="btn btn-ghost" style="font-size:11px" onclick="searchSeedCpc('${escapeHtml(seedCpc[0])}')">Search CPC ${escapeHtml(seedCpc[0])}</button>` : ''}${citing.length ? `<span style="font-size:11px;color:var(--muted)">Citing: ${citing.slice(0,5).map(id => `<a href="https://patents.google.com/patent/${id.replace(/[,\s]/g,'')}" target="_blank" rel="noopener" style="color:var(--accent);margin-right:4px">${id}</a>`).join('')}${citing.length > 5 ? ` +${citing.length-5} more` : ''}</span>` : ''}</div>${cited.length ? `<div style="margin-top:8px;font-size:11px;color:var(--muted)">Cited: ${cited.slice(0,5).map(id => `<a href="https://patents.google.com/patent/${id.replace(/[,\s]/g,'')}" target="_blank" rel="noopener" style="color:var(--accent);margin-right:4px">${id}</a>`).join('')}${cited.length > 5 ? ` +${cited.length-5} more` : ''}</div>` : ''}</div>`;} catch(e) {infoDiv.innerHTML = '<div style="color:var(--red);font-size:12px">Could not load seed patent data.</div>';}}function searchSeedCpc(cpcCode) {// Add the seed CPC code to search CPC codes and re-searchif (!state.selectedCpcCodes.includes(cpcCode)) {state.selectedCpcCodes.push(cpcCode);}state.saturation.searchesRun++;saveState();populateSearchPanel();runPriorArtSearch();}// βββ USPTO STEP 6: EXAMINER COMPARISON FRAMEWORK ββββββββββββββββββββββββββββasync function evaluatePatent(index) {if (state.evaluations[index]) {toggleEvaluation(index);return;}const evalDiv = document.getElementById(`eval-${index}`);if (!evalDiv) return;const pa = state.priorArt[index];if (!pa || !state.decomposition) {evalDiv.innerHTML = '<div style="color:var(--muted);font-size:12px;padding:12px 0">Run analysis in Step 1 first to enable evaluation.</div>';evalDiv.style.display = 'block';return;}evalDiv.innerHTML = '<div style="padding:12px 0;font-size:12px;color:var(--muted)"><div class="spinner spinner-accent" style="display:inline-block;vertical-align:middle;margin-right:8px;width:14px;height:14px;border-width:2px"></div>Evaluating against invention features...</div>';evalDiv.style.display = 'block';try {const response = await fetch(`${API_BASE}/api/evaluate-patent`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({invention_text: state.ideaText,patent: pa,decomposition: state.decomposition})});if (!response.ok) {const err = await response.json().catch(() => ({}));throw new Error(err.detail || 'Evaluation failed');}const data = await response.json();state.evaluations[index] = data;saveState();renderEvaluation(index, data);} catch(err) {evalDiv.innerHTML = `<div style="color:var(--red);font-size:12px;padding:12px 0">${escapeHtml(err.message)}</div>`;}}function statusIcon(val) {if (val === 'yes') return '<span style="color:#4ade80">✓</span>';if (val === 'partial') return '<span style="color:#facc15">~</span>';return '<span style="color:var(--muted)">✗</span>';}function renderEvaluation(index, data) {const evalDiv = document.getElementById(`eval-${index}`);if (!evalDiv) return;const threatColors = { high: 'red', medium: 'yellow', low: 'green' };const threatColor = threatColors[data.threat_level] || 'yellow';const comparisonRows = (data.feature_comparison || []).map(fc => `<tr><td style="padding:6px 8px;font-size:12px;border-bottom:1px solid var(--border)">${escapeHtml(fc.feature)}</td><td style="padding:6px 8px;text-align:center;border-bottom:1px solid var(--border)">${statusIcon(fc.disclosed)}</td><td style="padding:6px 8px;text-align:center;border-bottom:1px solid var(--border)">${statusIcon(fc.equivalent)}</td><td style="padding:6px 8px;text-align:center;border-bottom:1px solid var(--border)">${statusIcon(fc.same_solution)}</td><td style="padding:6px 8px;text-align:center;border-bottom:1px solid var(--border)">${statusIcon(fc.problem_only)}</td></tr>`).join('');evalDiv.innerHTML = `<div class="pa-evaluation" style="padding:16px 0;border-top:1px solid var(--border);margin-top:12px"><div style="display:flex;align-items:center;gap:12px;margin-bottom:12px"><span style="font-size:11px;letter-spacing:0.12em;text-transform:uppercase;color:var(--muted);font-weight:500">Examiner Comparison</span><span class="analysis-rating ${threatColor}">${escapeHtml(data.threat_level || 'unknown')} threat</span></div><div style="font-size:13px;color:rgba(237,240,255,0.8);margin-bottom:12px">${escapeHtml(data.overlap_summary || '')}</div><table style="width:100%;border-collapse:collapse;font-size:12px;color:var(--text)"><thead><tr style="color:var(--muted)"><th style="text-align:left;padding:6px 8px;border-bottom:1px solid var(--border)">Feature</th><th style="padding:6px 8px;border-bottom:1px solid var(--border)">Disclosed</th><th style="padding:6px 8px;border-bottom:1px solid var(--border)">Equivalent</th><th style="padding:6px 8px;border-bottom:1px solid var(--border)">Same Sol.</th><th style="padding:6px 8px;border-bottom:1px solid var(--border)">Prob. Only</th></tr></thead><tbody>${comparisonRows}</tbody></table>${data.distinguishing_features && data.distinguishing_features.length ? `<div style="margin-top:12px;font-size:12px"><strong style="color:var(--accent)">Distinguishing features:</strong>${data.distinguishing_features.map(f => `<span class="tag" style="margin:4px 4px 0 0">${escapeHtml(f)}</span>`).join('')}</div>` : ''}</div>`;evalDiv.style.display = 'block';}function toggleEvaluation(index) {const el = document.getElementById(`eval-${index}`);if (!el) return;el.style.display = el.style.display === 'none' ? 'block' : 'none';}// βββ USPTO STEP 7: SATURATION TRACKING ββββββββββββββββββββββββββββββββββββββfunction updateSaturation() {const s = state.saturation;if (s.searchesRun === 0) {document.getElementById('saturationBar').style.display = 'none';return;}document.getElementById('saturationBar').style.display = 'block';let score = 0;// Factor 1: Number of distinct searches run (max 30 points for 3+ searches)score += Math.min(30, s.searchesRun * 10);// Factor 2: How many boolean query levels exhausted (max 30 points)const uniqueExhausted = [...new Set(s.queriesExhausted)];score += Math.min(30, uniqueExhausted.length * 10);// Factor 3: Review coverage (max 20 points)const totalReviewed = Object.keys(state.evaluations).length + state.approvedArt.length;const totalResults = state.priorArt.length;if (totalResults > 0) score += Math.min(20, Math.round((totalReviewed / totalResults) * 20));// Factor 4: Having a seed patent (max 20 points)if (state.seedPatent !== null) score += 20;score = Math.min(100, score);document.getElementById('saturationPct').textContent = `${score}%`;document.getElementById('saturationFill').style.width = `${score}%`;let hint = '';if (score < 30) hint = 'Early stage \u2014 run broad and intermediate queries to establish baseline.';else if (score < 60) hint = 'Developing \u2014 try examiner-level queries and evaluate key results.';else if (score < 85) hint = 'Good coverage \u2014 use seed patent strategy and check diminishing returns.';else hint = 'Near saturation \u2014 search is likely comprehensive for this invention scope.';document.getElementById('saturationHint').textContent = hint;}// βββ RESTORE SESSION ON LOAD βββββββββββββββββββββββββββββββββββββββββββββββββfunction restoreSession() {loadState();5 unmodified linesrenderKeywords();if (state.cpcCodes && state.cpcCodes.length) renderCpcCodes();renderKindCodes();// Restore 7-step methodology sectionsif (state.decomposition) renderDecomposition();if (state.synonyms) renderSynonyms();document.getElementById('extractedSection').style.display = 'block';document.getElementById('analyzeBtn').innerHTML = 'β¦ Re-analyze';}