Skip to content

Commit 2795ca0

Browse files
author
Chris Park
committed
Merge branch 'develop'
2 parents 344c843 + b97745f commit 2795ca0

File tree

11 files changed

+142
-61
lines changed

11 files changed

+142
-61
lines changed

docker/Dockerfile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,6 @@ COPY tox.ini /python-dev/tox.ini
4949
WORKDIR /python-dev
5050

5151
# allow interactive bash inside docker container
52-
CMD ./run_python.sh $API_KEY $FILENAME $ALT_URL $GIT_USERNAME $VERSION
52+
CMD ./run_python.sh
5353

5454
VOLUME ["/source"]

docker/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,4 @@ Build the docker image, e.g. `docker build -t basistech/python:1.1 .`
99

1010
Run an example as `docker run -e API_KEY=api-key -v "path-to-local-python-dir:/source" basistech/python:1.1`
1111

12-
To test against a specific source file, add `-e FILENAME=filename` before the `-v`, to test against an alternate url, add `-e ALT_URL=alternate_url`, and optionally if you would like to regenerate gh-pages from the changes made to the development source you can add `-e GIT_USERNAME=git-username -e VERSION=version` before the `-v`. In order to push the gh-pages to git remember to mount .ssh and .gitconfig to the root dir `-v path-to-.ssh-dir:/root/.ssh -v path-to-.gitconfig:/root/.gitconfig`.
12+
To test against a specific source file, add `-e FILENAME=filename` before the `-v`, to test against an alternate url, add `-e ALT_URL=alternate_url`.

docker/run_python.sh

Lines changed: 13 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
retcode=0
44
ping_url="https://api.rosette.com/rest/v1"
5+
errors=( "Exception" "processingFailure" "badRequest" "ParseError" "ValueError" "SyntaxError" "AttributeError" "ImportError" )
56

67
#------------------ Functions ----------------------------------------------------
78
#Gets called when the user doesn't provide any args
@@ -10,12 +11,14 @@ function HELP {
1011
echo " API_KEY - Rosette API key (required)"
1112
echo " FILENAME - Python source file (optional)"
1213
echo " ALT_URL - Alternate service URL (optional)"
13-
echo " GIT_USERNAME - Git username where you would like to push regenerated gh-pages (optional)"
14-
echo " VERSION - Build version (optional)"
1514
echo "Compiles and runs the source file(s) using the local development source."
1615
exit 1
1716
}
1817

18+
if [ ! -z ${ALT_URL} ]; then
19+
ping_url=${ALT_URL}
20+
fi
21+
1922
#Checks if Rosette API key is valid
2023
function checkAPI {
2124
match=$(curl "${ping_url}/ping" -H "X-RosetteAPI-Key: ${API_KEY}" | grep -o "forbidden")
@@ -55,41 +58,25 @@ function runExample() {
5558
fi
5659
echo "${result}"
5760
echo -e "\n---------- ${1} end -------------"
58-
if [[ "${result}" == *"Exception"* ]]; then
59-
echo "Exception found"
60-
retcode=1
61-
elif [[ "$result" == *"processingFailure"* ]]; then
62-
retcode=1
63-
elif [[ "$result" == *"AttributeError"* ]]; then
64-
retcode=1
65-
elif [[ "$result" == *"ImportError"* ]]; then
66-
retcode=1
67-
fi
61+
for err in "${errors[@]}"; do
62+
if [[ ${result} == *"${err}"* ]]; then
63+
retcode=1
64+
fi
65+
done
6866
}
6967
#------------------ Functions End ------------------------------------------------
7068

7169
#Gets API_KEY, FILENAME and ALT_URL if present
72-
while getopts ":API_KEY:FILENAME:ALT_URL:GIT_USERNAME:VERSION" arg; do
70+
while getopts ":API_KEY:FILENAME:ALT_URL" arg; do
7371
case "${arg}" in
7472
API_KEY)
7573
API_KEY=${OPTARG}
76-
usage
7774
;;
7875
ALT_URL)
7976
ALT_URL=${OPTARG}
80-
usage
8177
;;
8278
FILENAME)
8379
FILENAME=${OPTARG}
84-
usage
85-
;;
86-
GIT_USERNAME)
87-
GIT_USERNAME=${OPTARG}
88-
usage
89-
;;
90-
VERSION)
91-
VERSION={OPTARG}
92-
usage
9380
;;
9481
esac
9582
done
@@ -109,8 +96,10 @@ if [ ! -z ${API_KEY} ]; then
10996
python /python-dev/setup.py install
11097
cd /python-dev/examples
11198
if [ ! -z ${FILENAME} ]; then
99+
echo -e "\nRunning example against: ${ping_url}\n"
112100
runExample ${FILENAME}
113101
else
102+
echo -e "\nRunning examples against: ${ping_url}\n"
114103
for file in *.py; do
115104
runExample ${file}
116105
done
@@ -123,21 +112,4 @@ fi
123112
cd /python-dev
124113
tox
125114

126-
#Generate gh-pages and push them to git account (if git username is provided)
127-
if [ ! -z ${GIT_USERNAME} ] && [ ! -z ${VERSION} ]; then
128-
#clone python git repo
129-
cd /
130-
git clone [email protected]:${GIT_USERNAME}/python.git
131-
cd python
132-
git checkout origin/gh-pages -b gh-pages
133-
git branch -d develop
134-
#generate gh-pages and set ouput dir to git repo (gh-pages branch)
135-
cd /python-dev
136-
.tox/py27/bin/epydoc -v --no-private --no-frames --css epydoc.css -o /python rosette/*.py
137-
cd /python
138-
git add .
139-
git commit -a -m "publish python apidocs ${VERSION}"
140-
git push
141-
fi
142-
143115
exit ${retcode}

examples/docker/Dockerfile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,6 @@ RUN chmod 755 /python/examples/run_python.sh
1010
WORKDIR /python/examples
1111

1212
# allow interactive bash inside docker container
13-
CMD ./run_python.sh $API_KEY $FILENAME $ALT_URL
13+
CMD ./run_python.sh
1414

1515
VOLUME ["/source"]

examples/docker/run_python.sh

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
retcode=0
44
ping_url="https://api.rosette.com/rest/v1"
5+
errors=( "Exception" "processingFailure" "badRequest" "ParseError" "ValueError" "SyntaxError" "AttributeError" "ImportError" )
56

67
#------------------ Functions ----------------------------------------------------
78

@@ -15,6 +16,10 @@ function HELP {
1516
exit 1
1617
}
1718

19+
if [ ! -z ${ALT_URL} ]; then
20+
ping_url=${ALT_URL}
21+
fi
22+
1823
#Checks if Rosette API key is valid
1924
function checkAPI() {
2025
match=$(curl "${ping_url}/ping" -H "X-RosetteAPI-Key: ${API_KEY}" | grep -o "forbidden")
@@ -54,16 +59,11 @@ function runExample() {
5459
fi
5560
echo "${result}"
5661
echo -e "\n---------- ${1} end -------------"
57-
if [[ "${result}" == *"Exception"* ]]; then
58-
echo "Exception found"
59-
retcode=1
60-
elif [[ "$result" == *"processingFailure"* ]]; then
61-
retcode=1
62-
elif [[ "$result" == *"AttributeError"* ]]; then
63-
retcode=1
64-
elif [[ "$result" == *"ImportError"* ]]; then
65-
retcode=1
66-
fi
62+
for err in "${errors[@]}"; do
63+
if [[ ${result} == *"${err}"* ]]; then
64+
retcode=1
65+
fi
66+
done
6767
}
6868

6969
#------------------ Functions End ------------------------------------------------
@@ -73,15 +73,12 @@ while getopts ":API_KEY:FILENAME:ALT_URL" arg; do
7373
case "${arg}" in
7474
API_KEY)
7575
API_KEY=${OPTARG}
76-
usage
7776
;;
7877
FILENAME)
7978
FILENAME=${OPTARG}
80-
usage
8179
;;
8280
ALT_URL)
8381
ALT_URL=${OPTARG}
84-
usage
8582
;;
8683
esac
8784
done
@@ -97,8 +94,10 @@ cp /source/examples/*.* .
9794
if [ ! -z ${API_KEY} ]; then
9895
checkAPI
9996
if [ ! -z ${FILENAME} ]; then
97+
echo -e "\nRunning example against: ${ping_url}\n"
10098
runExample ${FILENAME}
10199
else
100+
echo -e "\nRunning examples against: ${ping_url}\n"
102101
for file in *.py; do
103102
runExample ${file}
104103
done

examples/entities.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ def run(key, altUrl='https://api.rosette.com/rest/v1/'):
1717
entities_text_data = "Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a cameo in Boston this… http://dlvr.it/BnsFfS"
1818
params = DocumentParameters()
1919
params["content"] = entities_text_data
20-
return api.entities(params) # entity linking is turned off
20+
params["genre"] = "social-media"
21+
return api.entities(params)
2122

2223
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')
2324
parser.add_argument('-k', '--key', help='Rosette API Key', required=True)

examples/entities_linked.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ def run(key, altUrl='https://api.rosette.com/rest/v1/'):
1919
params = DocumentParameters()
2020
params["content"] = entities_linked_text_data
2121
params["genre"] = "social-media"
22-
return api.entities(params, True) # entity linking is turned on
22+
# This syntax is deprecated, call api.entities(params)
23+
return api.entities(params, True)
2324

2425

2526
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Calls the ' + os.path.splitext(os.path.basename(__file__))[0] + ' endpoint')

examples/language.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ def run(key, altUrl='https://api.rosette.com/rest/v1/'):
1717

1818
language_data = "Por favor Señorita, says the man."
1919
params = DocumentParameters()
20-
2120
params["content"] = language_data
21+
api.setCustomHeaders("X-RosetteAPI-App", "python-app")
2222
return api.language(params)
2323

2424

rosette/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,4 @@
1616
limitations under the License.
1717
"""
1818

19-
__version__ = '1.1.1'
19+
__version__ = '1.2.0'

rosette/api.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@
2626
import os
2727
from socket import gaierror
2828
import requests
29+
import re
30+
import warnings
2931

3032
_BINDING_VERSION = '1.1.1'
3133
_GZIP_BYTEARRAY = bytearray([0x1F, 0x8b, 0x08])
@@ -366,6 +368,17 @@ def info(self):
366368
identifying data."""
367369
url = self.service_url + "info"
368370
headers = {'Accept': 'application/json', 'X-RosetteAPI-Binding': 'python', 'X-RosetteAPI-Binding-Version': _BINDING_VERSION}
371+
372+
customHeaders = self.api.getCustomHeaders()
373+
pattern = re.compile('^X-RosetteAPI-')
374+
if customHeaders is not None:
375+
for key in customHeaders.keys():
376+
if pattern.match(key) is not None:
377+
headers[key] = customHeaders[key]
378+
else:
379+
raise RosetteException("badHeader", "Custom header name must begin with \"X-RosetteAPI-\"", key)
380+
self.api.clearCustomHeaders()
381+
369382
if self.debug:
370383
headers['X-RosetteAPI-Devel'] = 'true'
371384
self.logger.info('info: ' + url)
@@ -382,6 +395,17 @@ def ping(self):
382395

383396
url = self.service_url + 'ping'
384397
headers = {'Accept': 'application/json', 'X-RosetteAPI-Binding': 'python', 'X-RosetteAPI-Binding-Version': _BINDING_VERSION}
398+
399+
customHeaders = self.api.getCustomHeaders()
400+
pattern = re.compile('^X-RosetteAPI-')
401+
if customHeaders is not None:
402+
for key in customHeaders.keys():
403+
if pattern.match(key) is not None:
404+
headers[key] = customHeaders[key]
405+
else:
406+
raise RosetteException("badHeader", "Custom header name must begin with \"X-RosetteAPI-\"", key)
407+
self.api.clearCustomHeaders()
408+
385409
if self.debug:
386410
headers['X-RosetteAPI-Devel'] = 'true'
387411
self.logger.info('Ping: ' + url)
@@ -426,9 +450,21 @@ def call(self, parameters):
426450
params_to_serialize = parameters.serialize(self.api.options)
427451
headers = {}
428452
if self.user_key is not None:
453+
454+
customHeaders = self.api.getCustomHeaders()
455+
pattern = re.compile('^X-RosetteAPI-')
456+
if customHeaders is not None:
457+
for key in customHeaders.keys():
458+
if pattern.match(key) is not None:
459+
headers[key] = customHeaders[key]
460+
else:
461+
raise RosetteException("badHeader", "Custom header name must begin with \"X-RosetteAPI-\"", key)
462+
self.api.clearCustomHeaders()
463+
429464
headers["X-RosetteAPI-Key"] = self.user_key
430465
headers["X-RosetteAPI-Binding"] = "python"
431466
headers["X-RosetteAPI-Binding-Version"] = _BINDING_VERSION
467+
432468
if self.useMultipart:
433469
params = dict(
434470
(key,
@@ -502,6 +538,7 @@ def __init__(
502538
self.connection_refresh_duration = refresh_duration
503539
self.http_connection = None
504540
self.options = {}
541+
self.customHeaders = {}
505542

506543
def _connect(self, parsedUrl):
507544
""" Simple connection method
@@ -638,6 +675,30 @@ def clearOptions(self):
638675
"""
639676
self.options.clear()
640677

678+
def setCustomHeaders(self, name, value):
679+
"""
680+
Sets custom headers
681+
682+
@param headers: array of custom headers to be set
683+
"""
684+
if value is None:
685+
self.customHeaders.pop(name, None)
686+
else:
687+
self.customHeaders[name] = value
688+
689+
def getCustomHeaders(self):
690+
"""
691+
Get custom headers
692+
"""
693+
return self.customHeaders
694+
695+
def clearCustomHeaders(self):
696+
"""
697+
Clears custom headers
698+
"""
699+
700+
self.customHeaders.clear()
701+
641702
def ping(self):
642703
"""
643704
Create a ping L{EndpointCaller} for the server and ping it.
@@ -705,6 +766,7 @@ def entities(self, parameters, resolve_entities=False):
705766
@type resolve_entities: Boolean
706767
@return: A python dictionary containing the results of entity extraction."""
707768
if resolve_entities:
769+
warnings.warn("entities(params,resolve_entities) is deprecated and replaced by entities(params).", DeprecationWarning)
708770
return EndpointCaller(self, "entities/linked").call(parameters)
709771
else:
710772
return EndpointCaller(self, "entities").call(parameters)

0 commit comments

Comments
 (0)