-
Notifications
You must be signed in to change notification settings - Fork 181
Initial PR to add support for stackoverflow teams #78
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
Open
allen-munsch
wants to merge
11
commits into
GerevAI:main
Choose a base branch
from
allen-munsch:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 6 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
2b33e4f
initial attempt to add stackoverflow support
dfebfad
initial attempt to add stackoverflow support
6d0b810
initial attempt to add stackoverflow support
1f73af8
test the download, add the help text to the data-source-panel.tsx
dd575dc
test the download, add the help text to the data-source-panel.tsx, up…
036e7e5
comment out the test function
e52ec76
try to address code review, move io bound to queue, check for last in…
5f14fc3
rate limit the requests
05ae7c9
add a rate limiter
ec910fa
wire up async sqlite, add rate limiter, fix rendering issues on DataS…
1e4f56e
Merge branch 'main' into main
allen-munsch File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
import logging | ||
from dataclasses import dataclass | ||
from datetime import datetime | ||
from typing import Dict, List, Optional | ||
import requests | ||
|
||
from data_source.api.base_data_source import BaseDataSource, ConfigField, HTMLInputType, BaseDataSourceConfig | ||
from data_source.api.basic_document import DocumentType, BasicDocument | ||
from queues.index_queue import IndexQueue | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
endpoints = [ | ||
'posts', | ||
'articles', | ||
] | ||
|
||
|
||
@dataclass | ||
class StackOverflowPost: | ||
post_id: int | ||
post_type: str | ||
link: str | ||
body_markdown: str | ||
score: int | ||
last_activity_date: int | ||
creation_date: int | ||
owner_account_id: Optional[int] = None | ||
owner_reputation: Optional[int] = None | ||
owner_user_id: Optional[int] = None | ||
owner_user_type: Optional[str] = None | ||
owner_profile_image: Optional[str] = None | ||
owner_display_name: Optional[str] = None | ||
owner_link: Optional[str] = None | ||
title: Optional[str] = None | ||
last_edit_date: Optional[str] = None | ||
|
||
class StackOverflowConfig(BaseDataSourceConfig): | ||
api_key: str | ||
team_name: str | ||
|
||
|
||
class StackOverflowDataSource(BaseDataSource): | ||
|
||
@staticmethod | ||
def get_config_fields() -> List[ConfigField]: | ||
return [ | ||
ConfigField(label="PAT API Key", name="api_key", type=HTMLInputType.TEXT), | ||
ConfigField(label="Team Name", name="team_name", type=HTMLInputType.TEXT), | ||
] | ||
|
||
@staticmethod | ||
def validate_config(config: Dict) -> None: | ||
so_config = StackOverflowConfig(**config) | ||
StackOverflowDataSource._fetch_posts(so_config.api_key, so_config.team_name, 1, 'posts') | ||
|
||
def __init__(self, *args, **kwargs): | ||
super().__init__(*args, **kwargs) | ||
so_config = StackOverflowConfig(**self._raw_config) | ||
self._api_key = so_config.api_key | ||
self._team_name = so_config.team_name | ||
|
||
@staticmethod | ||
def _fetch_posts(api_key: str, team_name: str, page: int, doc_type: str) -> Dict: | ||
url = f'https://api.stackoverflowteams.com/2.3/{doc_type}?team={team_name}&filter=!nOedRLbqzB&page={page}' | ||
response = requests.get(url, headers={'X-API-Access-Token': api_key}) | ||
response.raise_for_status() | ||
return response.json() | ||
|
||
def _feed_new_documents(self) -> None: | ||
page = 1 | ||
has_more = True | ||
for doc_type in endpoints: | ||
while has_more: | ||
response = self._fetch_posts(self._api_key, self._team_name, page, doc_type) | ||
posts = response['items'] | ||
logger.info(f'Fetched {len(posts)} posts from Stack Overflow') | ||
for post_dict in posts: | ||
owner_fields = {} | ||
if 'owner' in post_dict: | ||
owner_fields = {f"owner_{k}": v for k, v in post_dict.pop('owner').items()} | ||
if 'title' not in post_dict: | ||
post_dict['title'] = post_dict['link'] | ||
post = StackOverflowPost(**post_dict, **owner_fields) | ||
self.add_task_to_queue(self._feed_post, post=post) | ||
has_more = response['has_more'] | ||
page += 1 | ||
|
||
def _feed_post(self, post: StackOverflowPost) -> None: | ||
logger.info(f'Feeding post {post.title}') | ||
post_document = BasicDocument(title=post.title, content=post.body_markdown, author=post.owner_display_name, | ||
timestamp=datetime.fromtimestamp(post.creation_date), id=post.post_id, | ||
data_source_id=self._data_source_id, location=post.link, | ||
url=post.link, author_image_url=post.owner_profile_image, | ||
type=DocumentType.MESSAGE) | ||
IndexQueue.get_instance().put_single(doc=post_document) | ||
allen-munsch marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
# def test(): | ||
# import os | ||
# config = {"api_key": os.environ['SO_API_KEY'], "team_name": os.environ['SO_TEAM_NAME']} | ||
# so = StackOverflowDataSource(config=config, data_source_id=0) | ||
# so._feed_new_documents() | ||
# | ||
# | ||
# if __name__ == '__main__': | ||
# test() |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.