added new endpoint for keywords search
This commit is contained in:
@@ -14,6 +14,7 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c
|
||||
"httpx~=0.27.0" \
|
||||
"python-multipart~=0.0.19"\
|
||||
"elasticsearch~=9.4.0" \
|
||||
"beautifulsoup4==4.12.3" \
|
||||
"openai~=2.41.0"
|
||||
|
||||
COPY [ "src/main", "/home" ]
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Business logic for persons / authors.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
from inse.keywords.prompts import KeywordsPrompt
|
||||
from inse.integrations import llm
|
||||
from inse.keywords.model import ExtractedKeywords, ExtractedKeywordsResponse
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def extract_keywords(query: str, mode: str, limit: int) -> ExtractedKeywordsResponse:
|
||||
"""
|
||||
Extracts keywords from the given text or URL using a language model.
|
||||
"""
|
||||
start_time = time.time()
|
||||
if mode == "url":
|
||||
text = _get_text_content(query)
|
||||
system_prompt = KeywordsPrompt.EXTRACT_WEBSITE_KEYWORDS_PROMPT
|
||||
|
||||
else:
|
||||
system_prompt = KeywordsPrompt.EXTRACT_KEYWORDS_TEXT_PROMPT
|
||||
text = query
|
||||
|
||||
|
||||
system_prompt
|
||||
user_prompt = f"""
|
||||
Now analyze the following text and return ONLY the JSON object.\n"""
|
||||
|
||||
if limit:
|
||||
user_prompt +="Extract exactly {limit} keywords for each level (broad, coarse, fine) from the text below.\n"
|
||||
|
||||
user_prompt += f"""Input:{text}"""
|
||||
|
||||
keywords = llm.call(
|
||||
system_prompt=system_prompt,
|
||||
user_prompt=user_prompt,
|
||||
json_schema = ExtractedKeywords.model_json_schema(),
|
||||
schema_name = "extracted_keywords",
|
||||
temperature=0.8,
|
||||
top_p=0.95,
|
||||
)
|
||||
keywords_json = json.loads(keywords)
|
||||
|
||||
elapsed_time = time.time() - start_time
|
||||
logger.info(f"Keyword extraction took {elapsed_time:.2f} seconds")
|
||||
return ExtractedKeywordsResponse(results=keywords_json, source=mode, source_url=query if mode == "url" else None, source_content=text)
|
||||
|
||||
|
||||
def _get_text_content(url: str) -> str:
|
||||
"""
|
||||
Fetches the HTML content from the given URL using httpx and extracts visible text.
|
||||
"""
|
||||
try:
|
||||
headers = {
|
||||
"User-Agent": (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
||||
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
||||
"Chrome/91.0.4472.124 Safari/537.36"
|
||||
)
|
||||
}
|
||||
# Using a synchronous client (no 'async' needed)
|
||||
with httpx.Client(timeout=10.0) as client:
|
||||
response = client.get(url, headers=headers)
|
||||
response.raise_for_status()
|
||||
|
||||
soup = BeautifulSoup(response.text, "html.parser")
|
||||
for element in soup(["script", "style"]):
|
||||
element.decompose()
|
||||
|
||||
text = soup.get_text(separator=" ", strip=True)
|
||||
text = " ".join(text.split())
|
||||
return text
|
||||
|
||||
except httpx.HTTPError as e:
|
||||
logger.error(f"HTTP error for {url}: {e}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing {url}: {e}")
|
||||
return ""
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Data models for persons / authors.
|
||||
"""
|
||||
from pydantic import BaseModel
|
||||
from pydantic import Field
|
||||
from typing import List
|
||||
|
||||
class KeywordsRequest(BaseModel):
|
||||
query: str = Field(description="The input text from which to extract keywords.")
|
||||
mode: str = Field(description="The mode of keyword extraction, e.g., 'url', 'text', or 'keywords'.")
|
||||
limit: int = Field(default=None, description="The maximum number of keywords to extract.")
|
||||
|
||||
class KeywordEntry(BaseModel):
|
||||
keyword: str = Field(description="The extracted keyword.")
|
||||
relevance_score: float = Field(description="The relevance score of the keyword.")
|
||||
|
||||
class ExtractedKeywords(BaseModel):
|
||||
broad_keywords: List[KeywordEntry] = Field(description="The extracted broad keywords from text.")
|
||||
coarse_grained: List[KeywordEntry] = Field(description="The extracted coarse-grained keywords from text.")
|
||||
fine_grained: List[KeywordEntry] = Field(description="The extracted fine-grained keywords from text.")
|
||||
|
||||
class ExtractedKeywordsResponse(BaseModel):
|
||||
results: ExtractedKeywords = Field(description="The extracted keywords from the input text.")
|
||||
source: str = Field(description="The source of the input text, e.g., 'url', 'text', or 'keywords'.")
|
||||
source_url: str | None = Field(default=None, description="The URL from which keywords were extracted, if applicable.")
|
||||
source_content: str = Field(description="The actual content from which keywords were extracted.")
|
||||
|
||||
@@ -0,0 +1,490 @@
|
||||
from enum import StrEnum
|
||||
class KeywordsPrompt(StrEnum):
|
||||
EXTRACT_KEYWORDS_TEXT_PROMPT = """You are an expert scientific, technical, and innovation intelligence analyst.
|
||||
|
||||
Your task is to extract keywords from a given text and organize them into three hierarchical levels suitable for technology scouting, innovation discovery, scientific literature search, and OpenAlex-based research retrieval.
|
||||
|
||||
The extracted keywords should prioritize:
|
||||
|
||||
* Scientific domains
|
||||
* Technologies
|
||||
* Research fields
|
||||
* Methods
|
||||
* Applications
|
||||
* Materials
|
||||
* Standards
|
||||
* Diseases
|
||||
* Industrial sectors
|
||||
* Technical concepts
|
||||
|
||||
Avoid generic business terms unless they are core topics of the text.
|
||||
|
||||
Examples of terms to avoid:
|
||||
|
||||
* Solution
|
||||
* Platform
|
||||
* Improvement
|
||||
* Capability
|
||||
* Innovation
|
||||
* Process
|
||||
* Service
|
||||
* Performance
|
||||
* Efficiency
|
||||
|
||||
unless they represent an actual searchable concept.
|
||||
|
||||
---
|
||||
|
||||
# Keyword Hierarchy
|
||||
|
||||
## 1. broad_keywords
|
||||
|
||||
High-level domains, disciplines, industries, or technology areas.
|
||||
|
||||
Examples:
|
||||
|
||||
* Artificial Intelligence
|
||||
* Healthcare
|
||||
* Biotechnology
|
||||
* Renewable Energy
|
||||
* Materials Science
|
||||
* Robotics
|
||||
|
||||
These should represent the major themes of the document.
|
||||
|
||||
---
|
||||
|
||||
## 2. coarse_grained
|
||||
|
||||
Mid-level concepts, technologies, research areas, methods, or applications.
|
||||
|
||||
Examples:
|
||||
|
||||
* Machine Learning
|
||||
* Drug Discovery
|
||||
* Computer Vision
|
||||
* Predictive Maintenance
|
||||
* Smart Manufacturing
|
||||
* Gene Editing
|
||||
|
||||
These should provide more specific context within the broad domains.
|
||||
|
||||
---
|
||||
|
||||
## 3. fine_grained
|
||||
|
||||
Highly specific technical concepts, algorithms, materials, protocols, standards, tools, products, datasets, biomarkers, or specialized terminology.
|
||||
|
||||
Examples:
|
||||
|
||||
* Transformer Architecture
|
||||
* CRISPR-Cas9
|
||||
* Retrieval-Augmented Generation
|
||||
* Lithium Iron Phosphate
|
||||
* YOLOv8
|
||||
* OPC UA
|
||||
|
||||
These should be the most specific and actionable concepts for literature retrieval.
|
||||
|
||||
---
|
||||
|
||||
# Relevance Score
|
||||
|
||||
Each keyword must include a relevance score.
|
||||
|
||||
Definition:
|
||||
|
||||
* 1.0 = central concept of the text
|
||||
* 0.9 = extremely important concept
|
||||
* 0.8 = highly relevant concept
|
||||
* 0.7 = important supporting concept
|
||||
* 0.6 = relevant secondary concept
|
||||
* below 0.6 = use sparingly
|
||||
|
||||
Guidelines:
|
||||
|
||||
* Scores must be between 0.0 and 1.0.
|
||||
* Use decimal precision up to 2 digits.
|
||||
* Rank keywords by importance.
|
||||
* The most important keywords should appear first.
|
||||
* Broad keywords generally receive higher scores than secondary topics.
|
||||
* Only include keywords with meaningful relevance.
|
||||
|
||||
---
|
||||
|
||||
# Extraction Rules
|
||||
|
||||
* Extract only concepts explicitly mentioned or strongly implied.
|
||||
* Prefer noun phrases.
|
||||
* Avoid complete sentences.
|
||||
* Avoid duplicates across levels whenever possible.
|
||||
* Do not invent technologies not supported by the text.
|
||||
* Prefer terminology that can be searched in scientific literature databases such as OpenAlex.
|
||||
* Return between 5 and 15 keywords per level when sufficient information exists.
|
||||
|
||||
---
|
||||
|
||||
# Output Schema
|
||||
|
||||
Return ONLY valid JSON.
|
||||
|
||||
{
|
||||
"broad_keywords": [
|
||||
{
|
||||
"keyword": "string",
|
||||
"relevance_score": 0.0
|
||||
}
|
||||
],
|
||||
"coarse_grained": [
|
||||
{
|
||||
"keyword": "string",
|
||||
"relevance_score": 0.0
|
||||
}
|
||||
],
|
||||
"fine_grained": [
|
||||
{
|
||||
"keyword": "string",
|
||||
"relevance_score": 0.0
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
---
|
||||
|
||||
# Example 1
|
||||
|
||||
Input:
|
||||
|
||||
Researchers developed a transformer-based machine learning framework for predictive maintenance in industrial manufacturing. The system uses sensor fusion, anomaly detection, and time-series forecasting to reduce downtime in smart factories.
|
||||
|
||||
Output:
|
||||
|
||||
{
|
||||
"broad_keywords": [
|
||||
{
|
||||
"keyword": "Artificial Intelligence",
|
||||
"relevance_score": 0.98
|
||||
},
|
||||
{
|
||||
"keyword": "Manufacturing",
|
||||
"relevance_score": 0.94
|
||||
},
|
||||
{
|
||||
"keyword": "Industrial Automation",
|
||||
"relevance_score": 0.90
|
||||
}
|
||||
],
|
||||
"coarse_grained": [
|
||||
{
|
||||
"keyword": "Machine Learning",
|
||||
"relevance_score": 0.96
|
||||
},
|
||||
{
|
||||
"keyword": "Predictive Maintenance",
|
||||
"relevance_score": 0.95
|
||||
},
|
||||
{
|
||||
"keyword": "Smart Factories",
|
||||
"relevance_score": 0.88
|
||||
},
|
||||
{
|
||||
"keyword": "Sensor Fusion",
|
||||
"relevance_score": 0.86
|
||||
},
|
||||
{
|
||||
"keyword": "Anomaly Detection",
|
||||
"relevance_score": 0.85
|
||||
},
|
||||
{
|
||||
"keyword": "Time-Series Forecasting",
|
||||
"relevance_score": 0.83
|
||||
}
|
||||
],
|
||||
"fine_grained": [
|
||||
{
|
||||
"keyword": "Transformer Architecture",
|
||||
"relevance_score": 0.95
|
||||
},
|
||||
{
|
||||
"keyword": "Industrial Sensors",
|
||||
"relevance_score": 0.84
|
||||
},
|
||||
{
|
||||
"keyword": "Multimodal Data Fusion",
|
||||
"relevance_score": 0.82
|
||||
},
|
||||
{
|
||||
"keyword": "Predictive Analytics",
|
||||
"relevance_score": 0.80
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
---
|
||||
|
||||
# Example 2
|
||||
|
||||
Input:
|
||||
|
||||
A healthcare platform uses large language models and retrieval-augmented generation to automatically summarize patient records and support clinical decision-making.
|
||||
|
||||
Output:
|
||||
|
||||
{
|
||||
"broad_keywords": [
|
||||
{
|
||||
"keyword": "Healthcare",
|
||||
"relevance_score": 0.97
|
||||
},
|
||||
{
|
||||
"keyword": "Artificial Intelligence",
|
||||
"relevance_score": 0.95
|
||||
},
|
||||
{
|
||||
"keyword": "Digital Health",
|
||||
"relevance_score": 0.89
|
||||
}
|
||||
],
|
||||
"coarse_grained": [
|
||||
{
|
||||
"keyword": "Large Language Models",
|
||||
"relevance_score": 0.96
|
||||
},
|
||||
{
|
||||
"keyword": "Clinical Decision Support",
|
||||
"relevance_score": 0.92
|
||||
},
|
||||
{
|
||||
"keyword": "Medical Record Analysis",
|
||||
"relevance_score": 0.90
|
||||
},
|
||||
{
|
||||
"keyword": "Natural Language Processing",
|
||||
"relevance_score": 0.88
|
||||
}
|
||||
],
|
||||
"fine_grained": [
|
||||
{
|
||||
"keyword": "Retrieval-Augmented Generation",
|
||||
"relevance_score": 0.95
|
||||
},
|
||||
{
|
||||
"keyword": "Patient Record Summarization",
|
||||
"relevance_score": 0.91
|
||||
},
|
||||
{
|
||||
"keyword": "Clinical Documentation",
|
||||
"relevance_score": 0.86
|
||||
},
|
||||
{
|
||||
"keyword": "Medical Text Processing",
|
||||
"relevance_score": 0.84
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
---
|
||||
"""
|
||||
|
||||
|
||||
EXTRACT_WEBSITE_KEYWORDS_PROMPT = """
|
||||
You are an expert technology scout, scientific analyst, and innovation intelligence specialist.
|
||||
|
||||
The input text was extracted automatically from a webpage using BeautifulSoup or a similar HTML parser.
|
||||
|
||||
The extracted text may contain:
|
||||
|
||||
* Navigation menus
|
||||
* Headers and footers
|
||||
* Cookie notices
|
||||
* Marketing language
|
||||
* Contact information
|
||||
* Repeated sections
|
||||
* Calls to action
|
||||
* Legal disclaimers
|
||||
* Product pages
|
||||
* Blog articles
|
||||
* News articles
|
||||
* Landing pages
|
||||
|
||||
Your first task is to identify the actual content and purpose of the webpage.
|
||||
|
||||
Ignore:
|
||||
|
||||
* Navigation elements
|
||||
* Cookie banners
|
||||
* Legal notices
|
||||
* Copyright text
|
||||
* Generic marketing statements
|
||||
* Contact information
|
||||
* Login/signup content
|
||||
* Careers pages unless they contain relevant technical information
|
||||
* Repeated website boilerplate
|
||||
|
||||
Focus only on content that helps identify:
|
||||
|
||||
* Technologies
|
||||
* Scientific concepts
|
||||
* Research areas
|
||||
* Technical methods
|
||||
* Products
|
||||
* Applications
|
||||
* Industrial sectors
|
||||
* Materials
|
||||
* Standards
|
||||
* Diseases
|
||||
* Engineering disciplines
|
||||
* Innovation domains
|
||||
|
||||
---
|
||||
|
||||
# Step 1: Determine Page Type
|
||||
|
||||
Determine which type of page is represented:
|
||||
|
||||
* Technology/Product Page
|
||||
* Company Page
|
||||
* Research Article
|
||||
* Scientific Blog Post
|
||||
* News Article
|
||||
* Technical Documentation
|
||||
* White Paper
|
||||
* Industry Report
|
||||
* Other
|
||||
|
||||
Use this classification internally only.
|
||||
|
||||
Do not include it in the output.
|
||||
|
||||
---
|
||||
|
||||
# Step 2: Extract Searchable Concepts
|
||||
|
||||
Prioritize concepts that are useful for:
|
||||
|
||||
* OpenAlex retrieval
|
||||
* Scientific literature discovery
|
||||
* Patent scouting
|
||||
* Technology scouting
|
||||
* Innovation monitoring
|
||||
|
||||
Prefer canonical scientific terminology over marketing language.
|
||||
|
||||
Examples:
|
||||
|
||||
Prefer:
|
||||
|
||||
* Large Language Models
|
||||
|
||||
Instead of:
|
||||
|
||||
* AI Assistant
|
||||
|
||||
Prefer:
|
||||
|
||||
* Smart Manufacturing
|
||||
|
||||
Instead of:
|
||||
|
||||
* Factory Optimization Solution
|
||||
|
||||
Prefer:
|
||||
|
||||
* Retrieval-Augmented Generation
|
||||
|
||||
Instead of:
|
||||
|
||||
* Intelligent Knowledge Assistant
|
||||
|
||||
Prefer:
|
||||
|
||||
* Predictive Maintenance
|
||||
|
||||
Instead of:
|
||||
|
||||
* Equipment Performance Optimization
|
||||
|
||||
---
|
||||
|
||||
# Keyword Hierarchy
|
||||
|
||||
## broad_keywords
|
||||
|
||||
High-level domains, industries, disciplines, or technology areas.
|
||||
|
||||
Examples:
|
||||
|
||||
* Artificial Intelligence
|
||||
* Healthcare
|
||||
* Manufacturing
|
||||
* Energy Storage
|
||||
* Biotechnology
|
||||
* Robotics
|
||||
|
||||
---
|
||||
|
||||
## coarse_grained
|
||||
|
||||
Technologies, methods, research fields, and applications.
|
||||
|
||||
Examples:
|
||||
|
||||
* Machine Learning
|
||||
* Predictive Maintenance
|
||||
* Drug Discovery
|
||||
* Smart Manufacturing
|
||||
* Computer Vision
|
||||
* Clinical Decision Support
|
||||
|
||||
---
|
||||
|
||||
## fine_grained
|
||||
|
||||
Specific technical concepts, algorithms, materials, standards, tools, products, datasets, biomarkers, or protocols.
|
||||
|
||||
Examples:
|
||||
|
||||
* Transformer Architecture
|
||||
* CRISPR-Cas9
|
||||
* OPC UA
|
||||
* Retrieval-Augmented Generation
|
||||
* YOLOv8
|
||||
* Lithium Iron Phosphate
|
||||
|
||||
---
|
||||
|
||||
# Relevance Score
|
||||
|
||||
Assign a relevance score between 0.0 and 1.0.
|
||||
|
||||
Guidelines:
|
||||
|
||||
* 1.00 = central topic of the webpage
|
||||
* 0.90 = major topic
|
||||
* 0.80 = highly relevant
|
||||
* 0.70 = supporting concept
|
||||
* 0.60 = secondary concept
|
||||
|
||||
Avoid scores below 0.60 unless necessary.
|
||||
|
||||
---
|
||||
|
||||
# Additional Rules
|
||||
|
||||
* Extract only concepts supported by the page content.
|
||||
* Do not hallucinate technologies.
|
||||
* Avoid generic company descriptions.
|
||||
* Avoid generic business terminology.
|
||||
* Prefer terminology suitable for scientific literature search.
|
||||
* Prefer concepts that could appear in OpenAlex, patents, technical reports, or academic publications.
|
||||
* Remove duplicates across hierarchy levels whenever possible.
|
||||
* Rank keywords by importance.
|
||||
|
||||
---
|
||||
|
||||
Return ONLY valid JSON matching the schema provided by the API.
|
||||
|
||||
The following text was extracted from a webpage:
|
||||
|
||||
{{PAGE_CONTENT}}
|
||||
"""
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
REST API for persons / authors.
|
||||
"""
|
||||
|
||||
from typing import Annotated
|
||||
from fastapi import Body
|
||||
from fastapi import APIRouter
|
||||
from . import logic
|
||||
from inse.keywords.model import ExtractedKeywordsResponse, KeywordsRequest
|
||||
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/api/inse-service",
|
||||
tags=["Keywords"],
|
||||
responses={404: {"description": "Not found"}},
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/keywords/extract",
|
||||
operation_id="extractKeywords",
|
||||
response_model=ExtractedKeywordsResponse,
|
||||
summary="Extracts keywords from text.",
|
||||
response_model_exclude_none=True,
|
||||
)
|
||||
def extract_keywords(
|
||||
request: Annotated[
|
||||
KeywordsRequest,
|
||||
Body(description="Input text for keyword extraction")
|
||||
],
|
||||
|
||||
):
|
||||
return logic.extract_keywords(query=request.query, mode=request.mode, limit=request.limit)
|
||||
@@ -29,6 +29,7 @@ from inse.funders.service import router as funders_service_router
|
||||
from inse.news.service import router as news_service_router
|
||||
from inse.projects.router import router as projects_router
|
||||
from inse.patents.service import router as patents_service_router
|
||||
from inse.keywords.service import router as keywords_service_router
|
||||
|
||||
from inse.institutions.router import router as institutions_router
|
||||
from . import config
|
||||
@@ -63,6 +64,7 @@ app.include_router(patents_service_router)
|
||||
app.include_router(university_ranking_router)
|
||||
app.include_router(projects_router)
|
||||
app.include_router(patents_all_router)
|
||||
app.include_router(keywords_service_router)
|
||||
|
||||
app.add_middleware(
|
||||
ETagCacheMiddleware,
|
||||
|
||||
Reference in New Issue
Block a user