|
| 1 | +from ._base import * |
| 2 | + |
| 3 | +from .filters import GDELTFilters |
| 4 | +from .models import GDELTArticle |
| 5 | + |
| 6 | +class GDELTFormat(Enum): |
| 7 | + dict = 'dict' |
| 8 | + obj = 'obj' |
| 9 | + json = 'json' |
| 10 | + pandas = 'pd' |
| 11 | + |
| 12 | + |
| 13 | +class GDELTMethods(Enum): |
| 14 | + article = 'article' |
| 15 | + timeline = 'timeline' |
| 16 | + |
| 17 | +class GDELT: |
| 18 | + api_url = 'https://api.gdeltproject.org/api/v2/doc/doc' |
| 19 | + available_modes = ["artlist", "timelinevol", "timelinevolraw", "timelinetone", "timelinelang", "timelinesourcecountry"] |
| 20 | + |
| 21 | + def __init__(self, result_format: GDELTFormat = GDELTFormat.obj, json_parsing_max_depth: int = 100, *args, **kwargs) -> None: |
| 22 | + self.max_depth_json_parsing = json_parsing_max_depth |
| 23 | + self._output_format = result_format |
| 24 | + self.sess = LazySession() |
| 25 | + |
| 26 | + def return_article_result(self, articles: Dict = None): |
| 27 | + if not articles or not articles.get('articles'): |
| 28 | + return None |
| 29 | + if self._output_format.value == 'dict': |
| 30 | + return articles['articles'] |
| 31 | + |
| 32 | + if self._output_format.value == 'pd': |
| 33 | + return pd.DataFrame(articles["articles"]) |
| 34 | + |
| 35 | + if self._output_format.value == 'json': |
| 36 | + return LazyJson.dumps(articles['articles']) |
| 37 | + |
| 38 | + if self._output_format.value == 'obj': |
| 39 | + return [GDELTArticle(**article) for article in articles['articles']] |
| 40 | + |
| 41 | + def return_timeline_search(self, results: Dict = None): |
| 42 | + if not results: |
| 43 | + return None |
| 44 | + |
| 45 | + if self._output_format.value == 'dict': |
| 46 | + return results |
| 47 | + |
| 48 | + if self._output_format.value == 'pd': |
| 49 | + formatted = pd.DataFrame(results) |
| 50 | + formatted["datetime"] = pd.to_datetime(formatted["datetime"]) |
| 51 | + return formatted |
| 52 | + |
| 53 | + if self._output_format.value == 'json': |
| 54 | + return LazyJson.dumps(results) |
| 55 | + |
| 56 | + if self._output_format.value == 'obj': |
| 57 | + return [LazyObject(res) for res in results] |
| 58 | + |
| 59 | + |
| 60 | + def article_search(self, filters: GDELTFilters) -> Union[pd.DataFrame, Dict, str]: |
| 61 | + articles = self._query("artlist", filters.query_string) |
| 62 | + return self.return_article_result(articles) |
| 63 | + |
| 64 | + def timeline_search(self, mode: str, filters: GDELTFilters) -> Union[pd.DataFrame, Dict, str]: |
| 65 | + timeline = self._query(mode, filters.query_string) |
| 66 | + results = {"datetime": [entry["date"] for entry in timeline["timeline"][0]["data"]]} |
| 67 | + for series in timeline["timeline"]: |
| 68 | + results[series["series"]] = [entry["value"] for entry in series["data"]] |
| 69 | + |
| 70 | + if mode == "timelinevolraw": results["All Articles"] = [entry["norm"] for entry in timeline["timeline"][0]["data"]] |
| 71 | + return self.return_timeline_search(results) |
| 72 | + |
| 73 | + def search(self, method: GDELTMethods, filters: GDELTFilters) -> Union[pd.DataFrame, Dict, str]: |
| 74 | + if method.value == 'article': |
| 75 | + return self.article_search(filters) |
| 76 | + if method.value == 'timeline': |
| 77 | + return self.timeline_search(filters) |
| 78 | + |
| 79 | + async def async_search(self, method: GDELTMethods, filters: GDELTFilters) -> Union[pd.DataFrame, Dict, str]: |
| 80 | + if method.value == 'article': |
| 81 | + return await self.async_article_search(filters) |
| 82 | + if method.value == 'timeline': |
| 83 | + return await self.async_timeline_search(filters) |
| 84 | + |
| 85 | + async def async_article_search(self, filters: GDELTFilters) -> Union[pd.DataFrame, Dict, str]: |
| 86 | + articles = await self._async_query("artlist", filters.query_string) |
| 87 | + return self.return_article_result(articles) |
| 88 | + |
| 89 | + async def async_timeline_search(self, mode: str, filters: GDELTFilters) -> Union[pd.DataFrame, Dict, str]: |
| 90 | + timeline = await self._async_query(mode, filters.query_string) |
| 91 | + results = {"datetime": [entry["date"] for entry in timeline["timeline"][0]["data"]]} |
| 92 | + for series in timeline["timeline"]: |
| 93 | + results[series["series"]] = [entry["value"] for entry in series["data"]] |
| 94 | + |
| 95 | + if mode == "timelinevolraw": results["All Articles"] = [entry["norm"] for entry in timeline["timeline"][0]["data"]] |
| 96 | + return self.return_timeline_search(results) |
| 97 | + |
| 98 | + def _decode_json(cls, content, max_recursion_depth: int = 100, recursion_depth: int = 0): |
| 99 | + try: |
| 100 | + result = LazyJson.loads(content, recursive=True) |
| 101 | + except Exception as e: |
| 102 | + if recursion_depth >= max_recursion_depth: |
| 103 | + raise ValueError("Max Recursion depth is reached. JSON can´t be parsed!") |
| 104 | + idx_to_replace = int(e.pos) |
| 105 | + if isinstance(content, bytes): content.decode("utf-8") |
| 106 | + json_message = list(content) |
| 107 | + json_message[idx_to_replace] = ' ' |
| 108 | + new_message = ''.join(str(m) for m in json_message) |
| 109 | + return GDELT._decode_json(content=new_message, max_recursion_depth=max_recursion_depth, recursion_depth=recursion_depth+1) |
| 110 | + return result |
| 111 | + |
| 112 | + async def _async_decode_json(cls, content, max_recursion_depth: int = 100, recursion_depth: int = 0): |
| 113 | + try: |
| 114 | + result = LazyJson.loads(content, recursive=True) |
| 115 | + except Exception as e: |
| 116 | + if recursion_depth >= max_recursion_depth: |
| 117 | + raise ValueError("Max Recursion depth is reached. JSON can´t be parsed!") |
| 118 | + idx_to_replace = int(e.pos) |
| 119 | + if isinstance(content, bytes): content.decode("utf-8") |
| 120 | + json_message = list(content) |
| 121 | + json_message[idx_to_replace] = ' ' |
| 122 | + new_message = ''.join(str(m) for m in json_message) |
| 123 | + return await GDELT._async_decode_json(content=new_message, max_recursion_depth=max_recursion_depth, recursion_depth=recursion_depth+1) |
| 124 | + return result |
| 125 | + |
| 126 | + def _query(self, mode: str, query_string: str) -> Dict: |
| 127 | + if mode not in GDELT.available_modes: |
| 128 | + raise ValueError(f"Mode {mode} not in supported API modes") |
| 129 | + resp = self.sess.fetch(url=GDELT.api_url, decode_json=False, method='GET', params={'query': query_string, 'mode': mode, 'format': 'json'}) |
| 130 | + if resp.status_code not in [200, 202]: |
| 131 | + raise ValueError("The gdelt api returned a non-successful status code. This is the response message: {}".format(resp.text)) |
| 132 | + return self._decode_json(resp.content, max_recursion_depth=self.max_depth_json_parsing) |
| 133 | + |
| 134 | + async def _async_query(self, mode: str, query_string: str) -> Dict: |
| 135 | + if mode not in GDELT.available_modes: |
| 136 | + raise ValueError(f"Mode {mode} not in supported API modes") |
| 137 | + resp = await self.sess.async_fetch(url=GDELT.api_url, decode_json=False, method='GET', params={'query': query_string, 'mode': mode, 'format': 'json'}) |
| 138 | + if resp.status_code not in [200, 202]: |
| 139 | + raise ValueError("The gdelt api returned a non-successful status code. This is the response message: {}".format(resp.text)) |
| 140 | + return await self._async_decode_json(resp.content, max_recursion_depth=self.max_depth_json_parsing) |
| 141 | + |
0 commit comments