Spaces:
Sleeping
Sleeping
Add relevance scoring and AI-powered claim analysis
Browse files- Add client-side relevance score (0-100%) on patent search results based
on keyword matches in title/abstract and CPC code overlap
- Add "Most relevant" as default sort option with client-side reordering
- Add /api/analyze-claim endpoint using Gemini to evaluate claims across
three dimensions: specificity, protection scope, and potential infringements
- Display analysis as a 3-column card grid with color-coded ratings
- Persist analysis results in session storage across page reloads
- Loosen requirements.txt version pins for broader compatibility
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Files changed (3)
123456123456fastapi==0.123.5uvicorn==0.38.0httpx==0.28.1python-dotenv==1.2.1pydantic==2.12.5google-generativeai==0.8.6fastapi>=0.115uvicorn>=0.30httpx>=0.27python-dotenv>=1.0pydantic>=2.10google-generativeai>=0.844 unmodified lines4546474849505152535455219 unmodified lines27527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533644 unmodified lines invention_text: str prior_art: list[dict]
class ClaimAnalysisRequest(BaseModel): claims: str invention_text: str prior_art: list[dict]
# ββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
219 unmodified lines return {"claims": claim_text.strip()}
@app.post("/api/analyze-claim")async def analyze_claim(req: ClaimAnalysisRequest): """Analyze generated patent claims for specificity, protection scope, and potential infringements.""" prior_art_summary = "\n".join( f"- {p.get('patentNumber', 'N/A')}: \"{p.get('title', '')}\" ({p.get('assignee', '')}, {p.get('year', '')}): {p.get('abstract', '')}" for p in req.prior_art )
system_prompt = """You are a senior patent litigation attorney and patent prosecution strategist with 20+ years of experience. Analyze the given patent claims in the context of the invention description and relevant prior art.
Evaluate three dimensions:
1. SPECIFICITY β How specific and well-defined are the claim elements compared to the prior art? Consider whether the claims use precise technical language, clearly define boundaries, and differentiate from existing patents. Rate as "High" (claims are precisely scoped with clear technical boundaries), "Medium" (claims have reasonable specificity but some terms are broad), or "Low" (claims are vague or overlap significantly with prior art language).
2. PROTECTION SCOPE β How broad or narrow is the protection these claims would provide? Consider the independent claim's reach, whether dependent claims meaningfully narrow scope, and whether the claims cover the core inventive concept without being so broad as to be vulnerable to invalidation. Rate as "Broad" (wide protection covering many implementations), "Moderate" (balanced coverage of the inventive concept), or "Narrow" (limited to a very specific implementation).
3. POTENTIAL INFRINGEMENTS β What types of existing or future products, methods, systems, or services might fall within the scope of these claims? Consider both literal infringement and doctrine-of-equivalents scenarios. Rate the commercial relevance as "High" (large market, many potential infringers), "Medium" (niche market or moderate number of potential infringers), or "Low" (very narrow applicability).
Respond ONLY with valid JSON in this exact format, no markdown fences:{ "specificity": { "rating": "High or Medium or Low", "summary": "One sentence summarizing the specificity assessment.", "bullets": ["First key observation", "Second key observation", "Third key observation"] }, "protection": { "rating": "Broad or Moderate or Narrow", "summary": "One sentence summarizing the protection scope.", "bullets": ["First key observation", "Second key observation", "Third key observation"] }, "infringements": { "rating": "High or Medium or Low", "summary": "One sentence summarizing potential infringement landscape.", "bullets": ["First category of potentially infringing products/methods", "Second category", "Third category"] }}"""
user_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")
for key in ("specificity", "protection", "infringements"): if key not in parsed: raise HTTPException(502, f"Gemini response missing '{key}' section") section = parsed[key] if "rating" not in section or "summary" not in section or "bullets" not in section: raise HTTPException(502, f"Gemini response '{key}' section missing required fields")
return parsed
# ββ Serve the frontend βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
FRONTEND_DIR = os.path.join(os.path.dirname(__file__), "..")392 unmodified lines393394395396397398399400401402403404405406407408409410121 unmodified lines532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587120 unmodified lines70870971071171271371452 unmodified lines76776876977077177277377477577677777877978078178278378478578678778878979079170779279379471079579679779830 unmodified lines829830831832833834835322 unmodified lines1158115911601075116111621163116411654 unmodified lines1170117111721086117311741175117625 unmodified lines12021203120412051206120712081209121012111212121318 unmodified lines12321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125818 unmodified lines12771278127912801281128212831284128512861287128812891290139 unmodified lines143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151729 unmodified lines15471548154915501551155215531554155515561557392 unmodified lines text-decoration: underline; filter: brightness(1.2);}.pa-relevance { display: inline-block; font-family: var(--mono); font-size: 11px; font-weight: 600; padding: 2px 8px; border-radius: 4px; margin-bottom: 6px;}.pa-relevance.high { color: #4ade80; background: rgba(74,222,128,0.12); }.pa-relevance.medium { color: #facc15; background: rgba(250,204,21,0.12); }.pa-relevance.low { color: var(--muted); background: rgba(237,240,255,0.06); }.pa-meta { font-size: 12px; color: var(--muted); margin-bottom: 10px; font-weight: 300; }.pa-abstract { font-size: 13px; color: rgba(237,240,255,0.6); line-height: 1.55; font-weight: 300; }.pa-actions {121 unmodified lines
/* βββ COPY BUTTON FEEDBACK βββ */.copied { color: var(--accent) !important; }
/* βββ CLAIM ANALYSIS βββ */.analysis-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; margin-top: 16px;}@media (max-width: 768px) { .analysis-grid { grid-template-columns: 1fr; }}.analysis-card { background: var(--surface); border: 1px solid var(--border); border-radius: 14px; padding: 24px; transition: border-color 0.2s;}.analysis-card:hover { border-color: rgba(255,255,255,0.15); }.analysis-card-icon { font-size: 24px; margin-bottom: 12px; }.analysis-card-title { font-size: 11px; letter-spacing: 0.14em; text-transform: uppercase; color: var(--muted); font-weight: 500; margin-bottom: 10px;}.analysis-rating { display: inline-flex; align-items: center; font-size: 12px; font-weight: 600; font-family: var(--mono); padding: 4px 12px; border-radius: 20px; margin-bottom: 12px;}.analysis-rating.green { background: rgba(74,222,128,0.12); color: #4ade80; border: 1px solid rgba(74,222,128,0.3);}.analysis-rating.yellow { background: rgba(250,204,21,0.12); color: #facc15; border: 1px solid rgba(250,204,21,0.3);}.analysis-rating.red { background: rgba(255,71,87,0.12); color: var(--red); border: 1px solid rgba(255,71,87,0.3);}.analysis-summary { font-size: 13px; color: rgba(237,240,255,0.85); line-height: 1.5; font-weight: 400; margin-bottom: 14px;}.analysis-bullets { list-style: none; padding: 0; margin: 0; }.analysis-bullets li { font-size: 12px; color: rgba(237,240,255,0.6); line-height: 1.55; font-weight: 300; padding: 4px 0 4px 16px; position: relative;}.analysis-bullets li::before { content: '\2014'; position: absolute; left: 0; color: var(--muted);}</style></head><body>120 unmodified lines <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="relevance">Most relevant</option> <option value="date">Newest first</option> <option value="citations">Most cited first</option> </select>52 unmodified lines <div class="claim-content" id="claimContent" contenteditable="true"></div> </div>
<!-- Claim Analysis --> <div id="claimAnalysisWrap" style="display:none"> <div style="margin-top:28px;margin-bottom:8px;display:flex;align-items:center;justify-content:space-between"> <div style="font-family:var(--display);font-size:22px;letter-spacing:0.05em">Claim Analysis</div> <span class="status-badge done" id="analysisStatus" style="display:none">✓ Analysis Complete</span> </div> <div id="analysisGrid" class="analysis-grid"></div> </div>
<div id="claimAnalysisLoading" style="display:none;text-align:center;padding:40px;margin-top:20px" class="card"> <div style="display:flex;justify-content:center;margin-bottom:16px"> <div class="spinner spinner-accent" style="width:28px;height:28px;border-width:3px"></div> </div> <div style="color:var(--muted);font-size:13px">Analyzing claim specificity, protection scope, and infringement potential...</div> </div>
<div id="claimAnalysisError" style="display:none"></div>
<div style="margin-top:20px"> <button class="btn btn-secondary" id="analyzeClaimBtn" onclick="analyzeClaimDraft()">⚖ Analyze Claims</button> </div>
<div class="btn-row" style="margin-top:20px"> <div class="btn-row" style="margin-top:12px"> <button class="btn btn-primary" onclick="copyClaim(event)">Copy to Clipboard</button> <button class="btn btn-secondary" onclick="regenerateClaim()">Regenerate</button> <button class="btn btn-ghost" onclick="goToStep(2)">β Back to Prior Art</button> <button class="btn btn-ghost" onclick="goToStep(2)">← Back to Prior Art</button> </div> </div> </div>30 unmodified lines priorArt: [], approvedArt: [], claimDraft: '', claimAnalysis: null, currentStep: 1, searchAfter: null, searchTotal: 0,322 unmodified lines const keywords = getSearchKeywords(); const codes = state.selectedKindCodes; const cpcCodes = state.selectedCpcCodes || []; const sortBy = document.getElementById('sortSelect')?.value || 'date'; const sortBy = document.getElementById('sortSelect')?.value || 'relevance'; const apiSortBy = sortBy === 'relevance' ? 'date' : sortBy; const after = append ? state.searchAfter : null;
try {4 unmodified lines keywords, kind_codes: codes, cpc_codes: cpcCodes, sort_by: sortBy, sort_by: apiSortBy, after }) });25 unmodified lines }
if (!append) state.approvedArt = []; if (sortBy === 'relevance') { const kw = state.searchKeywords || keywords; state.priorArt.sort((a, b) => computeRelevanceScore(b, kw, cpcCodes) - computeRelevanceScore(a, kw, cpcCodes) ); } renderPriorArt(); document.getElementById('priorArtResults').style.display = 'block'; if (!append) document.getElementById('priorArtResults').scrollIntoView({ behavior: 'smooth' });18 unmodified lines return div.innerHTML;}
function computeRelevanceScore(patent, keywords, cpcCodes) { if (!keywords || keywords.length === 0) return 0; let score = 0; const title = (patent.title || '').toLowerCase(); const abstract = (patent.abstract || '').toLowerCase(); const seen = new Set(); keywords.forEach(kw => { if (!kw) return; const lower = kw.toLowerCase(); if (seen.has(lower)) return; seen.add(lower); if (title.includes(lower)) score += 15; if (abstract.includes(lower)) score += 5; }); if (cpcCodes && cpcCodes.length > 0 && patent.cpc) { const patentCpc = patent.cpc.toLowerCase(); if (cpcCodes.some(c => patentCpc.startsWith(c.toLowerCase()))) score += 15; } return Math.min(100, score);}
function highlightKeywords(text, keywords) { if (!text || !keywords || keywords.length === 0) return escapeHtml(text); let out = escapeHtml(text);18 unmodified lines const titleHtml = highlightKeywords(pa.title, keywords); const abstractHtml = highlightKeywords(pa.abstract, keywords); const patentId = (pa.patentNumber || '').replace(/[,\s\/]/g, ''); const score = computeRelevanceScore(pa, keywords, state.selectedCpcCodes || []); const scoreTier = score >= 70 ? 'high' : score >= 40 ? 'medium' : 'low'; 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-relevance ${scoreTier}">Relevance: ${score}%</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">139 unmodified lines });}
// βββ STEP 3: CLAIM ANALYSIS βββββββββββββββββββββββββββββββββββββββββββββββββasync function analyzeClaimDraft() { const claims = document.getElementById('claimContent').innerText.trim(); if (!claims) return;
const btn = document.getElementById('analyzeClaimBtn'); btn.disabled = true; btn.innerHTML = '<div class="spinner"></div> Analyzing...';
document.getElementById('claimAnalysisWrap').style.display = 'none'; document.getElementById('claimAnalysisError').style.display = 'none'; document.getElementById('claimAnalysisLoading').style.display = 'block';
const approvedPatents = state.approvedArt.map(i => state.priorArt[i]);
try { const response = await fetch(`${API_BASE}/api/analyze-claim`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ claims: claims, invention_text: state.ideaText, prior_art: approvedPatents }) }); 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.claimAnalysis = data; } catch(err) { document.getElementById('claimAnalysisLoading').style.display = 'none'; const errorWrap = document.getElementById('claimAnalysisError'); renderError(errorWrap, 'Claim analysis failed', err.message, analyzeClaimDraft); btn.disabled = false; btn.innerHTML = '⚖ Analyze Claims'; return; }
document.getElementById('claimAnalysisLoading').style.display = 'none'; renderClaimAnalysis(); saveState(); btn.disabled = false; btn.innerHTML = '⚖ Re-Analyze Claims';}
function ratingColor(section, rating) { const r = (rating || '').toLowerCase(); if (section === 'specificity') return r === 'high' ? 'green' : r === 'medium' ? 'yellow' : 'red'; if (section === 'protection') return r === 'broad' ? 'green' : r === 'moderate' ? 'yellow' : 'red'; if (section === 'infringements') return r === 'high' ? 'green' : r === 'medium' ? 'yellow' : 'red'; return 'yellow';}
function renderClaimAnalysis() { if (!state.claimAnalysis) return; const grid = document.getElementById('analysisGrid'); const data = state.claimAnalysis; const sections = [ { key: 'specificity', icon: '\uD83D\uDD0D', title: 'Specificity' }, { key: 'protection', icon: '\uD83D\uDEE1\uFE0F', title: 'Protection Scope' }, { key: 'infringements', icon: '\u26A0\uFE0F', title: 'Potential Infringements' } ]; grid.innerHTML = sections.map(s => { const section = data[s.key]; if (!section) return ''; const color = ratingColor(s.key, section.rating); const bullets = (section.bullets || []).map(b => `<li>${escapeHtml(b)}</li>`).join(''); return ` <div class="analysis-card"> <div class="analysis-card-icon">${s.icon}</div> <div class="analysis-card-title">${s.title}</div> <div class="analysis-rating ${color}">${escapeHtml(section.rating)}</div> <div class="analysis-summary">${escapeHtml(section.summary)}</div> <ul class="analysis-bullets">${bullets}</ul> </div>`; }).join(''); document.getElementById('claimAnalysisWrap').style.display = 'block'; document.getElementById('analysisStatus').style.display = 'inline-flex';}
// βββ RESTORE SESSION ON LOAD βββββββββββββββββββββββββββββββββββββββββββββββββfunction restoreSession() { loadState();29 unmodified lines document.getElementById('claimOutputWrap').style.display = 'block'; }
if (state.claimAnalysis) { renderClaimAnalysis(); document.getElementById('analyzeClaimBtn').innerHTML = '⚖ Re-Analyze Claims'; }
if (state.currentStep > 1) { goToStep(state.currentStep, { skipGenerate: true }); }backend/requirements.txt+6-6
backend/server.py+61
eddison-app.html+208-4