-
Notifications
You must be signed in to change notification settings - Fork 2
Add scraper for knowledge base solutions data #49
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| """Code for scraping Solutions data""" | ||
| import logging | ||
|
|
||
| from typing import List, Dict, TypedDict | ||
| from tqdm import tqdm | ||
|
|
||
|
|
||
| import pandas as pd | ||
|
|
||
| from data_scraper.core.scraper import Scraper | ||
| from data_scraper.processors.solutions_provider import SolutionsProvider | ||
|
|
||
|
|
||
| LOG = logging.getLogger(__name__) | ||
| LOG.setLevel(logging.INFO) | ||
|
|
||
|
|
||
| class SolutionsRecord(TypedDict): | ||
| """Represents a record extracted from Solutions""" | ||
| kb_id: str | ||
| kind: str | ||
| topic: str | ||
| url: str | ||
| issue: str | ||
| diagnosticsteps: str | ||
| text: str | ||
| components: list[str] | ||
|
|
||
|
|
||
| class SolutionsScraper(Scraper): | ||
| """Main class for Solutions scraping and processing.""" | ||
|
|
||
| def __init__(self, config: dict): | ||
| super().__init__(config=config) | ||
| self.config = config | ||
| self.kb_provider = SolutionsProvider( | ||
| self.config["solutions_url"], | ||
| self.config["solutions_token"] | ||
| ) | ||
|
|
||
| def get_documents(self) -> list[dict]: | ||
| documents = self.kb_provider.get_solutions( | ||
| self.config["product_name"], | ||
| self.config["max_results"]) | ||
| return documents | ||
|
|
||
| def get_records(self, documents: List[Dict]) -> list[SolutionsRecord]: | ||
| """Convert Solution API responses to SolutionsRecord""" | ||
| solutions_records: list[SolutionsRecord] = [] | ||
| for raw_result in tqdm(documents, desc="Processing issues"): | ||
| solutions_records.append( | ||
| { | ||
| "kb_id": raw_result.get('id', ''), | ||
| "url": raw_result.get('view_uri', ''), | ||
| "topic": raw_result.get('publishedTitle', ''), | ||
| "issue": ''.join(raw_result.get('issue', '')), | ||
| "diagnosticsteps": ''.join(raw_result.get('solution_diagnosticsteps', 'N/A')), | ||
| "text": ''.join(raw_result.get('solution_resolution', 'N/A')), | ||
| "components": raw_result.get('component', []), | ||
| "kind": "solution", | ||
| } | ||
| ) | ||
|
|
||
| return solutions_records | ||
|
|
||
| def get_chunks(self, record: dict) -> list[str]: | ||
| chunks = [] | ||
|
|
||
| for kb_field in ["topic", "issue"]: | ||
| chunks += self.text_processor.split_text(record[kb_field]) | ||
|
|
||
| return chunks | ||
|
|
||
| def record_postprocessing(self, record): | ||
| # Postprocessing is not required for Errata records | ||
| pass | ||
|
|
||
| def cleanup_records( | ||
| self, records: list, backup_path: str = "solutions_all_data.csv" | ||
| ) -> list: | ||
| df = pd.DataFrame(records) | ||
|
|
||
| LOG.info("Records stats BEFORE cleanup: %d", df.shape[0]) | ||
|
|
||
| df = df.dropna() | ||
| df = df.drop_duplicates(subset=["text"]) | ||
|
|
||
| LOG.info("Records stats AFTER cleanup: %d", df.shape[0]) | ||
|
|
||
| LOG.info("Saving backup to: %s", backup_path) | ||
| df.to_csv(backup_path) | ||
|
|
||
| return [SolutionsRecord(**row) for row in df.to_dict(orient="records")] | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| """Client to fetch Solutions.""" | ||
| import logging | ||
| import requests | ||
|
|
||
| LOG = logging.getLogger(__name__) | ||
| LOG.setLevel(logging.INFO) | ||
|
|
||
|
|
||
| # pylint: disable=too-few-public-methods | ||
| class SolutionsProvider: | ||
| """Provider for Solutions""" | ||
|
|
||
| def __init__(self, query_url: str, query_token: str): | ||
| self.query_url = query_url | ||
| self.headers = { | ||
| "Content-Type": "application/json", | ||
| "Authorization": f"Bearer {query_token}", | ||
| } | ||
|
|
||
| def get_solutions(self, product_name: str, | ||
| max_results: int, | ||
| start_at: int = 0) -> list[dict]: | ||
| """Get solutions from Knowledge Base. | ||
|
|
||
| Gets solutions from Knowledge Base and returns list of all the solutions and number | ||
| of retrieved records. | ||
|
|
||
| Args: | ||
| product_name: Search for Solutions for the specific product name | ||
| (e.g., product_name="*OpenStack*") | ||
| max_results: Maximum number of solutions that should be retrieved | ||
| start_at: Specifies a start page you want to download. | ||
| """ | ||
|
|
||
| url = f"{self.query_url}/hydra/rest/search/v2/kcs" | ||
|
|
||
| query = (f"fq=(documentKind:Solution AND product: *{product_name}* AND " | ||
| "solution_resolution:*)&sort=lastModifiedDate desc") | ||
|
|
||
| payload = { | ||
| "clientName": "cli", | ||
| "expression": query, | ||
| "q": "*", | ||
| "rows": max_results, | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is there no limit on how many rows you can fetch? Do you need to fetch them in batches?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, the API doesn't limit us. We can fetch all records at once
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I vaguely remember seeing some issues, but I see only 6823 solutions for https://access.redhat.com/search/?q=*&p=1&rows=10&documentKind=Solution&sort=lastModifiedDate+desc&product=Red+Hat+OpenStack+Platform, so we should be fine. |
||
| "start": start_at | ||
| } | ||
|
|
||
| LOG.info("Processing Solutions request [product: %s, max_results: %d, " | ||
| "start_at: %d]", query, max_results, start_at) | ||
|
|
||
| try: | ||
| response = requests.post( | ||
| url, | ||
| json=payload, | ||
| headers=self.headers, | ||
| verify=False, | ||
| timeout=(3.05, 180), | ||
| ) | ||
| except requests.exceptions.Timeout: | ||
| LOG.error("Request to Knowledge base %s timed out.", query) | ||
| return [{}] | ||
| except requests.exceptions.RequestException as e: | ||
| LOG.error("Error fetching KB data: %s", e) | ||
| return [{}] | ||
| parsed_response = response.json()['response'] | ||
| LOG.info("Found %d Solution records matching the query and retrieved %d " \ | ||
| "of them. [query: %s, max_results: %d, start_at: %d]", | ||
| parsed_response["numFound"], | ||
| len(parsed_response["docs"]), | ||
| query, max_results, start_at) | ||
|
|
||
| return parsed_response["docs"] | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Isn't there
root_causeandenvironmentfields as well?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I’m not sure how much insight it will give us, since only half of the solutions include this field, but it’s definitely room for experimentation