├── episode-5 ├── flask │ └── src │ │ ├── watsonutils │ │ ├── __init__.py │ │ ├── credentials.json │ │ ├── vcap.py │ │ ├── creds.py │ │ ├── baseservice.py │ │ ├── naturallanguageclassification.py │ │ └── languagetranslation.py │ │ ├── runtime.txt │ │ ├── Procfile │ │ ├── manifest.yml │ │ ├── requirements.txt │ │ ├── templates │ │ └── watson │ │ │ └── wlindex.html │ │ └── static │ │ └── js │ │ └── services.js ├── django │ └── src │ │ └── projwatson │ │ ├── projwatson │ │ ├── __init__.py │ │ ├── wsgi.py │ │ └── urls.py │ │ ├── watsonlanguage │ │ ├── __init__.py │ │ ├── views │ │ │ ├── __init__.py │ │ │ └── wl.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── watsonutils │ │ │ ├── __init__.py │ │ │ ├── credentials.json │ │ │ ├── vcap.py │ │ │ ├── baseservice.py │ │ │ ├── creds.py │ │ │ ├── naturallanguageclassification.py │ │ │ └── languagetranslation.py │ │ ├── models.py │ │ ├── tests.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── urls.py │ │ ├── templates │ │ │ └── watson │ │ │ │ └── wlindex.html │ │ └── static │ │ │ └── js │ │ │ └── services.js │ │ ├── runtime.txt │ │ ├── db.sqlite3 │ │ ├── manifest.yml │ │ ├── requirements.txt │ │ ├── initdbadmin.py │ │ ├── manage.py │ │ ├── run.sh │ │ └── createdbadmin.py └── README.md ├── episode-6 ├── flask │ └── src │ │ ├── watsonutils │ │ ├── __init__.py │ │ ├── credentials.json │ │ ├── vcap.py │ │ ├── creds.py │ │ ├── baseservice.py │ │ ├── alchemylanguage.py │ │ ├── naturallanguageclassification.py │ │ ├── naturallanguageunderstanding.py │ │ └── languagetranslation.py │ │ ├── runtime.txt │ │ ├── Procfile │ │ ├── manifest.yml │ │ ├── requirements.txt │ │ ├── templates │ │ └── watson │ │ │ └── wlindex.html │ │ └── static │ │ └── js │ │ └── services.js ├── django │ └── src │ │ └── projwatson │ │ ├── projwatson │ │ ├── __init__.py │ │ ├── wsgi.py │ │ └── urls.py │ │ ├── watsonlanguage │ │ ├── __init__.py │ │ ├── views │ │ │ └── __init__.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── watsonutils │ │ │ ├── __init__.py │ │ │ ├── credentials.json │ │ │ ├── vcap.py │ │ │ ├── creds.py │ │ │ ├── baseservice.py │ │ │ ├── alchemylanguage.py │ │ │ ├── naturallanguageclassification.py │ │ │ ├── naturallanguageunderstanding.py │ │ │ └── languagetranslation.py │ │ ├── models.py │ │ ├── tests.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── urls.py │ │ ├── templates │ │ │ └── watson │ │ │ │ └── wlindex.html │ │ └── static │ │ │ └── js │ │ │ └── services.js │ │ ├── runtime.txt │ │ ├── db.sqlite3 │ │ ├── manifest.yml │ │ ├── requirements.txt │ │ ├── initdbadmin.py │ │ ├── manage.py │ │ ├── run.sh │ │ └── createdbadmin.py └── README.md ├── episode-1 ├── flask │ └── src │ │ ├── runtime.txt │ │ ├── Procfile │ │ ├── manifest.yml │ │ ├── requirements.txt │ │ ├── templates │ │ └── watson │ │ │ └── wlindex.html │ │ └── watson.py ├── django │ └── src │ │ └── projwatson │ │ ├── projwatson │ │ ├── __init__.py │ │ ├── wsgi.py │ │ └── urls.py │ │ ├── watsonlanguage │ │ ├── __init__.py │ │ ├── views │ │ │ ├── __init__.py │ │ │ └── wl.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── tests.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── urls.py │ │ └── templates │ │ │ └── watson │ │ │ └── wlindex.html │ │ ├── runtime.txt │ │ ├── db.sqlite3 │ │ ├── manifest.yml │ │ ├── requirements.txt │ │ ├── initdbadmin.py │ │ ├── manage.py │ │ ├── run.sh │ │ └── createdbadmin.py └── README.md ├── episode-2 ├── flask │ └── src │ │ ├── runtime.txt │ │ ├── Procfile │ │ ├── manifest.yml │ │ ├── requirements.txt │ │ ├── templates │ │ └── watson │ │ │ └── wlindex.html │ │ ├── translation.py │ │ └── watson.py ├── django │ └── src │ │ └── projwatson │ │ ├── projwatson │ │ ├── __init__.py │ │ ├── wsgi.py │ │ └── urls.py │ │ ├── watsonlanguage │ │ ├── __init__.py │ │ ├── views │ │ │ ├── __init__.py │ │ │ └── wl.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── tests.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── urls.py │ │ └── templates │ │ │ └── watson │ │ │ └── wlindex.html │ │ ├── runtime.txt │ │ ├── db.sqlite3 │ │ ├── manifest.yml │ │ ├── requirements.txt │ │ ├── initdbadmin.py │ │ ├── manage.py │ │ ├── run.sh │ │ └── createdbadmin.py └── README.md ├── episode-3 ├── flask │ └── src │ │ ├── runtime.txt │ │ ├── Procfile │ │ ├── manifest.yml │ │ ├── requirements.txt │ │ ├── templates │ │ └── watson │ │ │ └── wlindex.html │ │ ├── naturallanguageclassification.py │ │ ├── languagetranslation.py │ │ └── watson.py ├── django │ └── src │ │ └── projwatson │ │ ├── projwatson │ │ ├── __init__.py │ │ ├── wsgi.py │ │ └── urls.py │ │ ├── watsonlanguage │ │ ├── __init__.py │ │ ├── views │ │ │ ├── __init__.py │ │ │ └── wl.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── watsonutils │ │ │ ├── __init__.py │ │ │ ├── naturallanguageclassification.py │ │ │ └── languagetranslation.py │ │ ├── models.py │ │ ├── tests.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── urls.py │ │ └── templates │ │ │ └── watson │ │ │ └── wlindex.html │ │ ├── runtime.txt │ │ ├── db.sqlite3 │ │ ├── manifest.yml │ │ ├── requirements.txt │ │ ├── initdbadmin.py │ │ ├── manage.py │ │ ├── run.sh │ │ └── createdbadmin.py └── README.md ├── episode-4 ├── flask │ └── src │ │ ├── runtime.txt │ │ ├── Procfile │ │ ├── manifest.yml │ │ ├── requirements.txt │ │ ├── templates │ │ └── watson │ │ │ └── wlindex.html │ │ ├── naturallanguageclassification.py │ │ ├── static │ │ └── js │ │ │ └── services.js │ │ └── languagetranslation.py ├── django │ └── src │ │ └── projwatson │ │ ├── projwatson │ │ ├── __init__.py │ │ ├── wsgi.py │ │ └── urls.py │ │ ├── watsonlanguage │ │ ├── __init__.py │ │ ├── views │ │ │ └── __init__.py │ │ ├── migrations │ │ │ └── __init__.py │ │ ├── watsonutils │ │ │ ├── __init__.py │ │ │ ├── naturallanguageclassification.py │ │ │ └── languagetranslation.py │ │ ├── models.py │ │ ├── tests.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── urls.py │ │ ├── templates │ │ │ └── watson │ │ │ │ └── wlindex.html │ │ └── static │ │ │ └── js │ │ │ └── services.js │ │ ├── runtime.txt │ │ ├── db.sqlite3 │ │ ├── manifest.yml │ │ ├── requirements.txt │ │ ├── initdbadmin.py │ │ ├── manage.py │ │ ├── run.sh │ │ └── createdbadmin.py └── README.md ├── .travis.yml ├── .gitignore └── README.md /episode-5/flask/src/watsonutils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-6/flask/src/watsonutils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-1/flask/src/runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.5.1 2 | -------------------------------------------------------------------------------- /episode-2/flask/src/runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.5.1 2 | -------------------------------------------------------------------------------- /episode-3/flask/src/runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.5.1 2 | -------------------------------------------------------------------------------- /episode-4/flask/src/runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.5.1 2 | -------------------------------------------------------------------------------- /episode-5/flask/src/runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.5.1 2 | -------------------------------------------------------------------------------- /episode-6/flask/src/runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.5.1 2 | -------------------------------------------------------------------------------- /episode-1/flask/src/Procfile: -------------------------------------------------------------------------------- 1 | web: python watson.py -------------------------------------------------------------------------------- /episode-2/flask/src/Procfile: -------------------------------------------------------------------------------- 1 | web: python watson.py -------------------------------------------------------------------------------- /episode-3/flask/src/Procfile: -------------------------------------------------------------------------------- 1 | web: python watson.py -------------------------------------------------------------------------------- /episode-4/flask/src/Procfile: -------------------------------------------------------------------------------- 1 | web: python watson.py -------------------------------------------------------------------------------- /episode-5/flask/src/Procfile: -------------------------------------------------------------------------------- 1 | web: python watson.py -------------------------------------------------------------------------------- /episode-6/flask/src/Procfile: -------------------------------------------------------------------------------- 1 | web: python watson.py -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/projwatson/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/watsonlanguage/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/projwatson/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/watsonlanguage/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/projwatson/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/watsonlanguage/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/projwatson/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/watsonlanguage/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/projwatson/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/watsonlanguage/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/projwatson/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/watsonlanguage/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.5.1 2 | -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.5.1 2 | -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.5.1 2 | -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.5.1 2 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.5.1 2 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.5.1 2 | -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/watsonlanguage/views/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/watsonlanguage/views/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/watsonlanguage/views/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/watsonlanguage/views/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/watsonlanguage/views/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/watsonlanguage/views/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/watsonlanguage/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/watsonlanguage/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/watsonlanguage/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/watsonlanguage/watsonutils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/watsonlanguage/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/watsonlanguage/watsonutils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/watsonlanguage/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/watsonlanguage/watsonutils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/watsonlanguage/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/watsonlanguage/watsonutils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/watsonlanguage/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/watsonlanguage/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/watsonlanguage/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/watsonlanguage/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/watsonlanguage/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/watsonlanguage/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/watsonlanguage/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/watsonlanguage/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/watsonlanguage/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/watsonlanguage/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/watsonlanguage/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | # Create your models here. 4 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/watsonlanguage/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/watsonlanguage/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/watsonlanguage/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/watsonlanguage/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/watsonlanguage/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/watsonlanguage/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/watsonlanguage/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/python-primer-companion-code/HEAD/episode-1/django/src/projwatson/db.sqlite3 -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/python-primer-companion-code/HEAD/episode-2/django/src/projwatson/db.sqlite3 -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/python-primer-companion-code/HEAD/episode-3/django/src/projwatson/db.sqlite3 -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/python-primer-companion-code/HEAD/episode-4/django/src/projwatson/db.sqlite3 -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/python-primer-companion-code/HEAD/episode-5/django/src/projwatson/db.sqlite3 -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/db.sqlite3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/python-primer-companion-code/HEAD/episode-6/django/src/projwatson/db.sqlite3 -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/watsonlanguage/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class WatsonlanguageConfig(AppConfig): 5 | name = 'watsonlanguage' 6 | -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/watsonlanguage/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class WatsonlanguageConfig(AppConfig): 5 | name = 'watsonlanguage' 6 | -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/watsonlanguage/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class WatsonlanguageConfig(AppConfig): 5 | name = 'watsonlanguage' 6 | -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/watsonlanguage/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class WatsonlanguageConfig(AppConfig): 5 | name = 'watsonlanguage' 6 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/watsonlanguage/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class WatsonlanguageConfig(AppConfig): 5 | name = 'watsonlanguage' 6 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/watsonlanguage/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class WatsonlanguageConfig(AppConfig): 5 | name = 'watsonlanguage' 6 | -------------------------------------------------------------------------------- /episode-4/README.md: -------------------------------------------------------------------------------- 1 | # Episode 4 : REST API 2 | In this episode the language identification, translation and natural language combined application function 3 | is converted into REST API. 4 | 5 | The code that has been submitted to this repository, has passed tests performed at the end of the episode. -------------------------------------------------------------------------------- /episode-1/flask/src/manifest.yml: -------------------------------------------------------------------------------- 1 | applications: 2 | - path: . 3 | memory: 128M 4 | instances: 1 5 | domain: eu-gb.mybluemix.net 6 | name: your-flask-project 7 | host: your-flask-project 8 | disk_quota: 1024M 9 | buildpack: https://github.com/cloudfoundry/python-buildpack#v1.5.4 10 | cf_stacks: 11 | - cflinuxfs2 12 | -------------------------------------------------------------------------------- /episode-2/flask/src/manifest.yml: -------------------------------------------------------------------------------- 1 | applications: 2 | - path: . 3 | memory: 128M 4 | instances: 1 5 | domain: eu-gb.mybluemix.net 6 | name: your-flask-project 7 | host: your-flask-project 8 | disk_quota: 1024M 9 | buildpack: https://github.com/cloudfoundry/python-buildpack#v1.5.4 10 | cf_stacks: 11 | - cflinuxfs2 12 | -------------------------------------------------------------------------------- /episode-3/flask/src/manifest.yml: -------------------------------------------------------------------------------- 1 | applications: 2 | - path: . 3 | memory: 128M 4 | instances: 1 5 | domain: eu-gb.mybluemix.net 6 | name: your-flask-project 7 | host: your-flask-project 8 | disk_quota: 1024M 9 | buildpack: https://github.com/cloudfoundry/python-buildpack#v1.5.4 10 | cf_stacks: 11 | - cflinuxfs2 12 | -------------------------------------------------------------------------------- /episode-4/flask/src/manifest.yml: -------------------------------------------------------------------------------- 1 | applications: 2 | - path: . 3 | memory: 128M 4 | instances: 1 5 | domain: eu-gb.mybluemix.net 6 | name: your-flask-project 7 | host: your-flask-project 8 | disk_quota: 1024M 9 | buildpack: https://github.com/cloudfoundry/python-buildpack#v1.5.4 10 | cf_stacks: 11 | - cflinuxfs2 12 | -------------------------------------------------------------------------------- /episode-5/flask/src/manifest.yml: -------------------------------------------------------------------------------- 1 | applications: 2 | - path: . 3 | memory: 128M 4 | instances: 1 5 | domain: eu-gb.mybluemix.net 6 | name: your-flask-project 7 | host: your-flask-project 8 | disk_quota: 1024M 9 | buildpack: https://github.com/cloudfoundry/python-buildpack#v1.5.4 10 | cf_stacks: 11 | - cflinuxfs2 12 | -------------------------------------------------------------------------------- /episode-6/flask/src/manifest.yml: -------------------------------------------------------------------------------- 1 | applications: 2 | - path: . 3 | memory: 128M 4 | instances: 1 5 | domain: eu-gb.mybluemix.net 6 | name: your-flask-project 7 | host: your-flask-project 8 | disk_quota: 1024M 9 | buildpack: https://github.com/cloudfoundry/python-buildpack#v1.5.4 10 | cf_stacks: 11 | - cflinuxfs2 12 | -------------------------------------------------------------------------------- /episode-3/README.md: -------------------------------------------------------------------------------- 1 | # Episode 3 : Natural Language Classification 2 | After some code tidy up, this episode shows how to use the Natural Language Classifier service to determine 3 | an intent in the submitted, and translated text. 4 | 5 | The code that has been submitted to this repository, has passed tests performed at the end of the episode. -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/manifest.yml: -------------------------------------------------------------------------------- 1 | applications: 2 | - path: . 3 | memory: 128M 4 | instances: 1 5 | domain: eu-gb.mybluemix.net 6 | name: your-django-project 7 | host: your-django-project 8 | disk_quota: 1024M 9 | buildpack: https://github.com/cloudfoundry/python-buildpack#v1.5.4 10 | cf_stacks: 11 | - cflinuxfs2 12 | command: bash ./run.sh -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/manifest.yml: -------------------------------------------------------------------------------- 1 | applications: 2 | - path: . 3 | memory: 128M 4 | instances: 1 5 | domain: eu-gb.mybluemix.net 6 | name: your-django-project 7 | host: your-django-project 8 | disk_quota: 1024M 9 | buildpack: https://github.com/cloudfoundry/python-buildpack#v1.5.4 10 | cf_stacks: 11 | - cflinuxfs2 12 | command: bash ./run.sh -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/manifest.yml: -------------------------------------------------------------------------------- 1 | applications: 2 | - path: . 3 | memory: 128M 4 | instances: 1 5 | domain: eu-gb.mybluemix.net 6 | name: your-django-project 7 | host: your-django-project 8 | disk_quota: 1024M 9 | buildpack: https://github.com/cloudfoundry/python-buildpack#v1.5.4 10 | cf_stacks: 11 | - cflinuxfs2 12 | command: bash ./run.sh -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/manifest.yml: -------------------------------------------------------------------------------- 1 | applications: 2 | - path: . 3 | memory: 128M 4 | instances: 1 5 | domain: eu-gb.mybluemix.net 6 | name: your-django-project 7 | host: your-django-project 8 | disk_quota: 1024M 9 | buildpack: https://github.com/cloudfoundry/python-buildpack#v1.5.4 10 | cf_stacks: 11 | - cflinuxfs2 12 | command: bash ./run.sh -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/manifest.yml: -------------------------------------------------------------------------------- 1 | applications: 2 | - path: . 3 | memory: 128M 4 | instances: 1 5 | domain: eu-gb.mybluemix.net 6 | name: your-django-project 7 | host: your-django-project 8 | disk_quota: 1024M 9 | buildpack: https://github.com/cloudfoundry/python-buildpack#v1.5.4 10 | cf_stacks: 11 | - cflinuxfs2 12 | command: bash ./run.sh -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/manifest.yml: -------------------------------------------------------------------------------- 1 | applications: 2 | - path: . 3 | memory: 128M 4 | instances: 1 5 | domain: eu-gb.mybluemix.net 6 | name: your-django-project 7 | host: your-django-project 8 | disk_quota: 1024M 9 | buildpack: https://github.com/cloudfoundry/python-buildpack#v1.5.4 10 | cf_stacks: 11 | - cflinuxfs2 12 | command: bash ./run.sh -------------------------------------------------------------------------------- /episode-6/README.md: -------------------------------------------------------------------------------- 1 | # Episode 6 : Natural Language Keywords and Entities 2 | In this episode you learn how to use the Natural Language Understanding service to determine the primary keywords and entities extending 3 | your applications understanding of the submitted text. 4 | 5 | **Note:** This section used to use the now deprecated Alchemy Language service. 6 | -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/requirements.txt: -------------------------------------------------------------------------------- 1 | asn1crypto==0.23.0 2 | certifi==2017.11.5 3 | cffi==1.11.2 4 | chardet==3.0.4 5 | cryptography==2.1.3 6 | Django==1.9.2 7 | idna==2.6 8 | pycparser==2.18 9 | pyOpenSSL==17.3.0 10 | pysolr==3.6.0 11 | python-dateutil==2.6.1 12 | requests==2.18.4 13 | six==1.11.0 14 | urllib3==1.22 15 | watson-developer-cloud==1.0.0 16 | -------------------------------------------------------------------------------- /episode-2/README.md: -------------------------------------------------------------------------------- 1 | # Episode 2 : Language Translator 2 | This episode shows how to use the Translator service to determine available translations and to perform 3 | a translation so the submitted text can be used in the next stage of the application. 4 | 5 | The code that has been submitted to this repository, has passed tests performed at the end of the episode. 6 | -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/requirements.txt: -------------------------------------------------------------------------------- 1 | asn1crypto==0.23.0 2 | certifi==2017.11.5 3 | cffi==1.11.2 4 | chardet==3.0.4 5 | cryptography==2.1.3 6 | Django==1.9.2 7 | idna==2.6 8 | pycparser==2.18 9 | pyOpenSSL==17.3.0 10 | pysolr==3.6.0 11 | python-dateutil==2.6.1 12 | requests==2.18.4 13 | six==1.11.0 14 | urllib3==1.22 15 | watson-developer-cloud==1.0.0 16 | -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/requirements.txt: -------------------------------------------------------------------------------- 1 | asn1crypto==0.23.0 2 | certifi==2017.11.5 3 | cffi==1.11.2 4 | chardet==3.0.4 5 | cryptography==2.1.3 6 | Django==1.9.2 7 | idna==2.6 8 | pycparser==2.18 9 | pyOpenSSL==17.3.0 10 | pysolr==3.6.0 11 | python-dateutil==2.6.1 12 | requests==2.18.4 13 | six==1.11.0 14 | urllib3==1.22 15 | watson-developer-cloud==1.0.0 16 | -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/requirements.txt: -------------------------------------------------------------------------------- 1 | asn1crypto==0.23.0 2 | certifi==2017.11.5 3 | cffi==1.11.2 4 | chardet==3.0.4 5 | cryptography==2.1.3 6 | Django==1.9.2 7 | idna==2.6 8 | pycparser==2.18 9 | pyOpenSSL==17.3.0 10 | pysolr==3.6.0 11 | python-dateutil==2.6.1 12 | requests==2.18.4 13 | six==1.11.0 14 | urllib3==1.22 15 | watson-developer-cloud==1.0.0 16 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/requirements.txt: -------------------------------------------------------------------------------- 1 | asn1crypto==0.23.0 2 | certifi==2017.11.5 3 | cffi==1.11.2 4 | chardet==3.0.4 5 | cryptography==2.1.3 6 | Django==1.9.2 7 | idna==2.6 8 | pycparser==2.18 9 | pyOpenSSL==17.3.0 10 | pysolr==3.6.0 11 | python-dateutil==2.6.1 12 | requests==2.18.4 13 | six==1.11.0 14 | urllib3==1.22 15 | watson-developer-cloud==1.0.0 16 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/requirements.txt: -------------------------------------------------------------------------------- 1 | asn1crypto==0.23.0 2 | certifi==2017.11.5 3 | cffi==1.11.2 4 | chardet==3.0.4 5 | cryptography==2.1.3 6 | Django==1.9.2 7 | idna==2.6 8 | pycparser==2.18 9 | pyOpenSSL==17.3.0 10 | pysolr==3.6.0 11 | python-dateutil==2.6.1 12 | requests==2.18.4 13 | six==1.11.0 14 | urllib3==1.22 15 | watson-developer-cloud==1.0.0 16 | -------------------------------------------------------------------------------- /episode-5/flask/src/watsonutils/credentials.json: -------------------------------------------------------------------------------- 1 | { 2 | "language_translator": { 3 | "username": "", 4 | "password": "" 5 | }, 6 | "natural_language_classifier": { 7 | "username": "", 8 | "password": "" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /episode-5/README.md: -------------------------------------------------------------------------------- 1 | # Episode 5 : Credential Store 2 | In this episode you learn how to utilise the environment variables that IBM Cloud makes available to read in the service 3 | credentials. If the credentials are not found in IBM Cloud, ie. when you have not bound them into your application, the 4 | application checks for the credentials in a credentials.json file. Which you can then protect appropriately. 5 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/watsonlanguage/watsonutils/credentials.json: -------------------------------------------------------------------------------- 1 | { 2 | "language_translator": { 3 | "username": "", 4 | "password": "" 5 | }, 6 | "natural_language_classifier": { 7 | "username": "", 8 | "password": "" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /episode-1/flask/src/requirements.txt: -------------------------------------------------------------------------------- 1 | asn1crypto==0.23.0 2 | certifi==2017.11.5 3 | cffi==1.11.2 4 | chardet==3.0.4 5 | cryptography==2.1.3 6 | Flask==0.10.1 7 | Flask-WTF==0.12 8 | idna==2.6 9 | itsdangerous==0.24 10 | Jinja2==2.8 11 | MarkupSafe==0.23 12 | pycparser==2.18 13 | pyOpenSSL==17.3.0 14 | pysolr==3.6.0 15 | python-dateutil==2.6.1 16 | requests==2.18.4 17 | six==1.11.0 18 | urllib3==1.22 19 | watson-developer-cloud==1.0.0 20 | Werkzeug==0.11.4 21 | WTForms==2.1 22 | -------------------------------------------------------------------------------- /episode-2/flask/src/requirements.txt: -------------------------------------------------------------------------------- 1 | asn1crypto==0.23.0 2 | certifi==2017.11.5 3 | cffi==1.11.2 4 | chardet==3.0.4 5 | cryptography==2.1.3 6 | Flask==0.10.1 7 | Flask-WTF==0.12 8 | idna==2.6 9 | itsdangerous==0.24 10 | Jinja2==2.8 11 | MarkupSafe==0.23 12 | pycparser==2.18 13 | pyOpenSSL==17.3.0 14 | pysolr==3.6.0 15 | python-dateutil==2.6.1 16 | requests==2.18.4 17 | six==1.11.0 18 | urllib3==1.22 19 | watson-developer-cloud==1.0.0 20 | Werkzeug==0.11.4 21 | WTForms==2.1 22 | -------------------------------------------------------------------------------- /episode-3/flask/src/requirements.txt: -------------------------------------------------------------------------------- 1 | asn1crypto==0.23.0 2 | certifi==2017.11.5 3 | cffi==1.11.2 4 | chardet==3.0.4 5 | cryptography==2.1.3 6 | Flask==0.10.1 7 | Flask-WTF==0.12 8 | idna==2.6 9 | itsdangerous==0.24 10 | Jinja2==2.8 11 | MarkupSafe==0.23 12 | pycparser==2.18 13 | pyOpenSSL==17.3.0 14 | pysolr==3.6.0 15 | python-dateutil==2.6.1 16 | requests==2.18.4 17 | six==1.11.0 18 | urllib3==1.22 19 | watson-developer-cloud==1.0.0 20 | Werkzeug==0.11.4 21 | WTForms==2.1 22 | -------------------------------------------------------------------------------- /episode-4/flask/src/requirements.txt: -------------------------------------------------------------------------------- 1 | asn1crypto==0.23.0 2 | certifi==2017.11.5 3 | cffi==1.11.2 4 | chardet==3.0.4 5 | cryptography==2.1.3 6 | Flask==0.10.1 7 | Flask-WTF==0.12 8 | idna==2.6 9 | itsdangerous==0.24 10 | Jinja2==2.8 11 | MarkupSafe==0.23 12 | pycparser==2.18 13 | pyOpenSSL==17.3.0 14 | pysolr==3.6.0 15 | python-dateutil==2.6.1 16 | requests==2.18.4 17 | six==1.11.0 18 | urllib3==1.22 19 | watson-developer-cloud==1.0.0 20 | Werkzeug==0.11.4 21 | WTForms==2.1 22 | -------------------------------------------------------------------------------- /episode-5/flask/src/requirements.txt: -------------------------------------------------------------------------------- 1 | asn1crypto==0.23.0 2 | certifi==2017.11.5 3 | cffi==1.11.2 4 | chardet==3.0.4 5 | cryptography==2.1.3 6 | Flask==0.10.1 7 | Flask-WTF==0.12 8 | idna==2.6 9 | itsdangerous==0.24 10 | Jinja2==2.8 11 | MarkupSafe==0.23 12 | pycparser==2.18 13 | pyOpenSSL==17.3.0 14 | pysolr==3.6.0 15 | python-dateutil==2.6.1 16 | requests==2.18.4 17 | six==1.11.0 18 | urllib3==1.22 19 | watson-developer-cloud==1.0.0 20 | Werkzeug==0.11.4 21 | WTForms==2.1 22 | -------------------------------------------------------------------------------- /episode-6/flask/src/requirements.txt: -------------------------------------------------------------------------------- 1 | asn1crypto==0.23.0 2 | certifi==2017.11.5 3 | cffi==1.11.2 4 | chardet==3.0.4 5 | cryptography==2.1.3 6 | Flask==0.10.1 7 | Flask-WTF==0.12 8 | idna==2.6 9 | itsdangerous==0.24 10 | Jinja2==2.8 11 | MarkupSafe==0.23 12 | pycparser==2.18 13 | pyOpenSSL==17.3.0 14 | pysolr==3.6.0 15 | python-dateutil==2.6.1 16 | requests==2.18.4 17 | six==1.11.0 18 | urllib3==1.22 19 | watson-developer-cloud==1.0.0 20 | Werkzeug==0.11.4 21 | WTForms==2.1 22 | -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/projwatson/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for projwatson project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "projwatson.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/projwatson/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for projwatson project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "projwatson.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/projwatson/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for projwatson project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "projwatson.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/projwatson/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for projwatson project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "projwatson.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/projwatson/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for projwatson project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "projwatson.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/projwatson/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for projwatson project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "projwatson.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /episode-6/flask/src/watsonutils/credentials.json: -------------------------------------------------------------------------------- 1 | { 2 | "language_translator": { 3 | "username": "", 4 | "password": "" 5 | }, 6 | "natural_language_classifier": { 7 | "username": "", 8 | "password": "" 9 | }, 10 | "natural_language_understanding" : { 11 | "username": "", 12 | "password": "" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/watsonlanguage/watsonutils/credentials.json: -------------------------------------------------------------------------------- 1 | { 2 | "language_translator": { 3 | "username": "", 4 | "password": "" 5 | }, 6 | "natural_language_classifier": { 7 | "username": "", 8 | "password": "" 9 | }, 10 | "natural_language_understanding" : { 11 | "username": "", 12 | "password": "" 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /episode-1/README.md: -------------------------------------------------------------------------------- 1 | # Episode 1 : Application Shell and Language Identification 2 | This episode shows how to create initial Django and Flask projects with an application shell that can 3 | be run both outside and on IBM Cloud. The Watson Developer Cloud SDK for Python is used to incorporate simple 4 | language identification into the application. As the application is developed, accidental typos have been 5 | generated, but have deliberately kept in to show the debugging and problem analysis process. 6 | 7 | The code that has been submitted to this repository, has passed tests performed at the end of the episode. 8 | -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/initdbadmin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from createdbadmin import MainProgram 17 | go = MainProgram() -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/initdbadmin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from createdbadmin import MainProgram 17 | go = MainProgram() -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/initdbadmin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from createdbadmin import MainProgram 17 | go = MainProgram() -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/initdbadmin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from createdbadmin import MainProgram 17 | go = MainProgram() -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/initdbadmin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from createdbadmin import MainProgram 17 | go = MainProgram() -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/initdbadmin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from createdbadmin import MainProgram 17 | go = MainProgram() -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | group: travis_latest 2 | dist: xenial # required for Python >= 3.7 (travis-ci/travis-ci#9069) 3 | sudo: required # required for Python >= 3.7 (travis-ci/travis-ci#9069) 4 | language: python 5 | cache: pip 6 | python: 7 | - 3.7 8 | install: 9 | - pip install flake8 # -r requirements.txt 10 | before_script: 11 | # stop the build if there are Python syntax errors or undefined names 12 | - flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics 13 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 14 | - flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 15 | script: 16 | - true # add other tests here 17 | notifications: 18 | on_success: change 19 | on_failure: change # `always` will be the setting once code changes slow down 20 | -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/watsonlanguage/urls.py: -------------------------------------------------------------------------------- 1 | # Copyright 2016 IBM Corp. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from django.conf.urls import include, url 16 | from .views import wl 17 | 18 | urlpatterns = [ 19 | url(r'^lang$', wl.index, name='langhome'), 20 | ] -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/watsonlanguage/urls.py: -------------------------------------------------------------------------------- 1 | # Copyright 2016 IBM Corp. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from django.conf.urls import include, url 16 | from .views import wl 17 | 18 | urlpatterns = [ 19 | url(r'^lang$', wl.index, name='langhome'), 20 | ] -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/watsonlanguage/urls.py: -------------------------------------------------------------------------------- 1 | # Copyright 2016 IBM Corp. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from django.conf.urls import include, url 16 | from .views import wl 17 | 18 | urlpatterns = [ 19 | url(r'^lang$', wl.index, name='langhome'), 20 | ] -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/watsonlanguage/urls.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from django.conf.urls import include, url 17 | from .views import wl 18 | 19 | urlpatterns = [ 20 | url(r'^lang$', wl.index, name='langhome'), 21 | url(r'^process$', wl.process, name='apiprocess'), 22 | ] -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/watsonlanguage/urls.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from django.conf.urls import include, url 17 | from .views import wl 18 | 19 | urlpatterns = [ 20 | url(r'^lang$', wl.index, name='langhome'), 21 | url(r'^process$', wl.process, name='apiprocess'), 22 | ] -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/watsonlanguage/urls.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from django.conf.urls import include, url 17 | from .views import wl 18 | 19 | urlpatterns = [ 20 | url(r'^lang$', wl.index, name='langhome'), 21 | url(r'^process$', wl.process, name='apiprocess'), 22 | ] -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright 2016 IBM Corp. All Rights Reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import os 18 | import sys 19 | 20 | if __name__ == "__main__": 21 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "projwatson.settings") 22 | 23 | from django.core.management import execute_from_command_line 24 | 25 | execute_from_command_line(sys.argv) 26 | -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright 2016 IBM Corp. All Rights Reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import os 18 | import sys 19 | 20 | if __name__ == "__main__": 21 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "projwatson.settings") 22 | 23 | from django.core.management import execute_from_command_line 24 | 25 | execute_from_command_line(sys.argv) 26 | -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright 2016 IBM Corp. All Rights Reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import os 18 | import sys 19 | 20 | if __name__ == "__main__": 21 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "projwatson.settings") 22 | 23 | from django.core.management import execute_from_command_line 24 | 25 | execute_from_command_line(sys.argv) 26 | -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright 2016 IBM Corp. All Rights Reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import os 18 | import sys 19 | 20 | if __name__ == "__main__": 21 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "projwatson.settings") 22 | 23 | from django.core.management import execute_from_command_line 24 | 25 | execute_from_command_line(sys.argv) 26 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright 2016 IBM Corp. All Rights Reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import os 18 | import sys 19 | 20 | if __name__ == "__main__": 21 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "projwatson.settings") 22 | 23 | from django.core.management import execute_from_command_line 24 | 25 | execute_from_command_line(sys.argv) 26 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright 2016 IBM Corp. All Rights Reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import os 18 | import sys 19 | 20 | if __name__ == "__main__": 21 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "projwatson.settings") 22 | 23 | from django.core.management import execute_from_command_line 24 | 25 | execute_from_command_line(sys.argv) 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | #Ipython Notebook 62 | .ipynb_checkpoints 63 | -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2016 IBM Corp. All Rights Reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # This file must be saved as a UNIX File 18 | 19 | if [ -z "$VCAP_APP_PORT" ]; 20 | then SERVER_PORT=80; 21 | else SERVER_PORT="$VCAP_APP_PORT"; 22 | fi 23 | echo port is $SERVER_PORT 24 | echo Performing database initialisations and migrations 25 | python manage.py makemigrations 26 | python manage.py migrate 27 | python manage.py shell < initdbadmin.py 28 | echo [$0] Starting Django Server... 29 | python manage.py runserver 0.0.0.0:$SERVER_PORT --noreload -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2016 IBM Corp. All Rights Reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # This file must be saved as a UNIX File 18 | 19 | if [ -z "$VCAP_APP_PORT" ]; 20 | then SERVER_PORT=80; 21 | else SERVER_PORT="$VCAP_APP_PORT"; 22 | fi 23 | echo port is $SERVER_PORT 24 | echo Performing database initialisations and migrations 25 | python manage.py makemigrations 26 | python manage.py migrate 27 | python manage.py shell < initdbadmin.py 28 | echo [$0] Starting Django Server... 29 | python manage.py runserver 0.0.0.0:$SERVER_PORT --noreload -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2016 IBM Corp. All Rights Reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # This file must be saved as a UNIX File 18 | 19 | if [ -z "$VCAP_APP_PORT" ]; 20 | then SERVER_PORT=80; 21 | else SERVER_PORT="$VCAP_APP_PORT"; 22 | fi 23 | echo port is $SERVER_PORT 24 | echo Performing database initialisations and migrations 25 | python manage.py makemigrations 26 | python manage.py migrate 27 | python manage.py shell < initdbadmin.py 28 | echo [$0] Starting Django Server... 29 | python manage.py runserver 0.0.0.0:$SERVER_PORT --noreload -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2016 IBM Corp. All Rights Reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # This file must be saved as a UNIX File 18 | 19 | if [ -z "$VCAP_APP_PORT" ]; 20 | then SERVER_PORT=80; 21 | else SERVER_PORT="$VCAP_APP_PORT"; 22 | fi 23 | echo port is $SERVER_PORT 24 | echo Performing database initialisations and migrations 25 | python manage.py makemigrations 26 | python manage.py migrate 27 | python manage.py shell < initdbadmin.py 28 | echo [$0] Starting Django Server... 29 | python manage.py runserver 0.0.0.0:$SERVER_PORT --noreload -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2016 IBM Corp. All Rights Reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # This file must be saved as a UNIX File 18 | 19 | if [ -z "$VCAP_APP_PORT" ]; 20 | then SERVER_PORT=80; 21 | else SERVER_PORT="$VCAP_APP_PORT"; 22 | fi 23 | echo port is $SERVER_PORT 24 | echo Performing database initialisations and migrations 25 | python manage.py makemigrations 26 | python manage.py migrate 27 | python manage.py shell < initdbadmin.py 28 | echo [$0] Starting Django Server... 29 | python manage.py runserver 0.0.0.0:$SERVER_PORT --noreload -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Copyright 2016 IBM Corp. All Rights Reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # This file must be saved as a UNIX File 18 | 19 | if [ -z "$VCAP_APP_PORT" ]; 20 | then SERVER_PORT=80; 21 | else SERVER_PORT="$VCAP_APP_PORT"; 22 | fi 23 | echo port is $SERVER_PORT 24 | echo Performing database initialisations and migrations 25 | python manage.py makemigrations 26 | python manage.py migrate 27 | python manage.py shell < initdbadmin.py 28 | echo [$0] Starting Django Server... 29 | python manage.py runserver 0.0.0.0:$SERVER_PORT --noreload 30 | -------------------------------------------------------------------------------- /episode-5/flask/src/watsonutils/vcap.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import os 17 | import json 18 | 19 | def get_vcap_settings(var_service): 20 | """ Pulls VCAP settings from Bluemix environmental values""" 21 | app_vcap_config = os.environ.get('VCAP_SERVICES') 22 | if app_vcap_config: 23 | app_decoded_config = json.loads(app_vcap_config) 24 | for key, value in app_decoded_config.items(): 25 | if key.startswith(var_service): 26 | the_creds = app_decoded_config[key][0]['credentials'] 27 | return the_creds 28 | return None -------------------------------------------------------------------------------- /episode-6/flask/src/watsonutils/vcap.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import os 17 | import json 18 | 19 | def get_vcap_settings(var_service): 20 | """ Pulls VCAP settings from Bluemix environmental values""" 21 | app_vcap_config = os.environ.get('VCAP_SERVICES') 22 | if app_vcap_config: 23 | app_decoded_config = json.loads(app_vcap_config) 24 | for key, value in app_decoded_config.items(): 25 | if key.startswith(var_service): 26 | the_creds = app_decoded_config[key][0]['credentials'] 27 | return the_creds 28 | return None -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/watsonlanguage/watsonutils/vcap.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import os 17 | import json 18 | 19 | def get_vcap_settings(var_service): 20 | """ Pulls VCAP settings from Bluemix environmental values""" 21 | app_vcap_config = os.environ.get('VCAP_SERVICES') 22 | if app_vcap_config: 23 | app_decoded_config = json.loads(app_vcap_config) 24 | for key, value in app_decoded_config.items(): 25 | if key.startswith(var_service): 26 | the_creds = app_decoded_config[key][0]['credentials'] 27 | return the_creds 28 | return None -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/watsonlanguage/watsonutils/vcap.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import os 17 | import json 18 | 19 | def get_vcap_settings(var_service): 20 | """ Pulls VCAP settings from Bluemix environmental values""" 21 | app_vcap_config = os.environ.get('VCAP_SERVICES') 22 | if app_vcap_config: 23 | app_decoded_config = json.loads(app_vcap_config) 24 | for key, value in app_decoded_config.items(): 25 | if key.startswith(var_service): 26 | the_creds = app_decoded_config[key][0]['credentials'] 27 | return the_creds 28 | return None -------------------------------------------------------------------------------- /episode-1/flask/src/templates/watson/wlindex.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | Watson Language Detection Starter 19 | 20 | 21 | 22 |
23 |
24 | {{ info.form.csrf_token }} 25 | {{ info.form.txtdata.label }} {{ info.form.txtdata(rows='8') }} 26 | {{ info.form.submit }} 27 |
28 |
29 |
30 | {% if info.lang %} 31 | Language has been detected as {{ info.lang }} 32 | {% endif %} 33 |
34 |
35 | {% if info.error %} 36 | Error - {{ info.error }} 37 | {% endif %} 38 |
39 | 40 | -------------------------------------------------------------------------------- /episode-2/flask/src/templates/watson/wlindex.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | Watson Language Detection Starter 19 | 20 | 21 | 22 |
23 |
24 | {{ info.form.csrf_token }} 25 | {{ info.form.txtdata.label }} {{ info.form.txtdata(rows='8') }} 26 | {{ info.form.submit }} 27 |
28 |
29 |
30 | {% if info.lang %} 31 | Language has been detected as {{ info.lang }} 32 | {% endif %} 33 |
34 |
35 | {% if info.error %} 36 | Error - {{ info.error }} 37 | {% endif %} 38 |
39 | 40 | -------------------------------------------------------------------------------- /episode-3/flask/src/templates/watson/wlindex.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | Watson Language Detection Starter 19 | 20 | 21 | 22 |
23 |
24 | {{ info.form.csrf_token }} 25 | {{ info.form.txtdata.label }} {{ info.form.txtdata(rows='8') }} 26 | {{ info.form.submit }} 27 |
28 |
29 |
30 | {% if info.lang %} 31 | Language has been detected as {{ info.lang }} 32 | {% endif %} 33 |
34 |
35 | {% if info.error %} 36 | Error - {{ info.error }} 37 | {% endif %} 38 |
39 | 40 | -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/watsonlanguage/templates/watson/wlindex.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | Watson Language Detection Starter 19 | 20 | 21 | 22 |
23 |
24 | {% csrf_token %} 25 | 26 | {{ form.as_table }} 27 |
28 |
29 | 30 |
31 |
32 |
33 |
34 | {% if lang %} 35 | Language has been detected as {{ lang }} 36 | {% endif %} 37 |
38 |
39 | {% if error %} 40 | Error - {{ error }} 41 | {% endif %} 42 |
43 | 44 | -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/watsonlanguage/templates/watson/wlindex.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | Watson Language Detection Starter 19 | 20 | 21 | 22 |
23 |
24 | {% csrf_token %} 25 | 26 | {{ form.as_table }} 27 |
28 |
29 | 30 |
31 |
32 |
33 |
34 | {% if lang %} 35 | Language has been detected as {{ lang }} 36 | {% endif %} 37 |
38 |
39 | {% if error %} 40 | Error - {{ error }} 41 | {% endif %} 42 |
43 | 44 | -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/watsonlanguage/templates/watson/wlindex.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | Watson Language Detection Starter 19 | 20 | 21 | 22 |
23 |
24 | {% csrf_token %} 25 | 26 | {{ form.as_table }} 27 |
28 |
29 | 30 |
31 |
32 |
33 |
34 | {% if lang %} 35 | Language has been detected as {{ lang }} 36 | {% endif %} 37 |
38 |
39 | {% if error %} 40 | Error - {{ error }} 41 | {% endif %} 42 |
43 | 44 | -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/createdbadmin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from django.contrib.auth.models import User 17 | from django.db.utils import IntegrityError 18 | 19 | #Logging doesn't work from manage.py shell 20 | #import logginglogger = logging.getLogger(__name__) 21 | 22 | class MainProgram(object): 23 | def __init__(self): 24 | print('help') 25 | try: 26 | print('initialising') 27 | User.objects.create_superuser (username='', 28 | password='', 29 | email='an-email-address@yourco.com') 30 | except IntegrityError as e: 31 | print ("DB Error Thrown %s" % e) 32 | #logger.warning("DB Error Thrown %s" % e) 33 | -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/createdbadmin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from django.contrib.auth.models import User 17 | from django.db.utils import IntegrityError 18 | 19 | #Logging doesn't work from manage.py shell 20 | #import logginglogger = logging.getLogger(__name__) 21 | 22 | class MainProgram(object): 23 | def __init__(self): 24 | print('help') 25 | try: 26 | print('initialising') 27 | User.objects.create_superuser (username='', 28 | password='', 29 | email='an-email-address@yourco.com') 30 | except IntegrityError as e: 31 | print ("DB Error Thrown %s" % e) 32 | #logger.warning("DB Error Thrown %s" % e) 33 | -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/createdbadmin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from django.contrib.auth.models import User 17 | from django.db.utils import IntegrityError 18 | 19 | #Logging doesn't work from manage.py shell 20 | #import logginglogger = logging.getLogger(__name__) 21 | 22 | class MainProgram(object): 23 | def __init__(self): 24 | print('help') 25 | try: 26 | print('initialising') 27 | User.objects.create_superuser (username='', 28 | password='', 29 | email='an-email-address@yourco.com') 30 | except IntegrityError as e: 31 | print ("DB Error Thrown %s" % e) 32 | #logger.warning("DB Error Thrown %s" % e) 33 | -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/createdbadmin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from django.contrib.auth.models import User 17 | from django.db.utils import IntegrityError 18 | 19 | #Logging doesn't work from manage.py shell 20 | #import logginglogger = logging.getLogger(__name__) 21 | 22 | class MainProgram(object): 23 | def __init__(self): 24 | print('help') 25 | try: 26 | print('initialising') 27 | User.objects.create_superuser (username='', 28 | password='', 29 | email='an-email-address@yourco.com') 30 | except IntegrityError as e: 31 | print ("DB Error Thrown %s" % e) 32 | #logger.warning("DB Error Thrown %s" % e) 33 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/createdbadmin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from django.contrib.auth.models import User 17 | from django.db.utils import IntegrityError 18 | 19 | #Logging doesn't work from manage.py shell 20 | #import logginglogger = logging.getLogger(__name__) 21 | 22 | class MainProgram(object): 23 | def __init__(self): 24 | print('help') 25 | try: 26 | print('initialising') 27 | User.objects.create_superuser (username='', 28 | password='', 29 | email='an-email-address@yourco.com') 30 | except IntegrityError as e: 31 | print ("DB Error Thrown %s" % e) 32 | #logger.warning("DB Error Thrown %s" % e) 33 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/createdbadmin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from django.contrib.auth.models import User 17 | from django.db.utils import IntegrityError 18 | 19 | #Logging doesn't work from manage.py shell 20 | #import logginglogger = logging.getLogger(__name__) 21 | 22 | class MainProgram(object): 23 | def __init__(self): 24 | print('help') 25 | try: 26 | print('initialising') 27 | User.objects.create_superuser (username='', 28 | password='', 29 | email='an-email-address@yourco.com') 30 | except IntegrityError as e: 31 | print ("DB Error Thrown %s" % e) 32 | #logger.warning("DB Error Thrown %s" % e) 33 | -------------------------------------------------------------------------------- /episode-5/flask/src/watsonutils/creds.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import os 17 | import json 18 | 19 | class CredentialStore(object): 20 | """ 21 | Load Credentials from local store 22 | """ 23 | creds = None 24 | 25 | def __init__(self): 26 | super(CredentialStore, self).__init__() 27 | if CredentialStore.creds is None: 28 | module_dir = os.path.dirname(__file__) 29 | file_path = os.path.join(module_dir, 'credentials.json') 30 | print("Looking for file ", file_path) 31 | try: 32 | with open(file_path) as f: 33 | CredentialStore.creds = json.loads(f.read()) 34 | except FileNotFoundError: 35 | print("Credential File was not found") 36 | 37 | def getCreds(self, service): 38 | if CredentialStore.creds: 39 | return CredentialStore.creds.get(service, None) 40 | else: 41 | return None 42 | -------------------------------------------------------------------------------- /episode-6/flask/src/watsonutils/creds.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import os 17 | import json 18 | 19 | class CredentialStore(object): 20 | """ 21 | Load Credentials from local store 22 | """ 23 | creds = None 24 | 25 | def __init__(self): 26 | super(CredentialStore, self).__init__() 27 | if CredentialStore.creds is None: 28 | module_dir = os.path.dirname(__file__) 29 | file_path = os.path.join(module_dir, 'credentials.json') 30 | print("Looking for file ", file_path) 31 | try: 32 | with open(file_path) as f: 33 | CredentialStore.creds = json.loads(f.read()) 34 | except FileNotFoundError: 35 | print("Credential File was not found") 36 | 37 | def getCreds(self, service): 38 | if CredentialStore.creds: 39 | return CredentialStore.creds.get(service, None) 40 | else: 41 | return None 42 | -------------------------------------------------------------------------------- /episode-5/flask/src/watsonutils/baseservice.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import requests 17 | import json 18 | from .creds import CredentialStore 19 | from .vcap import get_vcap_settings 20 | 21 | import logging 22 | logger = logging.getLogger(__name__) 23 | 24 | class BaseService(object): 25 | def __init__(self, serviceName): 26 | super(BaseService, self).__init__() 27 | 28 | self.username = "" 29 | self.password = "" 30 | 31 | creds = get_vcap_settings(serviceName) 32 | if not creds: 33 | credStore = CredentialStore() 34 | creds = credStore.getCreds(serviceName) 35 | if creds: 36 | self.username = str(creds['username']) 37 | self.password = str(creds['password']) 38 | else: 39 | logger.warn("No credentials found for service %s" % serviceName) 40 | 41 | def getUser(self): 42 | return self.username 43 | 44 | def getPassword(self): 45 | return self.password 46 | 47 | 48 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/watsonlanguage/watsonutils/baseservice.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import requests 17 | import json 18 | from .creds import CredentialStore 19 | from .vcap import get_vcap_settings 20 | 21 | import logging 22 | logger = logging.getLogger(__name__) 23 | 24 | class BaseService(object): 25 | def __init__(self, serviceName): 26 | super(BaseService, self).__init__() 27 | 28 | self.username = "" 29 | self.password = "" 30 | 31 | creds = get_vcap_settings(serviceName) 32 | if not creds: 33 | credStore = CredentialStore() 34 | creds = credStore.getCreds(serviceName) 35 | if creds: 36 | self.username = str(creds['username']) 37 | self.password = str(creds['password']) 38 | else: 39 | logger.warn("No credentials found for service %s" % serviceName) 40 | 41 | def getUser(self): 42 | return self.username 43 | 44 | def getPassword(self): 45 | return self.password 46 | 47 | 48 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/watsonlanguage/watsonutils/creds.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import os 17 | import json 18 | 19 | import logging 20 | logger = logging.getLogger(__name__) 21 | 22 | class CredentialStore(object): 23 | """ 24 | Load Credentials from local store 25 | """ 26 | creds = None 27 | 28 | def __init__(self): 29 | super(CredentialStore, self).__init__() 30 | if CredentialStore.creds is None: 31 | module_dir = os.path.dirname(__file__) 32 | file_path = os.path.join(module_dir, 'credentials.json') 33 | logger.info("Looking for file ", file_path) 34 | try: 35 | with open(file_path) as f: 36 | CredentialStore.creds = json.loads(f.read()) 37 | except FileNotFoundError: 38 | logger.info("Credential File was not found") 39 | 40 | def getCreds(self, service): 41 | if CredentialStore.creds: 42 | return CredentialStore.creds.get(service, None) 43 | else: 44 | return None 45 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/watsonlanguage/watsonutils/creds.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import os 17 | import json 18 | 19 | import logging 20 | logger = logging.getLogger(__name__) 21 | 22 | class CredentialStore(object): 23 | """ 24 | Load Credentials from local store 25 | """ 26 | creds = None 27 | 28 | def __init__(self): 29 | super(CredentialStore, self).__init__() 30 | if CredentialStore.creds is None: 31 | module_dir = os.path.dirname(__file__) 32 | file_path = os.path.join(module_dir, 'credentials.json') 33 | logger.info("Looking for file ", file_path) 34 | try: 35 | with open(file_path) as f: 36 | CredentialStore.creds = json.loads(f.read()) 37 | except FileNotFoundError: 38 | logger.info("Credential File was not found") 39 | 40 | def getCreds(self, service): 41 | if CredentialStore.creds: 42 | return CredentialStore.creds.get(service, None) 43 | else: 44 | return None 45 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # python-primer-companion-code 2 | 3 | ## DEPRECATED: this repo is no longer actively maintained. It can still be used as reference, but may contain outdated or unpatched code. 4 | 5 | 6 | ## Episode 1 : [Application Shell and Language Identification](/episode-1/README.md) 7 | This episode guides you through the process of creating Django and Flask application shells, how to debug, 8 | switch on logging and consume the Watson Language Identification service using the python SDK. 9 | 10 | ## Episode 2 : [Language Translator](/episode-2/README.md) 11 | This episode shows how to use the Language Translator service to identify available translations and if available 12 | translate the submitted text into a language that your application is able to process. 13 | 14 | ## Episode 3 : [Natural Language Classification](/episode-3/README.md) 15 | This episode shows how to use the Natural Language service to identify an intent or meaning as a classification of 16 | of the submitted text. 17 | 18 | ## Episode 4 : [REST API](/episode-4/README.md) 19 | This episode shows how to wrap the application functionality into a REST API that can be used by other applications 20 | as well as asynchronously from the web browser. 21 | 22 | ## Episode 5 : [Credential Store](/episode-5/README.md) 23 | This episode shows how to utilise the environment variables that Bluemix makes available to read in the service 24 | credentials. 25 | 26 | ## Episode 6 : [Natural Language Understanding Keywords and Entities](/episode-6/README.md) 27 | This episode shows how to determine the keywords and entities in the submitted text. 28 | 29 | ## Episode 7 : Coming soon 30 | -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/projwatson/urls.py: -------------------------------------------------------------------------------- 1 | # Copyright 2016 IBM Corp. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """projwatson URL Configuration 16 | 17 | The `urlpatterns` list routes URLs to views. For more information please see: 18 | https://docs.djangoproject.com/en/1.9/topics/http/urls/ 19 | Examples: 20 | Function views 21 | 1. Add an import: from my_app import views 22 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 23 | Class-based views 24 | 1. Add an import: from other_app.views import Home 25 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 26 | Including another URLconf 27 | 1. Import the include() function: from django.conf.urls import url, include 28 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 29 | """ 30 | from django.conf.urls import url 31 | from django.contrib import admin 32 | from django.conf.urls import include 33 | 34 | urlpatterns = [ 35 | url(r'^watsonadmin/', admin.site.urls), 36 | url(r'^wl/', include('watsonlanguage.urls', namespace='watsonlang')), 37 | ] 38 | -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/projwatson/urls.py: -------------------------------------------------------------------------------- 1 | # Copyright 2016 IBM Corp. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """projwatson URL Configuration 16 | 17 | The `urlpatterns` list routes URLs to views. For more information please see: 18 | https://docs.djangoproject.com/en/1.9/topics/http/urls/ 19 | Examples: 20 | Function views 21 | 1. Add an import: from my_app import views 22 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 23 | Class-based views 24 | 1. Add an import: from other_app.views import Home 25 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 26 | Including another URLconf 27 | 1. Import the include() function: from django.conf.urls import url, include 28 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 29 | """ 30 | from django.conf.urls import url 31 | from django.contrib import admin 32 | from django.conf.urls import include 33 | 34 | urlpatterns = [ 35 | url(r'^watsonadmin/', admin.site.urls), 36 | url(r'^wl/', include('watsonlanguage.urls', namespace='watsonlang')), 37 | ] 38 | -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/projwatson/urls.py: -------------------------------------------------------------------------------- 1 | # Copyright 2016 IBM Corp. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """projwatson URL Configuration 16 | 17 | The `urlpatterns` list routes URLs to views. For more information please see: 18 | https://docs.djangoproject.com/en/1.9/topics/http/urls/ 19 | Examples: 20 | Function views 21 | 1. Add an import: from my_app import views 22 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 23 | Class-based views 24 | 1. Add an import: from other_app.views import Home 25 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 26 | Including another URLconf 27 | 1. Import the include() function: from django.conf.urls import url, include 28 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 29 | """ 30 | from django.conf.urls import url 31 | from django.contrib import admin 32 | from django.conf.urls import include 33 | 34 | urlpatterns = [ 35 | url(r'^watsonadmin/', admin.site.urls), 36 | url(r'^wl/', include('watsonlanguage.urls', namespace='watsonlang')), 37 | ] 38 | -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/projwatson/urls.py: -------------------------------------------------------------------------------- 1 | # Copyright 2016 IBM Corp. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """projwatson URL Configuration 16 | 17 | The `urlpatterns` list routes URLs to views. For more information please see: 18 | https://docs.djangoproject.com/en/1.9/topics/http/urls/ 19 | Examples: 20 | Function views 21 | 1. Add an import: from my_app import views 22 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 23 | Class-based views 24 | 1. Add an import: from other_app.views import Home 25 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 26 | Including another URLconf 27 | 1. Import the include() function: from django.conf.urls import url, include 28 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 29 | """ 30 | from django.conf.urls import url 31 | from django.contrib import admin 32 | from django.conf.urls import include 33 | 34 | urlpatterns = [ 35 | url(r'^watsonadmin/', admin.site.urls), 36 | url(r'^wl/', include('watsonlanguage.urls', namespace='watsonlang')), 37 | ] 38 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/projwatson/urls.py: -------------------------------------------------------------------------------- 1 | # Copyright 2016 IBM Corp. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """projwatson URL Configuration 16 | 17 | The `urlpatterns` list routes URLs to views. For more information please see: 18 | https://docs.djangoproject.com/en/1.9/topics/http/urls/ 19 | Examples: 20 | Function views 21 | 1. Add an import: from my_app import views 22 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 23 | Class-based views 24 | 1. Add an import: from other_app.views import Home 25 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 26 | Including another URLconf 27 | 1. Import the include() function: from django.conf.urls import url, include 28 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 29 | """ 30 | from django.conf.urls import url 31 | from django.contrib import admin 32 | from django.conf.urls import include 33 | 34 | urlpatterns = [ 35 | url(r'^watsonadmin/', admin.site.urls), 36 | url(r'^wl/', include('watsonlanguage.urls', namespace='watsonlang')), 37 | ] 38 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/projwatson/urls.py: -------------------------------------------------------------------------------- 1 | # Copyright 2016 IBM Corp. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """projwatson URL Configuration 16 | 17 | The `urlpatterns` list routes URLs to views. For more information please see: 18 | https://docs.djangoproject.com/en/1.9/topics/http/urls/ 19 | Examples: 20 | Function views 21 | 1. Add an import: from my_app import views 22 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 23 | Class-based views 24 | 1. Add an import: from other_app.views import Home 25 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 26 | Including another URLconf 27 | 1. Import the include() function: from django.conf.urls import url, include 28 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 29 | """ 30 | from django.conf.urls import url 31 | from django.contrib import admin 32 | from django.conf.urls import include 33 | 34 | urlpatterns = [ 35 | url(r'^watsonadmin/', admin.site.urls), 36 | url(r'^wl/', include('watsonlanguage.urls', namespace='watsonlang')), 37 | ] 38 | -------------------------------------------------------------------------------- /episode-6/flask/src/watsonutils/baseservice.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import requests 17 | import json 18 | from .creds import CredentialStore 19 | from .vcap import get_vcap_settings 20 | 21 | import logging 22 | logger = logging.getLogger(__name__) 23 | 24 | class BaseService(object): 25 | def __init__(self, serviceName): 26 | super(BaseService, self).__init__() 27 | 28 | self.username = "" 29 | self.password = "" 30 | self.apikey = "" 31 | 32 | creds = get_vcap_settings(serviceName) 33 | if not creds: 34 | credStore = CredentialStore() 35 | creds = credStore.getCreds(serviceName) 36 | if creds: 37 | self.username = str(creds.get('username', None)) 38 | self.password = str(creds.get('password', None)) 39 | self.apikey = str(creds.get('apikey', None)) 40 | else: 41 | logger.warn("No credentials found for service %s" % serviceName) 42 | 43 | def getUser(self): 44 | return self.username 45 | 46 | def getPassword(self): 47 | return self.password 48 | 49 | def getAPIKey(self): 50 | return self.apikey 51 | 52 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/watsonlanguage/watsonutils/baseservice.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import requests 17 | import json 18 | from .creds import CredentialStore 19 | from .vcap import get_vcap_settings 20 | 21 | import logging 22 | logger = logging.getLogger(__name__) 23 | 24 | class BaseService(object): 25 | def __init__(self, serviceName): 26 | super(BaseService, self).__init__() 27 | 28 | self.username = "" 29 | self.password = "" 30 | self.apikey = "" 31 | 32 | creds = get_vcap_settings(serviceName) 33 | if not creds: 34 | credStore = CredentialStore() 35 | creds = credStore.getCreds(serviceName) 36 | if creds: 37 | self.username = str(creds.get('username', None)) 38 | self.password = str(creds.get('password', None)) 39 | self.apikey = str(creds.get('apikey', None)) 40 | else: 41 | logger.warn("No credentials found for service %s" % serviceName) 42 | 43 | def getUser(self): 44 | return self.username 45 | 46 | def getPassword(self): 47 | return self.password 48 | 49 | def getAPIKey(self): 50 | return self.apikey 51 | -------------------------------------------------------------------------------- /episode-4/flask/src/templates/watson/wlindex.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | Watson Language Detection Starter 19 | 20 | 21 | 22 |
23 | This application needs JavaScript enabled in your browser! 24 |
25 | 26 |
27 |
28 | {{ info.form.csrf_token }} 29 | {{ info.form.txtdata.label }} {{ info.form.txtdata(rows='8') }} 30 | {{ info.form.submit }} 31 |
32 | 36 |
37 |
38 | {% if info.lang %} 39 | Language has been detected as {{ info.lang }} 40 | {% endif %} 41 |
42 |
43 | 44 | - 45 | 46 |
47 |
48 | {% if info.error %} 49 | Error - {{ info.error }} 50 | {% endif %} 51 |
52 |
53 | 56 | 59 | 60 | -------------------------------------------------------------------------------- /episode-5/flask/src/templates/watson/wlindex.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | Watson Language Detection Starter 19 | 20 | 21 | 22 |
23 | This application needs JavaScript enabled in your browser! 24 |
25 | 26 |
27 |
28 | {{ info.form.csrf_token }} 29 | {{ info.form.txtdata.label }} {{ info.form.txtdata(rows='8') }} 30 | {{ info.form.submit }} 31 |
32 | 36 |
37 |
38 | {% if info.lang %} 39 | Language has been detected as {{ info.lang }} 40 | {% endif %} 41 |
42 |
43 | 44 | - 45 | 46 |
47 |
48 | {% if info.error %} 49 | Error - {{ info.error }} 50 | {% endif %} 51 |
52 |
53 | 56 | 59 | 60 | -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/watsonlanguage/templates/watson/wlindex.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | Watson Language Detection Starter 19 | 20 | 21 | 22 |
23 | This application needs JavaScript enabled in your browser! 24 |
25 |
26 |
27 | {% csrf_token %} 28 | 29 | {{ form.as_table }} 30 |
31 |
32 | 33 |
34 |
35 | 39 |
40 |
41 | {% if lang %} 42 | Language has been detected as {{ lang }} 43 | {% endif %} 44 |
45 |
46 | 47 | - 48 | 49 |
50 |
51 | {% if error %} 52 | Error - {{ error }} 53 | {% endif %} 54 |
55 |
56 | 59 | 62 | 63 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/watsonlanguage/templates/watson/wlindex.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | Watson Language Detection Starter 19 | 20 | 21 | 22 |
23 | This application needs JavaScript enabled in your browser! 24 |
25 |
26 |
27 | {% csrf_token %} 28 | 29 | {{ form.as_table }} 30 |
31 |
32 | 33 |
34 |
35 | 39 |
40 |
41 | {% if lang %} 42 | Language has been detected as {{ lang }} 43 | {% endif %} 44 |
45 |
46 | 47 | - 48 | 49 |
50 |
51 | {% if error %} 52 | Error - {{ error }} 53 | {% endif %} 54 |
55 |
56 | 59 | 62 | 63 | -------------------------------------------------------------------------------- /episode-6/flask/src/templates/watson/wlindex.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | Watson Language Detection Starter 20 | 21 | 22 | 23 |
24 | This application needs JavaScript enabled in your browser! 25 |
26 | 27 |
28 |
29 | {{ info.form.csrf_token }} 30 | {{ info.form.txtdata.label }} {{ info.form.txtdata(rows='8') }} 31 | {{ info.form.submit }} 32 |
33 | 37 |
38 |
39 | {% if info.lang %} 40 | Language has been detected as {{ info.lang }} 41 | {% endif %} 42 |
43 |
44 | 45 | - 46 | 47 | - 48 | 49 | - 50 | 51 |
52 |
53 | {% if info.error %} 54 | Error - {{ info.error }} 55 | {% endif %} 56 |
57 |
58 | 61 | 64 | 65 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/watsonlanguage/templates/watson/wlindex.html: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | Watson Language Detection Starter 20 | 21 | 22 | 23 |
24 | This application needs JavaScript enabled in your browser! 25 |
26 |
27 |
28 | {% csrf_token %} 29 | 30 | {{ form.as_table }} 31 |
32 |
33 | 34 |
35 |
36 | 40 |
41 |
42 | {% if lang %} 43 | Language has been detected as {{ lang }} 44 | {% endif %} 45 |
46 |
47 | 48 | - 49 | 50 |
51 |
52 |
53 |
54 | {% if error %} 55 | Error - {{ error }} 56 | {% endif %} 57 |
58 |
59 | 62 | 65 | 66 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/watsonlanguage/watsonutils/alchemylanguage.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import AlchemyLanguageV1 as AlchemyLanguageService 19 | from watson_developer_cloud import WatsonException 20 | 21 | from .baseservice import BaseService 22 | 23 | import logging 24 | logger = logging.getLogger(__name__) 25 | 26 | class AlchemyLanguageUtils(BaseService): 27 | def __init__(self): 28 | super(AlchemyLanguageUtils, self).__init__("alchemy_api") 29 | self.service = AlchemyLanguageService(api_key=self.getAPIKey()) 30 | 31 | def getAlchemyService(self): 32 | return self.service 33 | 34 | def identifyKeyworkdsAndEntities(self, data): 35 | txt = data.encode("utf-8", "replace") 36 | alchemy_language = self.getAlchemyService() 37 | 38 | alchemyResults = alchemy_language.combined(text=txt, show_source_text=True, 39 | extract=['entity', 'keyword']) 40 | logger.info(json.dumps(alchemyResults, indent=2)) 41 | 42 | primeEntity = None 43 | primeKeyword = None 44 | 45 | if 'entities' in alchemyResults: 46 | entities = alchemyResults['entities'] 47 | if 0 < len(entities): 48 | primeEntity = entities[0].get('text', None) 49 | 50 | if 'keywords' in alchemyResults: 51 | keywords = alchemyResults['keywords'] 52 | if 0 < len(keywords): 53 | primeKeyword = keywords[0].get('text', None) 54 | 55 | 56 | retData = { "prime_entity" : primeEntity, 57 | "prime_keyword" : primeKeyword } 58 | return retData 59 | 60 | 61 | -------------------------------------------------------------------------------- /episode-6/flask/src/watsonutils/alchemylanguage.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import AlchemyLanguageV1 as AlchemyLanguageService 19 | from watson_developer_cloud import WatsonException 20 | 21 | from .baseservice import BaseService 22 | 23 | 24 | class AlchemyLanguageUtils(BaseService): 25 | def __init__(self, app): 26 | self.app = app 27 | super(AlchemyLanguageUtils, self).__init__("alchemy_api") 28 | self.service = AlchemyLanguageService(api_key=self.getAPIKey()) 29 | 30 | def getAlchemyService(self): 31 | return self.service 32 | 33 | def identifyKeyworkdsAndEntities(self, data): 34 | self.app.logger.info('Preparing to invoke AlchemyAPI Language service') 35 | txt = data.encode("utf-8", "replace") 36 | alchemy_language = self.getAlchemyService() 37 | 38 | alchemyResults = alchemy_language.combined(text=txt, show_source_text=True, 39 | extract=['entity', 'keyword']) 40 | self.app.logger.info(json.dumps(alchemyResults, indent=2)) 41 | 42 | primeEntity = None 43 | primeKeyword = None 44 | 45 | if 'entities' in alchemyResults: 46 | entities = alchemyResults['entities'] 47 | if 0 < len(entities): 48 | primeEntity = entities[0].get('text', None) 49 | 50 | if 'keywords' in alchemyResults: 51 | keywords = alchemyResults['keywords'] 52 | if 0 < len(keywords): 53 | primeKeyword = keywords[0].get('text', None) 54 | 55 | 56 | retData = { "prime_entity" : primeEntity, 57 | "prime_keyword" : primeKeyword } 58 | return retData 59 | 60 | 61 | -------------------------------------------------------------------------------- /episode-3/flask/src/naturallanguageclassification.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import WatsonException 19 | from watson_developer_cloud import NaturalLanguageClassifierV1 as NaturalLanguageClassifier 20 | 21 | 22 | class NaturalLanguageClassifierUtils(object): 23 | def __init__(self, app): 24 | super(NaturalLanguageClassifierUtils, self).__init__() 25 | self.app = app 26 | self.service = NaturalLanguageClassifier(username='', 27 | password='') 28 | 29 | def getNLCService(self): 30 | return self.service 31 | 32 | def classifyTheText(self, txt): 33 | self.app.logger.info("About to run the classification") 34 | nlc = self.getNLCService() 35 | classification = {} 36 | 37 | classificationList = nlc.list_classifiers() 38 | if "classifiers" in classificationList: 39 | if "classifier_id" in classificationList["classifiers"][0]: 40 | classID = classificationList["classifiers"][0]['classifier_id'] 41 | status = nlc.get_classifier(classID) 42 | if status.get("status") == "Available": 43 | classes = nlc.classify(classID, txt) 44 | if "classes" in classes: 45 | className = classes["classes"][0]["class_name"] 46 | confidence = classes["classes"][0]["confidence"] 47 | classification = {"confidence": confidence, 48 | "className" : className} 49 | self.app.logger.info(classification) 50 | 51 | return classification 52 | -------------------------------------------------------------------------------- /episode-2/flask/src/translation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import LanguageTranslationV2 as LanguageTranslationService 19 | 20 | 21 | def getTranslationService(): 22 | return LanguageTranslationService(username='', 23 | password='') 24 | 25 | 26 | def identifyLanguage(app, data): 27 | txt = data.encode("utf-8", "replace") 28 | language_translation = getTranslationService() 29 | langsdetected = language_translation.identify(txt) 30 | 31 | app.logger.info(json.dumps(langsdetected, indent=2)) 32 | primarylang = langsdetected["languages"][0] 33 | retData = {key: primarylang[key] for key in ('language', 'confidence')} 34 | app.logger.info(json.dumps(retData, indent=2)) 35 | return retData 36 | 37 | 38 | def checkForTranslation(app, fromlang, tolang): 39 | supportedModels = [] 40 | lt = getTranslationService() 41 | models = lt.list_models() 42 | modelList = models.get("models") 43 | supportedModels = [model['model_id'] for model in modelList 44 | if fromlang == model['source'] 45 | and tolang == model['target']] 46 | return supportedModels 47 | 48 | 49 | def performTranslation(app, txt, primarylang, targetlang): 50 | lt = getTranslationService() 51 | translation = lt.translate(txt, source=primarylang, target=targetlang) 52 | theTranslation = None 53 | if translation and ("translations" in translation): 54 | theTranslation = translation['translations'][0]['translation'] 55 | return theTranslation 56 | -------------------------------------------------------------------------------- /episode-4/flask/src/naturallanguageclassification.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import WatsonException 19 | from watson_developer_cloud import NaturalLanguageClassifierV1 as NaturalLanguageClassifier 20 | 21 | 22 | class NaturalLanguageClassifierUtils(object): 23 | def __init__(self, app): 24 | super(NaturalLanguageClassifierUtils, self).__init__() 25 | self.app = app 26 | self.service = NaturalLanguageClassifier(username='', 27 | password='') 28 | 29 | def getNLCService(self): 30 | return self.service 31 | 32 | def classifyTheText(self, txt): 33 | self.app.logger.info("About to run the classification") 34 | nlc = self.getNLCService() 35 | classification = {} 36 | 37 | classificationList = nlc.list_classifiers() 38 | if "classifiers" in classificationList: 39 | if "classifier_id" in classificationList["classifiers"][0]: 40 | classID = classificationList["classifiers"][0]['classifier_id'] 41 | status = nlc.get_classifier(classID) 42 | if "status" in status and "Available" == status["status"]: 43 | classes = nlc.classify(classID, txt) 44 | if "classes" in classes: 45 | className = classes["classes"][0]["class_name"] 46 | confidence = classes["classes"][0]["confidence"] 47 | classification = {"confidence": confidence, 48 | "className" : className} 49 | self.app.logger.info(classification) 50 | 51 | return classification 52 | -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/watsonlanguage/watsonutils/naturallanguageclassification.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import WatsonException 19 | from watson_developer_cloud import NaturalLanguageClassifierV1 as NaturalLanguageClassifier 20 | 21 | import logging 22 | logger = logging.getLogger(__name__) 23 | 24 | class NaturalLanguageClassifierUtils(object): 25 | def __init__(self): 26 | super(NaturalLanguageClassifierUtils, self).__init__() 27 | self.service = NaturalLanguageClassifier(username='', 28 | password='') 29 | 30 | def getNLCService(self): 31 | return self.service 32 | 33 | def classifyTheText(self, txt): 34 | logger.info("About to run the classification") 35 | nlc = self.getNLCService() 36 | classification = {} 37 | 38 | classificationList = nlc.list_classifiers() 39 | if "classifiers" in classificationList: 40 | if "classifier_id" in classificationList["classifiers"][0]: 41 | classID = classificationList["classifiers"][0]['classifier_id'] 42 | status = nlc.get_classifier(classID) 43 | if "status" in status and "Available" == status["status"]: 44 | classes = nlc.classify(classID, txt) 45 | if "classes" in classes: 46 | className = classes["classes"][0]["class_name"] 47 | confidence = classes["classes"][0]["confidence"] 48 | classification = {"confidence": confidence, 49 | "className" : className} 50 | logger.info(classification) 51 | 52 | return classification 53 | -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/watsonlanguage/watsonutils/naturallanguageclassification.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import WatsonException 19 | from watson_developer_cloud import NaturalLanguageClassifierV1 as NaturalLanguageClassifier 20 | 21 | import logging 22 | logger = logging.getLogger(__name__) 23 | 24 | class NaturalLanguageClassifierUtils(object): 25 | def __init__(self): 26 | super(NaturalLanguageClassifierUtils, self).__init__() 27 | self.service = NaturalLanguageClassifier(username='', 28 | password='') 29 | 30 | def getNLCService(self): 31 | return self.service 32 | 33 | def classifyTheText(self, txt): 34 | logger.info("About to run the classification") 35 | nlc = self.getNLCService() 36 | classification = {} 37 | 38 | classificationList = nlc.list_classifiers() 39 | if "classifiers" in classificationList: 40 | if "classifier_id" in classificationList["classifiers"][0]: 41 | classID = classificationList["classifiers"][0]['classifier_id'] 42 | status = nlc.get_classifier(classID) 43 | if "status" in status and "Available" == status["status"]: 44 | classes = nlc.classify(classID, txt) 45 | if "classes" in classes: 46 | className = classes["classes"][0]["class_name"] 47 | confidence = classes["classes"][0]["confidence"] 48 | classification = {"confidence": confidence, 49 | "className" : className} 50 | logger.info(classification) 51 | 52 | return classification 53 | -------------------------------------------------------------------------------- /episode-5/flask/src/watsonutils/naturallanguageclassification.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import WatsonException 19 | from watson_developer_cloud import NaturalLanguageClassifierV1 as NaturalLanguageClassifier 20 | 21 | from .baseservice import BaseService 22 | 23 | class NaturalLanguageClassifierUtils(BaseService): 24 | def __init__(self, app): 25 | super(NaturalLanguageClassifierUtils, self).__init__("natural_language_classifier") 26 | self.app = app 27 | self.service = NaturalLanguageClassifier(username=self.getUser(), 28 | password=self.getPassword()) 29 | 30 | def getNLCService(self): 31 | return self.service 32 | 33 | def classifyTheText(self, txt): 34 | self.app.logger.info("About to run the classification") 35 | nlc = self.getNLCService() 36 | classification = {} 37 | 38 | classificationList = nlc.list_classifiers() 39 | if "classifiers" in classificationList: 40 | if "classifier_id" in classificationList["classifiers"][0]: 41 | classID = classificationList["classifiers"][0]['classifier_id'] 42 | status = nlc.get_classifier(classID) 43 | if "status" in status and "Available" == status["status"]: 44 | classes = nlc.classify(classID, txt) 45 | if "classes" in classes: 46 | className = classes["classes"][0]["class_name"] 47 | confidence = classes["classes"][0]["confidence"] 48 | classification = {"confidence": confidence, 49 | "className" : className} 50 | self.app.logger.info(classification) 51 | 52 | return classification 53 | -------------------------------------------------------------------------------- /episode-6/flask/src/watsonutils/naturallanguageclassification.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import WatsonException 19 | from watson_developer_cloud import NaturalLanguageClassifierV1 as NaturalLanguageClassifier 20 | 21 | from .baseservice import BaseService 22 | 23 | class NaturalLanguageClassifierUtils(BaseService): 24 | def __init__(self, app): 25 | super(NaturalLanguageClassifierUtils, self).__init__("natural_language_classifier") 26 | self.app = app 27 | self.service = NaturalLanguageClassifier(username=self.getUser(), 28 | password=self.getPassword()) 29 | 30 | def getNLCService(self): 31 | return self.service 32 | 33 | def classifyTheText(self, txt): 34 | self.app.logger.info("About to run the classification") 35 | nlc = self.getNLCService() 36 | classification = {} 37 | 38 | classificationList = nlc.list_classifiers() 39 | if "classifiers" in classificationList: 40 | if "classifier_id" in classificationList["classifiers"][0]: 41 | classID = classificationList["classifiers"][0]['classifier_id'] 42 | status = nlc.get_classifier(classID) 43 | if "status" in status and "Available" == status["status"]: 44 | classes = nlc.classify(classID, txt) 45 | if "classes" in classes: 46 | className = classes["classes"][0]["class_name"] 47 | confidence = classes["classes"][0]["confidence"] 48 | classification = {"confidence": confidence, 49 | "className" : className} 50 | self.app.logger.info(classification) 51 | 52 | return classification 53 | -------------------------------------------------------------------------------- /episode-1/django/src/projwatson/watsonlanguage/views/wl.py: -------------------------------------------------------------------------------- 1 | # Copyright 2016 IBM Corp. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # -*- coding: utf-8 -*- 15 | 16 | from django.shortcuts import render 17 | from django import forms 18 | 19 | from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslation 20 | from watson_developer_cloud import WatsonException 21 | 22 | import json 23 | 24 | import logging 25 | logger = logging.getLogger(__name__) 26 | 27 | class Form_language(forms.Form): 28 | txtdata = forms.CharField(required=True, 29 | label="Text to Process", 30 | widget=forms.Textarea) 31 | 32 | def index(request): 33 | allinfo = {} 34 | form = None 35 | if request.POST: 36 | form = Form_language(request.POST) 37 | if form.is_valid(): 38 | data = form.cleaned_data['txtdata'] 39 | logger.info("Text to be process is %s" % data) 40 | lang = "TBD" 41 | 42 | try: 43 | language_translation = LanguageTranslation(username='', 44 | password='') 45 | langsdetected = language_translation.identify(data) 46 | primarylang = langsdetected["languages"][0]['language'] 47 | confidence = langsdetected["languages"][0]['confidence'] 48 | 49 | lang = "I am %s confident that the language is %s" % (confidence, primarylang) 50 | except WatsonException as err: 51 | allinfo['error'] = err 52 | 53 | allinfo['lang'] = lang 54 | else: 55 | allinfo['error'] = "The form is invalid" 56 | else: 57 | form = Form_language 58 | 59 | allinfo['form'] = form 60 | return render(request, 'watson/wlindex.html', allinfo) 61 | -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/watsonlanguage/static/js/services.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2016 IBM Corp. All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | $(document).ready(function() { 17 | javascriptCheck(); 18 | }); 19 | 20 | 21 | function javascriptCheck() { 22 | // if javascript is enabled on the browser then can 23 | // remove the warning message 24 | $('#no-script').remove(); 25 | } 26 | 27 | function onProcessClick(urlForAPI){ 28 | console.log('Will be Processing REST API ', urlForAPI); 29 | $('#id_language').text(''); 30 | $('#id_classification').text(''); 31 | $('#id_errormessagefromserver').text( 32 | 'Service has been invoked, waiting for response'); 33 | 34 | var ajaxData = "txtdata=" + $('#id_txtdata').val(); 35 | 36 | $.ajax({ 37 | type: 'POST', 38 | url: urlForAPI, 39 | data: ajaxData, 40 | success: processOK, 41 | error: processNotOK 42 | }); 43 | } 44 | 45 | function processNotOK() { 46 | // There was a problem in the request 47 | console.log('REST API call failed'); 48 | $('#id_errormessagefromserver').text('Service has failed'); 49 | } 50 | 51 | function processOK(response) { 52 | console.log('REST API call was good'); 53 | 54 | // Check for Error 55 | var results = response['results']; 56 | if (results) { 57 | var errMessage = results['error']; 58 | if (errMessage) { 59 | $('#id_errormessagefromserver').text(errMessage); 60 | } else { 61 | $('#id_errormessagefromserver').text(''); 62 | } 63 | 64 | console.log(results) 65 | 66 | var language = results['language']; 67 | if (language) { 68 | $('#id_language').text(language); 69 | } 70 | 71 | var classification = results['classification']; 72 | if (classification) { 73 | $('#id_classification').text(classification); 74 | } 75 | } 76 | } 77 | 78 | 79 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/watsonlanguage/static/js/services.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2016 IBM Corp. All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | $(document).ready(function() { 17 | javascriptCheck(); 18 | }); 19 | 20 | 21 | function javascriptCheck() { 22 | // if javascript is enabled on the browser then can 23 | // remove the warning message 24 | $('#no-script').remove(); 25 | } 26 | 27 | function onProcessClick(urlForAPI){ 28 | console.log('Will be Processing REST API ', urlForAPI); 29 | $('#id_language').text(''); 30 | $('#id_classification').text(''); 31 | $('#id_errormessagefromserver').text( 32 | 'Service has been invoked, waiting for response'); 33 | 34 | var ajaxData = "txtdata=" + $('#id_txtdata').val(); 35 | 36 | $.ajax({ 37 | type: 'POST', 38 | url: urlForAPI, 39 | data: ajaxData, 40 | success: processOK, 41 | error: processNotOK 42 | }); 43 | } 44 | 45 | function processNotOK() { 46 | // There was a problem in the request 47 | console.log('REST API call failed'); 48 | $('#id_errormessagefromserver').text('Service has failed'); 49 | } 50 | 51 | function processOK(response) { 52 | console.log('REST API call was good'); 53 | 54 | // Check for Error 55 | var results = response['results']; 56 | if (results) { 57 | var errMessage = results['error']; 58 | if (errMessage) { 59 | $('#id_errormessagefromserver').text(errMessage); 60 | } else { 61 | $('#id_errormessagefromserver').text(''); 62 | } 63 | 64 | console.log(results) 65 | 66 | var language = results['language']; 67 | if (language) { 68 | $('#id_language').text(language); 69 | } 70 | 71 | var classification = results['classification']; 72 | if (classification) { 73 | $('#id_classification').text(classification); 74 | } 75 | } 76 | } 77 | 78 | 79 | -------------------------------------------------------------------------------- /episode-4/flask/src/static/js/services.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2016 IBM Corp. All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | $(document).ready(function() { 18 | javascriptCheck(); 19 | }); 20 | 21 | 22 | function javascriptCheck() { 23 | // if javascript is enabled on the browser then can 24 | // remove the warning message 25 | $('#no-script').remove(); 26 | } 27 | 28 | function onProcessClick(urlForAPI){ 29 | console.log('Will be Processing REST API ', urlForAPI); 30 | $('#id_language').text(''); 31 | $('#id_classification').text(''); 32 | $('#id_errormessagefromserver').text( 33 | 'Service has been invoked, waiting for response'); 34 | 35 | // Flask form doesn't add a id_ prefix to the field ids. 36 | var ajaxData = "txtdata=" + $('#txtdata').val(); 37 | 38 | $.ajax({ 39 | type: 'POST', 40 | url: urlForAPI, 41 | data: ajaxData, 42 | success: processOK, 43 | error: processNotOK 44 | }); 45 | } 46 | 47 | function processNotOK() { 48 | // There was a problem in the request 49 | console.log('REST API call failed'); 50 | $('#id_errormessagefromserver').text('Service has failed'); 51 | } 52 | 53 | function processOK(response) { 54 | console.log('REST API call was good'); 55 | 56 | // Check for Error 57 | var results = response['results']; 58 | if (results) { 59 | var errMessage = results['error']; 60 | if (errMessage) { 61 | $('#id_errormessagefromserver').text(errMessage); 62 | } else { 63 | $('#id_errormessagefromserver').text(''); 64 | } 65 | 66 | console.log(results) 67 | 68 | var language = results['language']; 69 | if (language) { 70 | $('#id_language').text(language); 71 | } 72 | 73 | var classification = results['classification']; 74 | if (classification) { 75 | $('#id_classification').text(classification); 76 | } 77 | } 78 | } 79 | 80 | 81 | -------------------------------------------------------------------------------- /episode-5/flask/src/static/js/services.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2016 IBM Corp. All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | $(document).ready(function() { 18 | javascriptCheck(); 19 | }); 20 | 21 | 22 | function javascriptCheck() { 23 | // if javascript is enabled on the browser then can 24 | // remove the warning message 25 | $('#no-script').remove(); 26 | } 27 | 28 | function onProcessClick(urlForAPI){ 29 | console.log('Will be Processing REST API ', urlForAPI); 30 | $('#id_language').text(''); 31 | $('#id_classification').text(''); 32 | $('#id_errormessagefromserver').text( 33 | 'Service has been invoked, waiting for response'); 34 | 35 | // Flask form doesn't add a id_ prefix to the field ids. 36 | var ajaxData = "txtdata=" + $('#txtdata').val(); 37 | 38 | $.ajax({ 39 | type: 'POST', 40 | url: urlForAPI, 41 | data: ajaxData, 42 | success: processOK, 43 | error: processNotOK 44 | }); 45 | } 46 | 47 | function processNotOK() { 48 | // There was a problem in the request 49 | console.log('REST API call failed'); 50 | $('#id_errormessagefromserver').text('Service has failed'); 51 | } 52 | 53 | function processOK(response) { 54 | console.log('REST API call was good'); 55 | 56 | // Check for Error 57 | var results = response['results']; 58 | if (results) { 59 | var errMessage = results['error']; 60 | if (errMessage) { 61 | $('#id_errormessagefromserver').text(errMessage); 62 | } else { 63 | $('#id_errormessagefromserver').text(''); 64 | } 65 | 66 | console.log(results) 67 | 68 | var language = results['language']; 69 | if (language) { 70 | $('#id_language').text(language); 71 | } 72 | 73 | var classification = results['classification']; 74 | if (classification) { 75 | $('#id_classification').text(classification); 76 | } 77 | } 78 | } 79 | 80 | 81 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/watsonlanguage/watsonutils/naturallanguageclassification.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import WatsonException 19 | from watson_developer_cloud import NaturalLanguageClassifierV1 as NaturalLanguageClassifier 20 | 21 | from .baseservice import BaseService 22 | 23 | import logging 24 | logger = logging.getLogger(__name__) 25 | 26 | class NaturalLanguageClassifierUtils(BaseService): 27 | def __init__(self): 28 | super(NaturalLanguageClassifierUtils, self).__init__("natural_language_classifier") 29 | self.service = NaturalLanguageClassifier(username=self.getUser(), 30 | password=self.getPassword()) 31 | 32 | def getNLCService(self): 33 | return self.service 34 | 35 | def classifyTheText(self, txt): 36 | logger.info("About to run the classification") 37 | nlc = self.getNLCService() 38 | classification = {} 39 | 40 | classificationList = nlc.list_classifiers() 41 | logger.info(classificationList) 42 | if "classifiers" in classificationList: 43 | if 0 == len(classificationList["classifiers"]): 44 | logger.info('No Classifiers found') 45 | elif "classifier_id" in classificationList["classifiers"][0]: 46 | classID = classificationList["classifiers"][0]['classifier_id'] 47 | status = nlc.get_classifier(classID) 48 | if "status" in status and "Available" == status["status"]: 49 | classes = nlc.classify(classID, txt) 50 | if "classes" in classes: 51 | className = classes["classes"][0]["class_name"] 52 | confidence = classes["classes"][0]["confidence"] 53 | classification = {"confidence": confidence, 54 | "className" : className} 55 | logger.info(classification) 56 | 57 | return classification 58 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/watsonlanguage/watsonutils/naturallanguageclassification.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import WatsonException 19 | from watson_developer_cloud import NaturalLanguageClassifierV1 as NaturalLanguageClassifier 20 | 21 | from .baseservice import BaseService 22 | 23 | import logging 24 | logger = logging.getLogger(__name__) 25 | 26 | class NaturalLanguageClassifierUtils(BaseService): 27 | def __init__(self): 28 | super(NaturalLanguageClassifierUtils, self).__init__("natural_language_classifier") 29 | self.service = NaturalLanguageClassifier(username=self.getUser(), 30 | password=self.getPassword()) 31 | 32 | def getNLCService(self): 33 | return self.service 34 | 35 | def classifyTheText(self, txt): 36 | logger.info("About to run the classification") 37 | nlc = self.getNLCService() 38 | classification = {} 39 | 40 | classificationList = nlc.list_classifiers() 41 | logger.info(classificationList) 42 | if "classifiers" in classificationList: 43 | if 0 == len(classificationList["classifiers"]): 44 | logger.info('No Classifiers found') 45 | elif "classifier_id" in classificationList["classifiers"][0]: 46 | classID = classificationList["classifiers"][0]['classifier_id'] 47 | status = nlc.get_classifier(classID) 48 | if "status" in status and "Available" == status["status"]: 49 | classes = nlc.classify(classID, txt) 50 | if "classes" in classes: 51 | className = classes["classes"][0]["class_name"] 52 | confidence = classes["classes"][0]["confidence"] 53 | classification = {"confidence": confidence, 54 | "className" : className} 55 | logger.info(classification) 56 | 57 | return classification 58 | -------------------------------------------------------------------------------- /episode-6/flask/src/watsonutils/naturallanguageunderstanding.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2017 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import NaturalLanguageUnderstandingV1 as NaturalLanguageUnderstanding 19 | from watson_developer_cloud.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions 20 | 21 | from watson_developer_cloud import WatsonException 22 | 23 | from .baseservice import BaseService 24 | 25 | class NaturalLanguageUnderstandingUtils(BaseService): 26 | def __init__(self, app): 27 | self.app = app 28 | super(NaturalLanguageUnderstandingUtils, self).__init__("natural_language_understanding") 29 | 30 | self.service = NaturalLanguageUnderstanding(username=self.getUser(), 31 | password=self.getPassword(), 32 | version="2017-02-27") 33 | 34 | def getNLUService(self): 35 | return self.service 36 | 37 | def identifyKeyworkdsAndEntities(self, data): 38 | self.app.logger.info('Preparing to invoke Natural Language Understanding service') 39 | txt = data.encode("utf-8", "replace") 40 | nlu = self.getNLUService() 41 | 42 | results = nlu.analyze(text=data, return_analyzed_text=True, 43 | features=Features(entities=EntitiesOptions(), keywords=KeywordsOptions())) 44 | 45 | self.app.logger.info(json.dumps(results, indent=2)) 46 | 47 | primeEntity = None 48 | primeKeyword = None 49 | 50 | if 'entities' in results: 51 | entities = results['entities'] 52 | if 0 < len(entities): 53 | primeEntity = entities[0].get('text', None) 54 | 55 | if 'keywords' in results: 56 | keywords = results['keywords'] 57 | if 0 < len(keywords): 58 | primeKeyword = keywords[0].get('text', None) 59 | 60 | 61 | retData = { "prime_entity" : primeEntity, 62 | "prime_keyword" : primeKeyword } 63 | return retData 64 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/watsonlanguage/static/js/services.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2016 IBM Corp. All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | $(document).ready(function() { 18 | javascriptCheck(); 19 | }); 20 | 21 | 22 | function javascriptCheck() { 23 | // if javascript is enabled on the browser then can 24 | // remove the warning message 25 | $('#no-script').remove(); 26 | } 27 | 28 | function onProcessClick(urlForAPI){ 29 | console.log('Will be Processing REST API ', urlForAPI); 30 | $('#id_language').text(''); 31 | $('#id_classification').text(''); 32 | $('#id_outputtext').text(''); 33 | $('#id_errormessagefromserver').text( 34 | 'Service has been invoked, waiting for response'); 35 | 36 | var ajaxData = "txtdata=" + $('#id_txtdata').val(); 37 | 38 | $.ajax({ 39 | type: 'POST', 40 | url: urlForAPI, 41 | data: ajaxData, 42 | success: processOK, 43 | error: processNotOK 44 | }); 45 | } 46 | 47 | function processNotOK() { 48 | // There was a problem in the request 49 | console.log('REST API call failed'); 50 | $('#id_errormessagefromserver').text('Service has failed'); 51 | } 52 | 53 | function processOK(response) { 54 | console.log('REST API call was good'); 55 | 56 | // Check for Error 57 | var results = response['results']; 58 | if (results) { 59 | var errMessage = results['error']; 60 | if (errMessage) { 61 | $('#id_errormessagefromserver').text(errMessage); 62 | } else { 63 | $('#id_errormessagefromserver').text(''); 64 | } 65 | 66 | console.log(results) 67 | 68 | var outputtext = results['outputText']; 69 | if (outputtext) { 70 | $('#id_outputtext').text(outputtext); 71 | } 72 | 73 | var language = results['language']; 74 | if (language) { 75 | $('#id_language').text(language); 76 | } 77 | 78 | var classification = results['classification']; 79 | if (classification) { 80 | $('#id_classification').text(classification); 81 | } 82 | } 83 | } 84 | 85 | 86 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/watsonlanguage/watsonutils/naturallanguageunderstanding.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2017 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import NaturalLanguageUnderstandingV1 as NaturalLanguageUnderstanding 19 | from watson_developer_cloud.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions 20 | 21 | from watson_developer_cloud import WatsonException 22 | 23 | from .baseservice import BaseService 24 | 25 | import logging 26 | logger = logging.getLogger(__name__) 27 | 28 | class NaturalLanguageUnderstandingUtils(BaseService): 29 | def __init__(self): 30 | super(NaturalLanguageUnderstandingUtils, self).__init__("natural_language_understanding") 31 | 32 | self.service = NaturalLanguageUnderstanding(username=self.getUser(), 33 | password=self.getPassword(), 34 | version="2017-02-27") 35 | 36 | def getNLUService(self): 37 | return self.service 38 | 39 | def identifyKeyworkdsAndEntities(self, data): 40 | logger.info('Preparing to invoke Natural Language Understanding service') 41 | txt = data.encode("utf-8", "replace") 42 | nlu = self.getNLUService() 43 | 44 | results = nlu.analyze(text=data, return_analyzed_text=True, 45 | features=Features(entities=EntitiesOptions(), keywords=KeywordsOptions())) 46 | 47 | logger.info(json.dumps(results, indent=2)) 48 | 49 | primeEntity = None 50 | primeKeyword = None 51 | 52 | if 'entities' in results: 53 | entities = results['entities'] 54 | if 0 < len(entities): 55 | primeEntity = entities[0].get('text', None) 56 | 57 | if 'keywords' in results: 58 | keywords = results['keywords'] 59 | if 0 < len(keywords): 60 | primeKeyword = keywords[0].get('text', None) 61 | 62 | 63 | retData = { "prime_entity" : primeEntity, 64 | "prime_keyword" : primeKeyword } 65 | return retData 66 | -------------------------------------------------------------------------------- /episode-6/flask/src/static/js/services.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2016 IBM Corp. All Rights Reserved. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | $(document).ready(function() { 18 | javascriptCheck(); 19 | }); 20 | 21 | 22 | function javascriptCheck() { 23 | // if javascript is enabled on the browser then can 24 | // remove the warning message 25 | $('#no-script').remove(); 26 | } 27 | 28 | function onProcessClick(urlForAPI){ 29 | console.log('Will be Processing REST API ', urlForAPI); 30 | $('#id_language').text(''); 31 | $('#id_classification').text(''); 32 | $('#id_entity').text(''); 33 | $('#id_keyword').text(''); 34 | $('#id_errormessagefromserver').text( 35 | 'Service has been invoked, waiting for response'); 36 | 37 | // Flask form doesn't add a id_ prefix to the field ids. 38 | var ajaxData = "txtdata=" + $('#txtdata').val(); 39 | 40 | $.ajax({ 41 | type: 'POST', 42 | url: urlForAPI, 43 | data: ajaxData, 44 | success: processOK, 45 | error: processNotOK 46 | }); 47 | } 48 | 49 | function processNotOK() { 50 | // There was a problem in the request 51 | console.log('REST API call failed'); 52 | $('#id_errormessagefromserver').text('Service has failed'); 53 | } 54 | 55 | function processOK(response) { 56 | console.log('REST API call was good'); 57 | 58 | // Check for Error 59 | var results = response['results']; 60 | if (results) { 61 | var errMessage = results['error']; 62 | if (errMessage) { 63 | $('#id_errormessagefromserver').text(errMessage); 64 | } else { 65 | $('#id_errormessagefromserver').text(''); 66 | } 67 | 68 | console.log(results) 69 | 70 | var language = results['language']; 71 | if (language) { 72 | $('#id_language').text(language); 73 | } 74 | 75 | var classification = results['classification']; 76 | if (classification) { 77 | $('#id_classification').text(classification); 78 | } 79 | 80 | var entity = results['primary_entity']; 81 | if (entity) { 82 | $('#id_entity').text(entity); 83 | } 84 | 85 | var keyword = results['primary_keyword']; 86 | if (keyword) { 87 | $('#id_keyword').text(keyword); 88 | } 89 | 90 | } 91 | } 92 | 93 | 94 | -------------------------------------------------------------------------------- /episode-3/flask/src/languagetranslation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslationService 19 | from watson_developer_cloud import WatsonException 20 | 21 | 22 | class LanguageTranslationUtils(object): 23 | def __init__(self, app): 24 | super(LanguageTranslationUtils, self).__init__() 25 | self.app = app 26 | self.service = LanguageTranslationService(username='', 27 | password='') 28 | 29 | def getTranslationService(self): 30 | return self.service 31 | 32 | def identifyLanguage(self, data): 33 | txt = data.encode("utf-8", "replace") 34 | language_translation = self.getTranslationService() 35 | langsdetected = language_translation.identify(txt) 36 | 37 | self.app.logger.info(json.dumps(langsdetected, indent=2)) 38 | self.app.logger.info(langsdetected["languages"][0]['language']) 39 | self.app.logger.info(langsdetected["languages"][0]['confidence']) 40 | 41 | primarylang = langsdetected["languages"][0]['language'] 42 | confidence = langsdetected["languages"][0]['confidence'] 43 | 44 | retData = { "language" : primarylang, 45 | "confidence" : confidence } 46 | return retData 47 | 48 | 49 | def checkForTranslation(self, fromlang, tolang): 50 | supportedModels = [] 51 | lt = self.getTranslationService() 52 | models = lt.list_models() 53 | if models and ("models" in models): 54 | modelList = models["models"] 55 | for model in modelList: 56 | if fromlang == model['source'] and tolang == model['target']: 57 | supportedModels.append(model['model_id']) 58 | return supportedModels 59 | 60 | def performTranslation(self, txt, primarylang, targetlang): 61 | lt = self.getTranslationService() 62 | translation = lt.translate(txt, source=primarylang, target=targetlang) 63 | theTranslation = None 64 | if translation and ("translations" in translation): 65 | theTranslation = translation['translations'][0]['translation'] 66 | return theTranslation 67 | -------------------------------------------------------------------------------- /episode-4/flask/src/languagetranslation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslationService 19 | from watson_developer_cloud import WatsonException 20 | 21 | 22 | class LanguageTranslationUtils(object): 23 | def __init__(self, app): 24 | super(LanguageTranslationUtils, self).__init__() 25 | self.app = app 26 | self.service = LanguageTranslationService(username='', 27 | password='') 28 | 29 | def getTranslationService(self): 30 | return self.service 31 | 32 | def identifyLanguage(self, data): 33 | txt = data.encode("utf-8", "replace") 34 | language_translation = self.getTranslationService() 35 | langsdetected = language_translation.identify(txt) 36 | 37 | self.app.logger.info(json.dumps(langsdetected, indent=2)) 38 | self.app.logger.info(langsdetected["languages"][0]['language']) 39 | self.app.logger.info(langsdetected["languages"][0]['confidence']) 40 | 41 | primarylang = langsdetected["languages"][0]['language'] 42 | confidence = langsdetected["languages"][0]['confidence'] 43 | 44 | retData = { "language" : primarylang, 45 | "confidence" : confidence } 46 | return retData 47 | 48 | 49 | def checkForTranslation(self, fromlang, tolang): 50 | supportedModels = [] 51 | lt = self.getTranslationService() 52 | models = lt.list_models() 53 | if models and ("models" in models): 54 | modelList = models["models"] 55 | for model in modelList: 56 | if fromlang == model['source'] and tolang == model['target']: 57 | supportedModels.append(model['model_id']) 58 | return supportedModels 59 | 60 | def performTranslation(self, txt, primarylang, targetlang): 61 | lt = self.getTranslationService() 62 | translation = lt.translate(txt, source=primarylang, target=targetlang) 63 | theTranslation = None 64 | if translation and ("translations" in translation): 65 | theTranslation = translation['translations'][0]['translation'] 66 | return theTranslation 67 | -------------------------------------------------------------------------------- /episode-5/flask/src/watsonutils/languagetranslation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslationService 19 | from watson_developer_cloud import WatsonException 20 | 21 | from .baseservice import BaseService 22 | 23 | class LanguageTranslationUtils(BaseService): 24 | def __init__(self, app): 25 | super(LanguageTranslationUtils, self).__init__("language_translator") 26 | self.app = app 27 | self.service = LanguageTranslationService(username=self.getUser(), 28 | password=self.getPassword()) 29 | 30 | def getTranslationService(self): 31 | return self.service 32 | 33 | def identifyLanguage(self, data): 34 | txt = data.encode("utf-8", "replace") 35 | language_translation = self.getTranslationService() 36 | langsdetected = language_translation.identify(txt) 37 | 38 | self.app.logger.info(json.dumps(langsdetected, indent=2)) 39 | self.app.logger.info(langsdetected["languages"][0]['language']) 40 | self.app.logger.info(langsdetected["languages"][0]['confidence']) 41 | 42 | primarylang = langsdetected["languages"][0]['language'] 43 | confidence = langsdetected["languages"][0]['confidence'] 44 | 45 | retData = { "language" : primarylang, 46 | "confidence" : confidence } 47 | return retData 48 | 49 | 50 | def checkForTranslation(self, fromlang, tolang): 51 | supportedModels = [] 52 | lt = self.getTranslationService() 53 | models = lt.list_models() 54 | if models and ("models" in models): 55 | modelList = models["models"] 56 | for model in modelList: 57 | if fromlang == model['source'] and tolang == model['target']: 58 | supportedModels.append(model['model_id']) 59 | return supportedModels 60 | 61 | def performTranslation(self, txt, primarylang, targetlang): 62 | lt = self.getTranslationService() 63 | translation = lt.translate(txt, source=primarylang, target=targetlang) 64 | theTranslation = None 65 | if translation and ("translations" in translation): 66 | theTranslation = translation['translations'][0]['translation'] 67 | return theTranslation 68 | -------------------------------------------------------------------------------- /episode-6/flask/src/watsonutils/languagetranslation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslationService 19 | from watson_developer_cloud import WatsonException 20 | 21 | from .baseservice import BaseService 22 | 23 | class LanguageTranslationUtils(BaseService): 24 | def __init__(self, app): 25 | super(LanguageTranslationUtils, self).__init__("language_translator") 26 | self.app = app 27 | self.service = LanguageTranslationService(username=self.getUser(), 28 | password=self.getPassword()) 29 | 30 | def getTranslationService(self): 31 | return self.service 32 | 33 | def identifyLanguage(self, data): 34 | txt = data.encode("utf-8", "replace") 35 | language_translation = self.getTranslationService() 36 | langsdetected = language_translation.identify(txt) 37 | 38 | self.app.logger.info(json.dumps(langsdetected, indent=2)) 39 | self.app.logger.info(langsdetected["languages"][0]['language']) 40 | self.app.logger.info(langsdetected["languages"][0]['confidence']) 41 | 42 | primarylang = langsdetected["languages"][0]['language'] 43 | confidence = langsdetected["languages"][0]['confidence'] 44 | 45 | retData = { "language" : primarylang, 46 | "confidence" : confidence } 47 | return retData 48 | 49 | 50 | def checkForTranslation(self, fromlang, tolang): 51 | supportedModels = [] 52 | lt = self.getTranslationService() 53 | models = lt.list_models() 54 | if models and ("models" in models): 55 | modelList = models["models"] 56 | for model in modelList: 57 | if fromlang == model['source'] and tolang == model['target']: 58 | supportedModels.append(model['model_id']) 59 | return supportedModels 60 | 61 | def performTranslation(self, txt, primarylang, targetlang): 62 | lt = self.getTranslationService() 63 | translation = lt.translate(txt, source=primarylang, target=targetlang) 64 | theTranslation = None 65 | if translation and ("translations" in translation): 66 | theTranslation = translation['translations'][0]['translation'] 67 | return theTranslation 68 | -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/watsonlanguage/watsonutils/languagetranslation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslationService 19 | from watson_developer_cloud import WatsonException 20 | 21 | 22 | import logging 23 | logger = logging.getLogger(__name__) 24 | 25 | class LanguageTranslationUtils(object): 26 | def __init__(self): 27 | super(LanguageTranslationUtils, self).__init__() 28 | self.service = LanguageTranslationService(username='', 29 | password='') 30 | 31 | def getTranslationService(self): 32 | return self.service 33 | 34 | def identifyLanguage(self, data): 35 | txt = data.encode("utf-8", "replace") 36 | language_translation = self.getTranslationService() 37 | langsdetected = language_translation.identify(txt) 38 | 39 | logger.info(json.dumps(langsdetected, indent=2)) 40 | logger.info(langsdetected["languages"][0]['language']) 41 | logger.info(langsdetected["languages"][0]['confidence']) 42 | 43 | primarylang = langsdetected["languages"][0]['language'] 44 | confidence = langsdetected["languages"][0]['confidence'] 45 | 46 | retData = { "language" : primarylang, 47 | "confidence" : confidence } 48 | return retData 49 | 50 | 51 | def checkForTranslation(self, fromlang, tolang): 52 | supportedModels = [] 53 | lt = self.getTranslationService() 54 | models = lt.list_models() 55 | if models and ("models" in models): 56 | modelList = models["models"] 57 | for model in modelList: 58 | if fromlang == model['source'] and tolang == model['target']: 59 | supportedModels.append(model['model_id']) 60 | return supportedModels 61 | 62 | def performTranslation(self, txt, primarylang, targetlang): 63 | lt = self.getTranslationService() 64 | translation = lt.translate(txt, source=primarylang, target=targetlang) 65 | theTranslation = None 66 | if translation and ("translations" in translation): 67 | theTranslation = translation['translations'][0]['translation'] 68 | return theTranslation 69 | -------------------------------------------------------------------------------- /episode-4/django/src/projwatson/watsonlanguage/watsonutils/languagetranslation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslationService 19 | from watson_developer_cloud import WatsonException 20 | 21 | 22 | import logging 23 | logger = logging.getLogger(__name__) 24 | 25 | class LanguageTranslationUtils(object): 26 | def __init__(self): 27 | super(LanguageTranslationUtils, self).__init__() 28 | self.service = LanguageTranslationService(username='', 29 | password='') 30 | 31 | def getTranslationService(self): 32 | return self.service 33 | 34 | def identifyLanguage(self, data): 35 | txt = data.encode("utf-8", "replace") 36 | language_translation = self.getTranslationService() 37 | langsdetected = language_translation.identify(txt) 38 | 39 | logger.info(json.dumps(langsdetected, indent=2)) 40 | logger.info(langsdetected["languages"][0]['language']) 41 | logger.info(langsdetected["languages"][0]['confidence']) 42 | 43 | primarylang = langsdetected["languages"][0]['language'] 44 | confidence = langsdetected["languages"][0]['confidence'] 45 | 46 | retData = { "language" : primarylang, 47 | "confidence" : confidence } 48 | return retData 49 | 50 | 51 | def checkForTranslation(self, fromlang, tolang): 52 | supportedModels = [] 53 | lt = self.getTranslationService() 54 | models = lt.list_models() 55 | if models and ("models" in models): 56 | modelList = models["models"] 57 | for model in modelList: 58 | if fromlang == model['source'] and tolang == model['target']: 59 | supportedModels.append(model['model_id']) 60 | return supportedModels 61 | 62 | def performTranslation(self, txt, primarylang, targetlang): 63 | lt = self.getTranslationService() 64 | translation = lt.translate(txt, source=primarylang, target=targetlang) 65 | theTranslation = None 66 | if translation and ("translations" in translation): 67 | theTranslation = translation['translations'][0]['translation'] 68 | return theTranslation 69 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/watsonlanguage/watsonutils/languagetranslation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslationService 19 | from watson_developer_cloud import WatsonException 20 | 21 | from .baseservice import BaseService 22 | 23 | import logging 24 | logger = logging.getLogger(__name__) 25 | 26 | class LanguageTranslationUtils(BaseService): 27 | def __init__(self): 28 | super(LanguageTranslationUtils, self).__init__("language_translator") 29 | self.service = LanguageTranslationService(username=self.getUser(), 30 | password=self.getPassword()) 31 | 32 | def getTranslationService(self): 33 | return self.service 34 | 35 | def identifyLanguage(self, data): 36 | txt = data.encode("utf-8", "replace") 37 | language_translation = self.getTranslationService() 38 | langsdetected = language_translation.identify(txt) 39 | 40 | logger.info(json.dumps(langsdetected, indent=2)) 41 | logger.info(langsdetected["languages"][0]['language']) 42 | logger.info(langsdetected["languages"][0]['confidence']) 43 | 44 | primarylang = langsdetected["languages"][0]['language'] 45 | confidence = langsdetected["languages"][0]['confidence'] 46 | 47 | retData = { "language" : primarylang, 48 | "confidence" : confidence } 49 | return retData 50 | 51 | 52 | def checkForTranslation(self, fromlang, tolang): 53 | supportedModels = [] 54 | lt = self.getTranslationService() 55 | models = lt.list_models() 56 | if models and ("models" in models): 57 | modelList = models["models"] 58 | for model in modelList: 59 | if fromlang == model['source'] and tolang == model['target']: 60 | supportedModels.append(model['model_id']) 61 | return supportedModels 62 | 63 | def performTranslation(self, txt, primarylang, targetlang): 64 | lt = self.getTranslationService() 65 | translation = lt.translate(txt, source=primarylang, target=targetlang) 66 | theTranslation = None 67 | if translation and ("translations" in translation): 68 | theTranslation = translation['translations'][0]['translation'] 69 | return theTranslation 70 | -------------------------------------------------------------------------------- /episode-6/django/src/projwatson/watsonlanguage/watsonutils/languagetranslation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import json 17 | 18 | from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslationService 19 | from watson_developer_cloud import WatsonException 20 | 21 | from .baseservice import BaseService 22 | 23 | import logging 24 | logger = logging.getLogger(__name__) 25 | 26 | class LanguageTranslationUtils(BaseService): 27 | def __init__(self): 28 | super(LanguageTranslationUtils, self).__init__("language_translator") 29 | self.service = LanguageTranslationService(username=self.getUser(), 30 | password=self.getPassword()) 31 | 32 | def getTranslationService(self): 33 | return self.service 34 | 35 | def identifyLanguage(self, data): 36 | txt = data.encode("utf-8", "replace") 37 | language_translation = self.getTranslationService() 38 | langsdetected = language_translation.identify(txt) 39 | 40 | logger.info(json.dumps(langsdetected, indent=2)) 41 | logger.info(langsdetected["languages"][0]['language']) 42 | logger.info(langsdetected["languages"][0]['confidence']) 43 | 44 | primarylang = langsdetected["languages"][0]['language'] 45 | confidence = langsdetected["languages"][0]['confidence'] 46 | 47 | retData = { "language" : primarylang, 48 | "confidence" : confidence } 49 | return retData 50 | 51 | 52 | def checkForTranslation(self, fromlang, tolang): 53 | supportedModels = [] 54 | lt = self.getTranslationService() 55 | models = lt.list_models() 56 | if models and ("models" in models): 57 | modelList = models["models"] 58 | for model in modelList: 59 | if fromlang == model['source'] and tolang == model['target']: 60 | supportedModels.append(model['model_id']) 61 | return supportedModels 62 | 63 | def performTranslation(self, txt, primarylang, targetlang): 64 | lt = self.getTranslationService() 65 | translation = lt.translate(txt, source=primarylang, target=targetlang) 66 | theTranslation = None 67 | if translation and ("translations" in translation): 68 | theTranslation = translation['translations'][0]['translation'] 69 | return theTranslation 70 | -------------------------------------------------------------------------------- /episode-3/django/src/projwatson/watsonlanguage/views/wl.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from django.shortcuts import render 17 | from django import forms 18 | 19 | from watson_developer_cloud import WatsonException 20 | 21 | from watsonlanguage.watsonutils.languagetranslation import LanguageTranslationUtils 22 | from watsonlanguage.watsonutils.naturallanguageclassification import NaturalLanguageClassifierUtils 23 | 24 | import json 25 | 26 | import logging 27 | logger = logging.getLogger(__name__) 28 | 29 | class Form_language(forms.Form): 30 | txtdata = forms.CharField(required=True, 31 | label="Text to Process", 32 | widget=forms.Textarea) 33 | 34 | def index(request): 35 | allinfo = {} 36 | outputTxt = "TBD" 37 | targetlang = 'en' 38 | classification = None 39 | form = None 40 | if request.POST: 41 | form = Form_language(request.POST) 42 | if form.is_valid(): 43 | data = form.cleaned_data['txtdata'] 44 | logger.info("Text to be process is %s" % data) 45 | lang = "TBD" 46 | 47 | try: 48 | ltu = LanguageTranslationUtils() 49 | nlcu = NaturalLanguageClassifierUtils() 50 | lang = ltu.identifyLanguage(data) 51 | primarylang = lang["language"] 52 | confidence = lang["confidence"] 53 | 54 | outputTxt = "I am %s confident that the language is %s" % (confidence, primarylang) 55 | if targetlang != primarylang: 56 | supportedModels = ltu.checkForTranslation(primarylang, targetlang) 57 | if supportedModels: 58 | englishTxt = ltu.performTranslation(data, primarylang, targetlang) 59 | outputTxt += ", which in english is %s" % englishTxt 60 | 61 | classification = nlcu.classifyTheText(englishTxt) 62 | else: 63 | outputTxt += ", which unfortunately we can't translate into English" 64 | else: 65 | classification = nlcu.classifyTheText(data) 66 | if classification: 67 | outputTxt += "(and %s confident that it is %s classification)" \ 68 | % (classification['confidence'], 69 | classification['className']) 70 | except WatsonException as err: 71 | allinfo['error'] = err 72 | 73 | allinfo['lang'] = outputTxt 74 | else: 75 | allinfo['error'] = "The form is invalid" 76 | else: 77 | form = Form_language 78 | 79 | allinfo['form'] = form 80 | return render(request, 'watson/wlindex.html', allinfo) 81 | 82 | 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /episode-1/flask/src/watson.py: -------------------------------------------------------------------------------- 1 | # Copyright 2016 IBM Corp. All Rights Reserved. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import os 16 | 17 | from flask import Flask, render_template, redirect, session, url_for 18 | from flask.ext.wtf import Form 19 | from wtforms import TextAreaField, SubmitField 20 | from wtforms.validators import Required 21 | 22 | from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslation 23 | from watson_developer_cloud import WatsonException 24 | 25 | # Initialise the application and the secret key needed for CSRF protected form 26 | # submission. 27 | # You should change the secret key to something that is secret and complex. 28 | app = Flask(__name__) 29 | app.config['SECRET_KEY'] = 'please subtitute this string with something hard to guess' 30 | 31 | 32 | # The form containing the text to be processed that the application web page 33 | # will be submitted 34 | class LangForm(Form): 35 | txtdata = TextAreaField('Text to process', validators=[Required()]) 36 | submit = SubmitField('Process') 37 | 38 | 39 | # As this is the only route defined in this application, so far, it is the only 40 | # page that the application will respond to. 41 | @app.route('/wl/lang', methods=['GET', 'POST']) 42 | def wlhome(): 43 | # This is how you do logging, in this case information messages. 44 | app.logger.info('wlhome page requested') 45 | allinfo = {} 46 | lang = 'TBD' 47 | txt = None 48 | form = LangForm() 49 | # If the form passes this check, then its a POST and the fields are valid. 50 | # ie. if the request is a GET then this check fails. 51 | if form.validate_on_submit(): 52 | lang = 'TBC' 53 | txt = form.txtdata.data 54 | form.txtdata.data = '' 55 | 56 | try: 57 | language_translation = LanguageTranslation(username='', 58 | password='') 59 | langsdetected = language_translation.identify(txt) 60 | primarylang = langsdetected["languages"][0] 61 | 62 | lang = "I am {confidence} confident that the language is {language}.".format(**primarylang) 63 | session['langtext'] = lang 64 | 65 | allinfo['lang'] = lang 66 | allinfo['form'] = form 67 | return redirect(url_for('wlhome')) 68 | except WatsonException as err: 69 | allinfo['error'] = err 70 | 71 | allinfo['lang'] = session.get('langtext') 72 | allinfo['form'] = form 73 | return render_template('watson/wlindex.html', info=allinfo) 74 | 75 | 76 | port = os.getenv('PORT', 5000) 77 | if __name__ == "__main__": 78 | app.run(host='0.0.0.0', port=int(port), debug=True) 79 | -------------------------------------------------------------------------------- /episode-2/flask/src/watson.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import os 17 | import json 18 | 19 | from flask import Flask, jsonify, render_template, redirect, session, url_for 20 | from flask.ext.wtf import Form 21 | from wtforms import TextAreaField, SubmitField 22 | from wtforms.validators import Required 23 | 24 | from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslation 25 | from watson_developer_cloud import WatsonException 26 | 27 | # Initialise the application and the secret key needed for CSRF protected form submission. 28 | # You should change the secret key to something that is secret and complex. 29 | app = Flask(__name__) 30 | app.config['SECRET_KEY'] = 'please subtitute this string with something hard to guess' 31 | 32 | # The form containing the text to be processed that the application web page will be submitted/ 33 | class LangForm(Form): 34 | txtdata = TextAreaField('Text to process', validators=[Required()]) 35 | submit = SubmitField('Process') 36 | 37 | # As this is the only route defined in this application, so far, it is the only page that 38 | # the application will respond to. 39 | @app.route('/wl/lang', methods=['GET', 'POST']) 40 | def wlhome(): 41 | # This is how you do logging, in this case information messages. 42 | app.logger.info('wlhome page requested') 43 | allinfo = {} 44 | lang = "TBD" 45 | txt = None 46 | form = LangForm() 47 | # If the form passes this check, then its a POST and the fields are valid. ie. if the 48 | # request is a GET then this check fails. 49 | if form.validate_on_submit(): 50 | lang = "TBC" 51 | txt = form.txtdata.data 52 | form.txtdata.data = '' 53 | 54 | try: 55 | language_translation = LanguageTranslation(username='', 56 | password='') 57 | langsdetected = language_translation.identify(txt) 58 | primarylang = langsdetected["languages"][0]['language'] 59 | confidence = langsdetected["languages"][0]['confidence'] 60 | 61 | lang = "I am %s confident that the language is %s" % (confidence, primarylang) 62 | session['langtext'] = lang 63 | 64 | allinfo['lang'] = lang 65 | allinfo['form'] = form 66 | return redirect(url_for('wlhome')) 67 | except WatsonException as err: 68 | allinfo['error'] = err 69 | 70 | allinfo['lang'] = session.get('langtext') 71 | allinfo['form'] = form 72 | return render_template('watson/wlindex.html', info=allinfo) 73 | 74 | port = os.getenv('PORT', '5000') 75 | if __name__ == "__main__": 76 | app.run(host='0.0.0.0', port=int(port), debug=True) 77 | -------------------------------------------------------------------------------- /episode-3/flask/src/watson.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import os 17 | import json 18 | 19 | from flask import Flask, jsonify, render_template, redirect, session, url_for 20 | from flask.ext.wtf import Form 21 | from wtforms import TextAreaField, SubmitField 22 | from wtforms.validators import Required 23 | 24 | from watson_developer_cloud import WatsonException 25 | 26 | from languagetranslation import LanguageTranslationUtils 27 | from naturallanguageclassification import NaturalLanguageClassifierUtils 28 | 29 | 30 | app = Flask(__name__) 31 | app.config['SECRET_KEY'] = 'please subtittute this string with something hard to guess' 32 | 33 | class LangForm(Form): 34 | txtdata = TextAreaField('Text to process', validators=[Required()]) 35 | submit = SubmitField('Process') 36 | 37 | @app.route('/wl/lang', methods=['GET', 'POST']) 38 | def wlhome(): 39 | app.logger.info('wlhome page requested') 40 | allinfo = {} 41 | outputTxt = "TBD" 42 | targetlang = 'en' 43 | lang = "TBD" 44 | txt = None 45 | form = LangForm() 46 | if form.validate_on_submit(): 47 | lang = "TBC" 48 | txt = form.txtdata.data 49 | form.txtdata.data = '' 50 | 51 | try: 52 | ltu = LanguageTranslationUtils(app) 53 | nlcu = NaturalLanguageClassifierUtils(app) 54 | lang = ltu.identifyLanguage(txt) 55 | primarylang = lang["language"] 56 | confidence = lang["confidence"] 57 | 58 | outputTxt = "I am %s confident that the language is %s" % (confidence, primarylang) 59 | if targetlang != primarylang: 60 | supportedModels = ltu.checkForTranslation(primarylang, targetlang) 61 | if supportedModels: 62 | englishTxt = ltu.performTranslation(txt, primarylang, targetlang) 63 | outputTxt += ", which in english is %s" % englishTxt 64 | classification = nlcu.classifyTheText(englishTxt) 65 | else: 66 | outputTxt += ", which unfortunately we can't translate into English" 67 | else: 68 | classification = nlcu.classifyTheText(txt) 69 | if classification: 70 | outputTxt += "(and %s confident that it is %s classification)" \ 71 | % (classification['confidence'], 72 | classification['className']) 73 | 74 | session['langtext'] = outputTxt 75 | 76 | allinfo['lang'] = lang 77 | allinfo['form'] = form 78 | return redirect(url_for('wlhome')) 79 | except WatsonException as err: 80 | allinfo['error'] = err 81 | 82 | allinfo['lang'] = session.get('langtext') 83 | allinfo['form'] = form 84 | return render_template('watson/wlindex.html', info=allinfo) 85 | 86 | port = os.getenv('PORT', '5000') 87 | if __name__ == "__main__": 88 | app.run(host='0.0.0.0', port=int(port), debug=True) 89 | -------------------------------------------------------------------------------- /episode-2/django/src/projwatson/watsonlanguage/views/wl.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016 IBM Corp. All Rights Reserved. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # https://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | from django.shortcuts import render 17 | from django import forms 18 | 19 | from watson_developer_cloud import LanguageTranslatorV2 as LanguageTranslationService 20 | from watson_developer_cloud import WatsonException 21 | 22 | import json 23 | 24 | import logging 25 | logger = logging.getLogger(__name__) 26 | 27 | class Form_language(forms.Form): 28 | txtdata = forms.CharField(required=True, 29 | label="Text to Process", 30 | widget=forms.Textarea) 31 | 32 | def index(request): 33 | allinfo = {} 34 | outputTxt = "TBD" 35 | targetlang = 'en' 36 | form = None 37 | if request.POST: 38 | form = Form_language(request.POST) 39 | if form.is_valid(): 40 | data = form.cleaned_data['txtdata'] 41 | logger.info("Text to be process is %s" % data) 42 | lang = "TBD" 43 | 44 | try: 45 | lang = identifyLanguage(data) 46 | primarylang = lang["language"] 47 | confidence = lang["confidence"] 48 | 49 | outputTxt = "I am %s confident that the language is %s" % (confidence, primarylang) 50 | if targetlang != primarylang: 51 | supportedModels = checkForTranslation(primarylang, targetlang) 52 | if supportedModels: 53 | englishTxt = performTranslation(data, primarylang, targetlang) 54 | outputTxt += ", which in english is %s" % englishTxt 55 | else: 56 | outputTxt += ", which unfortunately we can't translate into English" 57 | 58 | except WatsonException as err: 59 | allinfo['error'] = err 60 | 61 | allinfo['lang'] = outputTxt 62 | else: 63 | allinfo['error'] = "The form is invalid" 64 | else: 65 | form = Form_language 66 | 67 | allinfo['form'] = form 68 | return render(request, 'watson/wlindex.html', allinfo) 69 | 70 | def getTranslationService(): 71 | return LanguageTranslationService(username='', 72 | password='') 73 | 74 | def identifyLanguage(data): 75 | txt = data.encode("utf-8", "replace") 76 | language_translation = getTranslationService() 77 | langsdetected = language_translation.identify(txt) 78 | 79 | logger.info(json.dumps(langsdetected, indent=2)) 80 | logger.info(langsdetected["languages"][0]['language']) 81 | logger.info(langsdetected["languages"][0]['confidence']) 82 | 83 | primarylang = langsdetected["languages"][0]['language'] 84 | confidence = langsdetected["languages"][0]['confidence'] 85 | 86 | retData = { "language" : primarylang, 87 | "confidence" : confidence } 88 | return retData 89 | 90 | 91 | def checkForTranslation(fromlang, tolang): 92 | supportedModels = [] 93 | lt = getTranslationService() 94 | models = lt.list_models() 95 | if models and ("models" in models): 96 | modelList = models["models"] 97 | for model in modelList: 98 | if fromlang == model['source'] and tolang == model['target']: 99 | supportedModels.append(model['model_id']) 100 | return supportedModels 101 | 102 | def performTranslation(txt, primarylang, targetlang): 103 | lt = getTranslationService() 104 | translation = lt.translate(txt, source=primarylang, target=targetlang) 105 | theTranslation = None 106 | if translation and ("translations" in translation): 107 | theTranslation = translation['translations'][0]['translation'] 108 | return theTranslation 109 | -------------------------------------------------------------------------------- /episode-5/django/src/projwatson/watsonlanguage/views/wl.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # -*- coding: utf-8 -*- 3 | # Copyright 2016 IBM Corp. All Rights Reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # https://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from django.shortcuts import render 18 | from django import forms 19 | from django.http import HttpResponse 20 | from django.views.decorators.csrf import csrf_exempt 21 | 22 | from watson_developer_cloud import WatsonException 23 | 24 | from watsonlanguage.watsonutils.languagetranslation import LanguageTranslationUtils 25 | from watsonlanguage.watsonutils.naturallanguageclassification import NaturalLanguageClassifierUtils 26 | 27 | import json 28 | 29 | import logging 30 | logger = logging.getLogger(__name__) 31 | 32 | class Form_language(forms.Form): 33 | txtdata = forms.CharField(required=True, 34 | label="Text to Process", 35 | widget=forms.Textarea) 36 | 37 | def index(request): 38 | allinfo = {} 39 | form = None 40 | if request.POST: 41 | form = Form_language(request.POST) 42 | if form.is_valid(): 43 | data = form.cleaned_data['txtdata'] 44 | logger.info("Text to be process is %s" % data) 45 | lang = "TBD" 46 | 47 | try: 48 | allinfo = invokeServices(data) 49 | except WatsonException as err: 50 | allinfo['error'] = err 51 | 52 | allinfo['lang'] = allinfo.get('outputText', 'Check for errors, no output produced') 53 | else: 54 | allinfo['error'] = "The form is invalid" 55 | else: 56 | form = Form_language 57 | 58 | allinfo['form'] = form 59 | return render(request, 'watson/wlindex.html', allinfo) 60 | 61 | 62 | @csrf_exempt 63 | def process(request): 64 | results = {} 65 | theData = {"error":"If you see this message then something has gone badly wrong"} 66 | 67 | validRequest = False 68 | logger.info("Checking request method") 69 | if request.method == "GET": 70 | logger.info("Request is a GET") 71 | data = "Hard coded string to test that API is returning something" 72 | validRequest = True 73 | 74 | if request.method == "POST": 75 | logger.info("Request is a POST") 76 | form = Form_language(request.POST) 77 | if form.is_valid(): 78 | data = form.cleaned_data['txtdata'] 79 | validRequest = True 80 | else: 81 | logger.info("The form is not valid") 82 | 83 | if validRequest: 84 | try: 85 | theData = invokeServices(data) 86 | except WatsonException as err: 87 | logger.warn('Watson Exception has been thrown') 88 | logger.warn(err) 89 | theData['error'] = 'Watson Exception has been thrown'; 90 | else: 91 | theData['error'] = "The form data is invalid"; 92 | 93 | results["results"] = theData 94 | return HttpResponse(json.dumps(results), content_type="application/json") 95 | 96 | 97 | def invokeServices(data): 98 | reply = {} 99 | targetlang = 'en' 100 | classification = {} 101 | 102 | ltu = LanguageTranslationUtils() 103 | nlcu = NaturalLanguageClassifierUtils() 104 | 105 | lang = ltu.identifyLanguage(data) 106 | primarylang = ltu.identifyLanguage(data)["language"] 107 | confidence = lang["confidence"] 108 | outputTxt = "I am %s confident that the language is %s" % (confidence, primarylang) 109 | 110 | if targetlang != primarylang: 111 | logger.info("Translation into %s is needed" % targetlang) 112 | supportedModels = ltu.checkForTranslation(primarylang, targetlang) 113 | if supportedModels: 114 | englishTxt = ltu.performTranslation(data, primarylang, targetlang) 115 | outputTxt += ", which in english is %s" % englishTxt 116 | 117 | classification = nlcu.classifyTheText(englishTxt) 118 | else: 119 | outputTxt += ", which unfortunately we can't translate into English" 120 | else: 121 | classification = nlcu.classifyTheText(data) 122 | if classification: 123 | outputTxt += "(and %s confident that it is %s classification)" \ 124 | % (classification['confidence'], 125 | classification['className']) 126 | 127 | reply['language'] = primarylang 128 | reply['classification'] = classification.get('className', 'no classifier found') 129 | reply['outputText'] = outputTxt 130 | 131 | return reply 132 | 133 | --------------------------------------------------------------------------------