Skip to content

Commit

Permalink
EDIT: make examples consisten with the latest package update + improv…
Browse files Browse the repository at this point in the history
…e code quality
  • Loading branch information
vdmitriyev committed Mar 4, 2024
1 parent dd5b2fc commit 4f47d0c
Show file tree
Hide file tree
Showing 17 changed files with 328 additions and 225 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
dist/*
orcidpyclient.egg-info/*
docs/_build/*
generated/*

# extensions
*.pyc
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ A simple wrapper around the orcid.org API. Ready to run examples can be found in

Install latest relased version
```
pip install -i https://test.pypi.org/simple/ orcidpyclient
pip install -i https://test.pypi.org/simple/ orcidpyclient --upgrade
```

Install latest version from source code
Expand Down
9 changes: 9 additions & 0 deletions docs/core.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,15 @@ for key_word in orcid_res.keywords:
print (key_word)
```

#### Iterate over publications

```python
import orcidpyclient
orcid_res = orcidpyclient.get('0000-0002-4510-0385')
for value in obj.publications:
print(value)
```

#### Trying different author with a different ORCID

```python
Expand Down
9 changes: 6 additions & 3 deletions docs/examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@
* Additional information
+ iterates through the list or ID's, extracts ORCID, creates bat file to compile bibtex into HTMLs with help of JabRef
- List should be in the python dict format, here is the example (I created file 'orcid-list.json')
```
```json
[
{ 'John Wilbanks' : '0000-0002-4510-0385'},
]
{
"name": "John Wilbanks",
"orcid": "0000-0002-4510-0385"
}
]
```
+ **NOTE**: To make in run on Mac OS, it's better if you will copy JabRef into the 'generated' folder directly

Expand Down
47 changes: 23 additions & 24 deletions docs/examples/extracting_bibtex.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,28 @@
import logging
import os

import orcidpyclient as orcid
try:
import orcidpyclient
except:

logging.getLogger(__name__).setLevel(logging.INFO)

# retrieve a profile from his ORCID
me = orcid.get("0000-0001-5661-4587")

TARGET_FODLER = "generated"
import os
import sys
from pathlib import Path

current_path = Path(os.path.abspath(os.path.dirname(__file__)))
_path_to_add = os.path.join(str(current_path.parent.parent))
print(f"[i] Try following path to load package: {_path_to_add})")
sys.path.append(_path_to_add)

def print_keyword(obj):
"""Printing author keywords"""
import orcidpyclient

print("[i] printing author keywords")
for key_word in obj.keywords:
print(key_word)
print(f"[i] Use dev version of package with version")


def print_publications(obj):
"""Printing author publications"""
logging.getLogger(__name__).setLevel(logging.INFO)

print("[i] printing author publications")
for value in obj.publications:
print(value)
TARGET_FODLER = "generated"
ORCID_ID = "0000-0001-5661-4587"


def save_bibtex(bibtex, file_name="orcid-bibtex-output.bib", encoding="utf-8"):
Expand Down Expand Up @@ -88,19 +86,19 @@ def extract_bibtex(obj):

bibtex = {}
for value in obj.publications:
if value.citation_type == "BIBTEX":
if value.citation_type.lower() == "bibtex":
if value.publicationyear not in bibtex:
bibtex[value.publicationyear] = list()
bibtex[value.publicationyear].append(value.citation_value)
else:
bibtex[value.publicationyear].append(value.citation_value)
else:
print("[i] this publications is having no BIBTEX {0}".format(value))
print("[i] this publications is having NO BibTeX {0}".format(value))

return bibtex


def orcid_bibtex(obj):
def extract_bibtex_orcid(orcid_profile):
"""
(Class) -> None
Expand All @@ -111,7 +109,7 @@ def orcid_bibtex(obj):
os.makedirs(TARGET_FODLER)

# extracting bibtex
orcid_bibtex = extract_bibtex(me)
orcid_bibtex = extract_bibtex(orcid_profile)

# saving bibtex to file
save_bibtex(orcid_bibtex)
Expand All @@ -120,6 +118,7 @@ def orcid_bibtex(obj):
save_nocite(orcid_bibtex)


# print_keyword(me)
# print_publications(me)
orcid_bibtex(me)
if __name__ == "__main__":
# retrieve a profile from his ORCID
orcid_profile = orcidpyclient.get(ORCID_ID, debug=False)
extract_bibtex_orcid(orcid_profile)
44 changes: 32 additions & 12 deletions docs/examples/orcid_bibtex_to_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,23 @@
import traceback
import uuid

import orcidpyclient as orcid
try:
import orcidpyclient
except:

import os
import sys
from pathlib import Path

current_path = Path(os.path.abspath(os.path.dirname(__file__)))
_path_to_add = os.path.join(str(current_path.parent.parent))

print(f"[i] Try following path to load package: {_path_to_add})")
sys.path.append(_path_to_add)

import orcidpyclient

print(f"[i] Use dev version of package with version")

logging.getLogger(__name__).setLevel(logging.INFO)

Expand Down Expand Up @@ -160,7 +176,7 @@ def extract_bitex(obj, author):
for value in obj.publications:
try:
if hasattr(value, "citation_type"):
if value.citation_type == "BIBTEX":
if value.citation_type.lower() == "bibtex":
if value.publicationyear not in bibtex:
bibtex[value.publicationyear] = list()
bibtex[value.publicationyear].append(value.citation_value)
Expand All @@ -184,7 +200,8 @@ def extract_bitex(obj, author):
return bibtex


def load_list(fname: str = "orcid-list.json"):
def load_list(fname: str):

if not os.path.exists(fname):
raise Exception("JSON file was not found: {fname}")

Expand All @@ -200,12 +217,15 @@ def main():
Extrating bibtex from ORCID, saving it to the file
"""

orcid_file_name_ = "orcid-list.json"
separate_by_year = False
try:
orcid_list = load_list()
except:
print("No py file with ORCIDS to work with was found")
orcid_list = load_list(fname=orcid_file_name_)
print(orcid_list)
except Exception as ex:
print(f"[e] JSON file with ORCIDs was NOT found: {orcid_file_name_}")
_, _, ex_traceback = sys.exc_info()
log_traceback(ex, ex_traceback)
exit(0)

orcid_extracted = list()
Expand All @@ -215,13 +235,12 @@ def main():

years = {}
# extracting bibtex
for key in orcid_list:
for item in orcid_list:

name = key
name, orcidid = item["name"], item["orcid"]
years[name] = list()
orcidid = orcid_list[key]
print("[i] extracting bibtex for {0}".format(name))
orcid_obj = orcid.get(orcidid)
orcid_obj = orcidpyclient.get(orcidid)

# extracting bibtex
try:
Expand All @@ -230,7 +249,8 @@ def main():
# years
tmp_list = list()
for key in orcid_bibtex:
tmp_list.append(key)
tmp_list.append(int(key))

years[name] = sorted(tmp_list, reverse=True)

# saving bibtex into separated files
Expand Down
7 changes: 7 additions & 0 deletions docs/examples/search_authors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# importing module located in parent folder
import sys

sys.path.insert(0, "../")

import sys
import pyorcid
4 changes: 2 additions & 2 deletions orcidpyclient/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
__all__ = ('get', 'search', 'orcid_api_version')
__all__ = ("get", "search", "orcid_api_version")

from .rest import get, search, orcid_api_version
from .functions import get, orcid_api_version, search
7 changes: 4 additions & 3 deletions orcidpyclient/constants.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
ORCID_API_VERSION = '3.0'
ORCID_PUBLIC_BASE_URL = f'https://pub.orcid.org/v{ORCID_API_VERSION}/'
ORCID_SANDBOX_BASE_URL = 'https://pub.orcid.org/'
ORCID_API_VERSION = "3.0"
ORCID_PUBLIC_BASE_URL = f"https://pub.orcid.org/v{ORCID_API_VERSION}/"
ORCID_SANDBOX_BASE_URL = "https://pub.orcid.org/"

BASE_HEADERS = {"Accept": "application/orcid+json", "Content-Type": "application/json;charset=UTF-8"}
1 change: 1 addition & 0 deletions orcidpyclient/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
class ORCIDException(Exception):
pass


class NotFoundException(ORCIDException):
pass
76 changes: 76 additions & 0 deletions orcidpyclient/functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import json
import logging
import sys

import requests

from .constants import BASE_HEADERS, ORCID_API_VERSION, ORCID_PUBLIC_BASE_URL
from .logger_config import logger, stdout_sh
from .rest import Author


def _set_logger_debug(debug: bool = False):
"""_summary_
Args:
debug (bool, optional): _description_. Defaults to False.
"""

if debug:
logger.setLevel(logging.DEBUG)
stdout_sh.setLevel(logging.DEBUG)


def get(orcid_id: str, debug: bool = False):
"""Get an author based on an ORCID identifier."""

_set_logger_debug(debug)

if sys.version_info[0] < 3:
raise Exception("Python 2 is not supported")

_url = f"{ORCID_PUBLIC_BASE_URL}{orcid_id}"
_res = requests.get(_url, headers=BASE_HEADERS)

json_body = _res.json()

logger.debug("RESPONSE (BASE): {0}".format(json.dumps(json_body, sort_keys=True, indent=4, separators=(",", ": "))))

return Author(json_body)


def search(query, debug: bool = False):
"""Search the ORCID by sending a query to API
API documentation:
https://info.orcid.org/documentation/api-tutorials/api-tutorial-searching-the-orcid-registry/
api_example_query = {'q':'family-name:Malavolti+AND+given-names:Marco'}
Args:
query (_type_): query string
debug (bool, optional): option for the logging. Defaults to False.
Returns:
_type_: iterator of the results
"""

_set_logger_debug(debug)

if sys.version_info[0] < 3:
raise Exception("Python 2 is not supported")

_url = f"{ORCID_PUBLIC_BASE_URL}search?q={query}"
resp = requests.get(_url, headers=BASE_HEADERS)
logger.debug(resp.url)
json_body = resp.json()
logger.debug(json_body)
if json_body.get("result") is not None:
return (get(res.get("orcid-identifier", {}).get("path")) for res in json_body.get("result", {}))
else:
return iter(list())


def orcid_api_version():
"""Provides version of ORCID API that is used"""
return ORCID_API_VERSION
13 changes: 13 additions & 0 deletions orcidpyclient/logger_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import logging
import sys

_logger_depth = "INFO"

logger = logging.getLogger("#orcid#")
logger.setLevel(getattr(logging, _logger_depth))

stdout_sh = logging.StreamHandler(sys.stdout)
stdout_sh.setLevel(getattr(logging, _logger_depth))
stdout_sh.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))

logger.addHandler(stdout_sh)
Loading

0 comments on commit 4f47d0c

Please sign in to comment.