├── .bumpversion.cfg ├── .env.enc ├── .github ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE.md ├── stale.yml └── workflows │ ├── build-test.yml │ └── deploy.yml ├── .gitignore ├── .gometalinter.json ├── .releaserc ├── .secrets.baseline ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── MIGRATION-V1.md ├── MIGRATION-V2.md ├── Makefile ├── README.md ├── appscan ├── ASOC.sh ├── Configfile ├── Makefile ├── app.json └── getJson.py ├── docker ├── Dockerfile └── README.md ├── package-lock.json ├── v2 ├── assistantv1 │ ├── assistant_v1.go │ ├── assistant_v1_examples_test.go │ ├── assistant_v1_integration_test.go │ ├── assistant_v1_suite_test.go │ └── assistant_v1_test.go ├── assistantv2 │ ├── assistant_v2.go │ ├── assistant_v2_examples_test.go │ ├── assistant_v2_integration_test.go │ ├── assistant_v2_suite_test.go │ └── assistant_v2_test.go ├── common │ ├── headers.go │ ├── headers_test.go │ └── version.go ├── comparecomplyv1 │ ├── compare_comply_v1.go │ ├── compare_comply_v1_examples_test.go │ ├── compare_comply_v1_integration_test.go │ ├── compare_comply_v1_suite_test.go │ └── compare_comply_v1_test.go ├── discoveryv1 │ ├── discovery_v1.go │ ├── discovery_v1_examples_test.go │ ├── discovery_v1_integration_test.go │ ├── discovery_v1_suite_test.go │ └── discovery_v1_test.go ├── discoveryv2 │ ├── discovery_v2.go │ ├── discovery_v2_examples_test.go │ ├── discovery_v2_integration_test.go │ ├── discovery_v2_suite_test.go │ └── discovery_v2_test.go ├── examples │ ├── assistantv1 │ │ └── assistant_v1.go │ ├── assistantv2 │ │ └── assistant_v2.go │ ├── discoveryv1 │ │ └── discovery_v1.go │ ├── discoveryv2 │ │ └── discovery_v2.go │ ├── languagetranslatorv3 │ │ └── language_translator_v3.go │ ├── naturallanguageclassifierv1 │ │ └── natural_language_classifier_v1.go │ ├── naturallanguageunderstandingv1 │ │ └── natural_language_understanding_v1.go │ ├── personalityinsightsv3 │ │ └── personality_insights_v3.go │ ├── speechtotextv1 │ │ └── speech_to_text_v1.go │ ├── texttospeechv1 │ │ └── text_to_speech_v1.go │ ├── toneanalyzerv3 │ │ └── tone_analyzer_v3.go │ ├── visualrecognitionv3 │ │ └── visual_recognition_v3.go │ └── visualrecognitionv4 │ │ └── visual_recognition_v4.go ├── go.mod ├── go.sum ├── languagetranslatorv3 │ ├── language_translator_v3.go │ ├── language_translator_v3_examples_test.go │ ├── language_translator_v3_integration_test.go │ ├── language_translator_v3_suite_test.go │ └── language_translator_v3_test.go ├── naturallanguageclassifierv1 │ ├── natural_language_classifier_v1.go │ ├── natural_language_classifier_v1_examples_test.go │ ├── natural_language_classifier_v1_integration_test.go │ ├── natural_language_classifier_v1_suite_test.go │ └── natural_language_classifier_v1_test.go ├── naturallanguageunderstandingv1 │ ├── natural_language_understanding_v1.go │ ├── natural_language_understanding_v1_examples_test.go │ ├── natural_language_understanding_v1_integration_test.go │ ├── natural_language_understanding_v1_suite_test.go │ └── natural_language_understanding_v1_test.go ├── personalityinsightsv3 │ ├── personality_insights_v3.go │ ├── personality_insights_v3_examples_test.go │ ├── personality_insights_v3_integration_test.go │ ├── personality_insights_v3_suite_test.go │ └── personality_insights_v3_test.go ├── resources │ ├── CarsvsTrucks.mlmodel │ ├── South_Africa_Luca_Galuzzi_2004.jpeg │ ├── TestEnrichments.csv │ ├── audio_example.mp3 │ ├── audio_raw_example.raw │ ├── car.jpg │ ├── cars.zip │ ├── confirm-grammar.xml │ ├── contract_A.pdf │ ├── contract_B.pdf │ ├── corpus-short-1.txt │ ├── corpus.tmx │ ├── dummy-storage-credentials.json │ ├── energy-policy.html │ ├── example.html │ ├── face.jpg │ ├── glossary.tmx │ ├── hello_world.txt │ ├── kitty.jpg │ ├── language_translator_model.tmx │ ├── my-giraffe.jpeg │ ├── nlu_categories_training.json │ ├── nlu_classifications_training.json │ ├── nlu_training_data.csv │ ├── output.wav │ ├── personality-v3.json │ ├── personality-v3.txt │ ├── sample-tables.pdf │ ├── sample-tables.png │ ├── simple.html │ ├── stopwords.txt │ ├── tone-example.html │ ├── trucks.zip │ ├── tts_audio.wav │ ├── weather_training_data.csv │ └── weather_training_metadata.json ├── speechtotextv1 │ ├── speech_to_text_v1.go │ ├── speech_to_text_v1_adapter.go │ ├── speech_to_text_v1_examples_test.go │ ├── speech_to_text_v1_integration_test.go │ ├── speech_to_text_v1_suite_test.go │ ├── speech_to_text_v1_test.go │ └── websocket_listener.go ├── texttospeechv1 │ ├── synthesize_listener.go │ ├── text_to_speech_v1.go │ ├── text_to_speech_v1_adapter.go │ ├── text_to_speech_v1_examples_test.go │ ├── text_to_speech_v1_integration_test.go │ ├── text_to_speech_v1_suite_test.go │ └── text_to_speech_v1_test.go ├── toneanalyzerv3 │ ├── tone_analyzer_v3.go │ ├── tone_analyzer_v3_examples_test.go │ ├── tone_analyzer_v3_integration_test.go │ ├── tone_analyzer_v3_suite_test.go │ └── tone_analyzer_v3_test.go ├── visualrecognitionv3 │ ├── visual_recognition_v3.go │ ├── visual_recognition_v3_examples_test.go │ ├── visual_recognition_v3_integration_test.go │ ├── visual_recognition_v3_suite_test.go │ └── visual_recognition_v3_test.go └── visualrecognitionv4 │ ├── visual_recognition_v4.go │ ├── visual_recognition_v4_examples_test.go │ ├── visual_recognition_v4_integration_test.go │ ├── visual_recognition_v4_suite_test.go │ └── visual_recognition_v4_test.go └── v3 ├── assistantv1 ├── assistant_v1.go ├── assistant_v1_examples_test.go ├── assistant_v1_integration_test.go ├── assistant_v1_suite_test.go └── assistant_v1_test.go ├── assistantv2 ├── assistant_v2.go ├── assistant_v2_examples_test.go ├── assistant_v2_integration_test.go ├── assistant_v2_suite_test.go └── assistant_v2_test.go ├── common ├── headers.go ├── headers_test.go └── version.go ├── discoveryv1 ├── discovery_v1.go ├── discovery_v1_examples_test.go ├── discovery_v1_suite_test.go └── discovery_v1_test.go ├── discoveryv2 ├── discovery_v2.go ├── discovery_v2_examples_test.go ├── discovery_v2_integration_test.go ├── discovery_v2_suite_test.go └── discovery_v2_test.go ├── go.mod ├── go.sum ├── languagetranslatorv3 ├── language_translator_v3.go ├── language_translator_v3_examples_test.go ├── language_translator_v3_integration_test.go ├── language_translator_v3_suite_test.go └── language_translator_v3_test.go ├── naturallanguageunderstandingv1 ├── natural_language_understanding_v1.go ├── natural_language_understanding_v1_examples_test.go ├── natural_language_understanding_v1_integration_test.go ├── natural_language_understanding_v1_suite_test.go └── natural_language_understanding_v1_test.go ├── resources ├── CarsvsTrucks.mlmodel ├── South_Africa_Luca_Galuzzi_2004.jpeg ├── TestEnrichments.csv ├── audio_example.mp3 ├── audio_raw_example.raw ├── car.jpg ├── cars.zip ├── confirm-grammar.xml ├── contract_A.pdf ├── contract_B.pdf ├── corpus-short-1.txt ├── corpus.tmx ├── dummy-storage-credentials.json ├── energy-policy.html ├── example.html ├── face.jpg ├── glossary.tmx ├── hello_world.txt ├── kitty.jpg ├── language_translator_model.tmx ├── my-giraffe.jpeg ├── nlu_categories_training.json ├── nlu_classifications_training.json ├── nlu_training_data.csv ├── output.wav ├── personality-v3.json ├── personality-v3.txt ├── sample-tables.pdf ├── sample-tables.png ├── simple.html ├── stopwords.txt ├── tone-example.html ├── trucks.zip ├── tts_audio.wav ├── weather_training_data.csv └── weather_training_metadata.json ├── speechtotextv1 ├── speech_to_text_v1.go ├── speech_to_text_v1_adapter.go ├── speech_to_text_v1_examples_test.go ├── speech_to_text_v1_integration_test.go ├── speech_to_text_v1_suite_test.go ├── speech_to_text_v1_test.go └── websocket_listener.go └── texttospeechv1 ├── synthesize_listener.go ├── text_to_speech_v1.go ├── text_to_speech_v1_adapter.go ├── text_to_speech_v1_examples_test.go ├── text_to_speech_v1_integration_test.go ├── text_to_speech_v1_suite_test.go └── text_to_speech_v1_test.go /.bumpversion.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 3.0.0 3 | commit = True 4 | message = [skip ci] docs: Update version numbers from {current_version} -> {new_version} 5 | 6 | [bumpversion:file:v2/common/version.go] 7 | search = Version = "{current_version}" 8 | replace = Version = "{new_version}" 9 | 10 | [bumpversion:file:README.md] 11 | search = v{current_version} 12 | replace = v{new_version} 13 | -------------------------------------------------------------------------------- /.env.enc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/.env.enc -------------------------------------------------------------------------------- /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at ehdsouza27@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Questions 2 | 3 | If you have issues with the APIs or have a question about the Watson services, see [Stack Overflow](https://stackoverflow.com/questions/tagged/ibm-watson+go). 4 | 5 | # Issues 6 | 7 | If you encounter an issue with the Go SDK, you are welcome to submit a [bug report](https://github.com/watson-developer-cloud/go-sdk/issues). 8 | Before that, please search for similar issues. It's possible somebody has encountered this issue already. 9 | 10 | # Pull Requests 11 | 12 | If you want to contribute to the repository, here's a quick guide: 13 | 1. Fork the repository 14 | 2. The GOPATH environment variable is used to specify directories outside of $GOROOT that contain the source for Go projects and their binaries. Example: 15 | ```sh 16 | export GOPATH="$HOME/workspace/go-workspace" 17 | export PATH=$PATH:$GOPATH/bin 18 | ```` 19 | 3. Have the following directory layout 20 | ```sh 21 | mkdir $GOPATH/{src,bin,pkg} 22 | ``` 23 | 4. Clone the respository into `src/github.com/watson-developer-cloud` directory 24 | 5. Use [dep][dep] dependency manager. 25 | On MacOS you can install or upgrade to the latest released version of [dep][dep] with Homebrew 26 | ```sh 27 | $ brew install dep 28 | $ dep ensure 29 | ``` 30 | 6. Check your code for lint issues 31 | ```sh 32 | golangci-lint run 33 | ``` 34 | 7. Develop and test your code changes `go test ./...` 35 | 8. Commit your changes: 36 | * Commits should follow the [Angular commit message guidelines](https://github.com/angular/angular/blob/master/CONTRIBUTING.md#-commit-message-guidelines). This is because our release tool uses this format for determining release versions and generating changelogs. To make this easier, we recommend using the [Commitizen CLI](https://github.com/commitizen/cz-cli) with the `cz-conventional-changelog` adapter. 37 | 9. Push to your fork and submit a pull request to the **master** branch 38 | 39 | # Developer's Certificate of Origin 1.1 40 | 41 | By making a contribution to this project, I certify that: 42 | 43 | (a) The contribution was created in whole or in part by me and I 44 | have the right to submit it under the open source license 45 | indicated in the file; or 46 | 47 | (b) The contribution is based upon previous work that, to the best 48 | of my knowledge, is covered under an appropriate open source 49 | license and I have the right under that license to submit that 50 | work with modifications, whether created in whole or in part 51 | by me, under the same open source license (unless I am 52 | permitted to submit under a different license), as indicated 53 | in the file; or 54 | 55 | (c) The contribution was provided directly to me by some other 56 | person who certified (a), (b) or (c) and I have not modified 57 | it. 58 | 59 | (d) I understand and agree that this project and the contribution 60 | are public and that a record of the contribution (including all 61 | personal information I submit with it, including my sign-off) is 62 | maintained indefinitely and may be redistributed consistent with 63 | this project or the open source license(s) involved. 64 | 65 | ## Additional Resources 66 | + [General GitHub documentation](https://help.github.com/) 67 | + [GitHub pull request documentation](https://help.github.com/send-pull-requests/) 68 | 69 | [dw]: https://developer.ibm.com/answers/questions/ask/?topics=watson 70 | [stackoverflow]: http://stackoverflow.com/questions/ask?tags=ibm-watson 71 | [dep]: https://github.com/golang/dep -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | Remember, an issue is not the place to ask questions. If you have issues with the APIs or have a question about the Watson services, see [Stack Overflow](https://stackoverflow.com/questions/tagged/ibm-watson+go). 11 | 12 | Before you open an issue, please check if a similar issue already exists or has been closed before. 13 | 14 | **Check service status** 15 | 16 | 1. For service issues or 5xx errors, first, go to the [IBM Cloud status page](https://cloud.ibm.com/status?component=compare-comply%2Cdiscovery%2Cconversation%2Cwatson-vision-combined%2Cnatural-language-understanding%2Cnatural-language-classifier%2Clanguage-translator%2Cpersonality-insights%2Cspeech-to-text%2Ctext-to-speech%2Ctone-analyzer&selected=status) and check the status of the service. 17 | 1. If the service status is OK, continue with a bug report. 18 | 19 | --- 20 | 21 | **Overview** 22 | _What is the issue? Be concise and clear._ 23 | 24 | **Expected behavior** 25 | _What did you expect to happen?_ 26 | 27 | **Actual behavior** 28 | _What actually happened?_ 29 | 30 | **How to reproduce** 31 | _Help us to reproduce what you experienced. Include your code snippets (without credentials)_ 32 | 33 | **Screenshots** 34 | _If applicable, add screenshots to help explain your problem._ 35 | 36 | **SDK Version** 37 | _Please provide the SDK version here._ 38 | 39 | **Additional information:** 40 | - OS: _for example, iOS_ 41 | - Which version of `Go` are you using? 42 | 43 | **Additional context** 44 | _Add any other details about the problem._ 45 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | Remember, an issue is not the place to ask questions. If you have issues with the APIs or have a question about the Watson services, see [Stack Overflow](https://stackoverflow.com/questions/tagged/ibm-watson+go). 11 | 12 | Before you open an issue, please check if a similar issue already exists or has been closed before. 13 | 14 | ### When you open an issue for a feature request, please add as much detail as possible: 15 | 16 | - [ ] A descriptive title starting with the service name 17 | - [ ] A description of the problem you're trying to solve 18 | - [ ] A suggested solution if possible 19 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Summary 2 | 3 | Provide a general description of the code changes in your pull 4 | request... were there any bugs you had fixed? If so, mention them. If 5 | these bugs have open GitHub issues, be sure to tag them here as well, 6 | to keep the conversation linked together. 7 | 8 | ### Other Information 9 | 10 | If there's anything else that's important and relevant to your pull 11 | request, mention that information here. 12 | 13 | 14 | Thanks for contributing to the Watson Developer Cloud! -------------------------------------------------------------------------------- /.github/stale.yml: -------------------------------------------------------------------------------- 1 | # Number of days of inactivity before an issue becomes stale 2 | daysUntilStale: 60 3 | # Number of days of inactivity before a stale issue is closed 4 | daysUntilClose: 7 5 | # Issues with these labels will never be considered stale 6 | exemptLabels: 7 | - pinned 8 | - security 9 | # Label to use when marking an issue as stale 10 | staleLabel: wontfix 11 | # Comment to post when marking an issue as stale. Set to `false` to disable 12 | markComment: > 13 | This issue has been automatically marked as stale because it has had no 14 | recent activity. It will be closed if no further activity occurs. Thank you 15 | for your contributions. 16 | # Comment to post when closing a stale issue. Set to `false` to disable 17 | closeComment: false 18 | -------------------------------------------------------------------------------- /.github/workflows/build-test.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support documentation. 4 | # This workflow will download a prebuilt Go version, install dependencies and run tests 5 | 6 | name: Build and Test 7 | 8 | on: 9 | push: 10 | branches: ["**"] 11 | pull_request: 12 | branches: [master] 13 | 14 | # Allows you to run this workflow manually from the Actions tab 15 | workflow_dispatch: 16 | 17 | jobs: 18 | build_test: 19 | name: Build and Test on G0 ${{ matrix.go-version }} and ${{ matrix.os }} 20 | runs-on: ${{ matrix.os }} 21 | strategy: 22 | matrix: 23 | go-version: ["1.14"] 24 | os: [ubuntu-latest] 25 | env: 26 | GO111MODULE: on 27 | 28 | steps: 29 | - uses: actions/checkout@v2 30 | - name: Set up Go 31 | uses: actions/setup-go@v2 32 | with: 33 | go-version: ${{ matrix.go-version }} 34 | - name: Execute GO tests 35 | run: | 36 | curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s -- -b $(go env GOPATH)/bin v1.21.0 37 | make all 38 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support documentation. 4 | # This workflow will download a prebuilt GO version, install dependencies, build and deploy/publish a new release 5 | 6 | name: Deploy and Publish 7 | 8 | on: 9 | workflow_run: 10 | workflows: ["Build and Test"] 11 | branches: [ master ] 12 | types: 13 | - completed 14 | 15 | # Allows you to run this workflow manually from the Action tab 16 | workflow_dispatch: 17 | 18 | jobs: 19 | deploy: 20 | if: "!contains(github.event.head_commit.message, 'skip ci')" 21 | name: Deploy and Publish 22 | runs-on: ubuntu-latest 23 | 24 | steps: 25 | - uses: actions/checkout@v2 26 | with: 27 | persist-credentials: false 28 | 29 | - name: Set up Go 30 | uses: actions/setup-go@v2 31 | with: 32 | go-version: 1.12 33 | 34 | - name: Setup Node.js 35 | uses: actions/setup-node@v1 36 | with: 37 | node-version: 14 38 | 39 | - name: Install Semantic Release dependencies 40 | run: | 41 | sudo apt-get install bumpversion 42 | npm install -g semantic-release 43 | npm install -g @semantic-release/changelog 44 | npm install -g @semantic-release/exec 45 | npm install -g @semantic-release/git 46 | npm install -g @semantic-release/github 47 | npm install -g @semantic-release/commit-analyzer 48 | 49 | - name: Publish to Git Releases and Tags 50 | if: ${{ github.event.workflow_run.conclusion == 'success' }} 51 | env: 52 | GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} 53 | NPM_TOKEN: ${{ secrets.NPM_TOKEN }} 54 | run: npx semantic-release # --dry-run 55 | 56 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | .ibm-project 3 | .DS_Store 4 | credentials.txt 5 | *.coverprofile 6 | node_modules/ 7 | .project 8 | *.env 9 | *.log 10 | 11 | # ignore vendor/ 12 | vendor/ 13 | 14 | # ignore detect secrets files 15 | .pre-commit-config.yaml 16 | .openapi-generator-ignore 17 | .openapi-generator/ 18 | 19 | # VSCode config 20 | .vscode/ 21 | *.code-workspace 22 | -------------------------------------------------------------------------------- /.gometalinter.json: -------------------------------------------------------------------------------- 1 | { 2 | "Enable": ["golint"], 3 | "Exclude": ["don't use MixedCaps in package name", "should not use dot imports"] 4 | } -------------------------------------------------------------------------------- /.releaserc: -------------------------------------------------------------------------------- 1 | { 2 | "branch": "master", 3 | "verifyConditions": ["@semantic-release/changelog", "@semantic-release/github"], 4 | "debug": true, 5 | "prepare": [ 6 | { 7 | "path": "@semantic-release/exec", 8 | "cmd": "bumpversion --allow-dirty --current-version ${lastRelease.version} --new-version ${nextRelease.version} patch" 9 | }, 10 | "@semantic-release/changelog", 11 | "@semantic-release/git" 12 | ], 13 | "publish": [ 14 | { 15 | "path": "@semantic-release/github" 16 | } 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | dist: xenial 4 | 5 | go: 6 | - 1.12.x 7 | 8 | notifications: 9 | email: false 10 | 11 | env: 12 | global: 13 | - GO111MODULE=on 14 | 15 | before_install: 16 | - '[ "${TRAVIS_PULL_REQUEST}" = "false" ] && openssl aes-256-cbc -K $encrypted_5831e1224655_key -iv $encrypted_5831e1224655_iv -in .env.enc -out .env -d || true' 17 | - nvm install 12 18 | - npm install -g npm@6.x 19 | - sudo apt-get update 20 | - sudo apt-get install python 21 | 22 | install: 23 | - if [ "${TRAVIS_TAG}" = "${TRAVIS_BRANCH}" ]; then cd appscan; make asoc-tool; cd ../; fi 24 | - curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s -- -b $(go env GOPATH)/bin v1.21.0 25 | 26 | before_script: 27 | - if [ "${TRAVIS_TAG}" = "${TRAVIS_BRANCH}" ]; then chmod a+x ./appscan/ASOC.sh; fi 28 | 29 | script: 30 | - make all 31 | - if [ "${TRAVIS_TAG}" = "${TRAVIS_BRANCH}" ]; then ./appscan/ASOC.sh; fi 32 | 33 | before_deploy: 34 | - pip install --user bumpversion 35 | - npm install @semantic-release/changelog 36 | - npm install @semantic-release/exec 37 | - npm install @semantic-release/git 38 | - npm install @semantic-release/github 39 | 40 | deploy: 41 | - provider: script 42 | skip_cleanup: true 43 | script: npx semantic-release --repository-url https://${GH_TOKEN}@github.com/watson-developer-cloud/go-sdk --debug 44 | -------------------------------------------------------------------------------- /MIGRATION-V2.md: -------------------------------------------------------------------------------- 1 | # Migrating to version 2.0.0 2 | 3 | In order to move from versions `1.x` to version `2.0.0`, there are some breaking changes that need to be accounted for. This guide will address overall changes happening to all service packages, and then call out important changes to individual packages. 4 | 5 | ## Overall Changes to all Packages 6 | 7 | ### Breaking import path 8 | 9 | In order to import the `v2` version of the Go module, the import path for the SDK must be updated to the following schema: 10 | 11 | ```go 12 | import "github.com/watson-developer-cloud/go-sdk/v2/{service}" 13 | ``` 14 | 15 | Where `{service}` represents the service you are attempting to import, i.e. `assistantv1`. 16 | 17 | ### Breaking `go-sdk-core` version change 18 | 19 | For all packages, we now import the `go-sdk-core/v5` module as a dependency. This replaces `go-sdk-core`. Any code that previously imported the Go Core should replace their existing imports with: 20 | 21 | ``` 22 | "github.com/IBM/go-sdk-core/v5/core" 23 | ``` 24 | 25 | ### Breaking Version Date Type Change 26 | 27 | For all packages, the `Version` property on the service struct is now a `*String`. It had previously been a `String` which was provided as a literal. The Go SDK Core has a convenience method to provide this string pointer: 28 | 29 | ```go 30 | service, err = assistantv1.NewAssistantV1(&assistantv1.AssistantV1Options{ 31 | Version: core.StringPtr("2020-04-01"), 32 | ServiceName: "assistant", 33 | }) 34 | ``` 35 | 36 | ### Breaking Changes to model setter functions 37 | 38 | In the `1.x` version of the SDK, setter methods were provided for almost all model structs for dealing with data from the service. Version `2.0.0` makes significant breaking changes in how setters are handled for these structs. 39 | 40 | Specifically, now the only structs that have setters for their properties are structs with the naming convention `{ServiceOperation}Options`. These are called `Options Models` and are typically the top level struct that is passed into a function. These structs have setter methods exposed that allow the individual properties within them to be set. 41 | 42 | For lower level models underneath these options models, they had setter methods for each individual property. As this bloated the code surface and provided little value compared to setting the property directly, we have decided in version `2.0.0` to remove these setters. 43 | 44 | If your code editor calls out that a setter method you are using has been removed, the appropriate way to update is to set the property directly. 45 | 46 | ### Providing custom `Context` to functions 47 | 48 | Version `2.0.0` of the Go SDK now includes an alternate version of each operation belonging to the service, named `WithContext`. This alternate function allows you to pass in a `context.Context` parameter while invoking the operation. The `context.Context` parameter can be used to specify a timeout, or cancel an in-flight request. Details about `context.Context` can be found [here](https://golang.org/pkg/context). 49 | 50 | ### Automatic Retries 51 | 52 | All service structs can be configured to retry HTTP methods in the event of an error. 53 | 54 | You can customize the retry logic to suit your purposes. The function `EnableRetries(maxRetries int, mayTretryInterval time.Duration)` allows you to configure the retry strategy that you would like to enable for the functions called by the service. 55 | 56 | You can also disable retries by using the `DisableRetries()` method exposed on the service struct. 57 | 58 | ## Service specific changes 59 | 60 | ### assistantv1 61 | 62 | - In the `Message()` function, the MessageInput{}'s `Text` property is now a `*string`. 63 | 64 | ### assistantv2 65 | 66 | - In the `Message()` function, the MessageInput{}'s `Text` property is now a `*string`. This can be constructed via the `core.StringPtr("{message}")` convenience method. 67 | - The `Message()` function's `MessageContext{}` struct has a property `Skills` that now accepts a `map[string]assistantv2.MessageContextSkill{}` type 68 | 69 | ### texttospeechv1 70 | 71 | - The `VoiceModel` naming convention has been replaced by `CustomModel` for all models and functions. For example, `CreateVoiceModel` in the `1.x` branch is now `CreateCustomModel` in version `2.0.0`. 72 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Makefile to build go-sdk library 2 | 3 | VDIR=v3 4 | 5 | all: build test lint tidy 6 | 7 | build: 8 | cd ${VDIR} && go build ./... 9 | 10 | test: unittest integrationtest 11 | 12 | unittest: 13 | cd ${VDIR} && go test `go list ./... | grep -v examples` 14 | 15 | integrationtest: 16 | cd ${VDIR} && go test `go list ./... | grep -v examples` -tags=integration 17 | 18 | lint: 19 | cd ${VDIR} && golangci-lint run --build-tags=integration 20 | 21 | tidy: 22 | cd ${VDIR} && go mod tidy 23 | -------------------------------------------------------------------------------- /appscan/ASOC.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cd appscan 4 | make generate-irx 5 | make upload-file 6 | make run-scan 7 | cd ../ 8 | -------------------------------------------------------------------------------- /appscan/Configfile: -------------------------------------------------------------------------------- 1 | # URLs to the CISO APIs 2 | LOGIN_URL ?= 'https://appscan.ibmcloud.com/api/V2/Account/ApiKeyLogin' 3 | UPLOAD_URL ?= 'https://appscan.ibmcloud.com/api/v2/FileUpload' 4 | GET_APP_URL ?= 'https://appscan.ibmcloud.com/api/V2/Apps?$$$$filter=Name%20eq%20' 5 | STATIC_SCAN_URL ?= 'https://appscan.ibmcloud.com/api/v2/Scans/StaticAnalyzer' 6 | CREATE_APP_URL ?= 'https://appscan.ibmcloud.com/api/V2/Apps' 7 | GET_ASSET_GROUP_URL ?= 'https://appscan.ibmcloud.com/api/V2/AssetGroups' 8 | 9 | APPSCAN_CLIENT_URL ?= https://appscan.ibmcloud.com/api/SCX/StaticAnalyzer/SAClientUtil?os= 10 | OS ?= linux 11 | APPSCAN_TOOL := $(APPSCAN_CLIENT_URL)$(OS) 12 | 13 | GIT_REPO ?= git@github.com:watson-developer-cloud/go-sdk.git 14 | 15 | PROJECT_NAME ?= go-sdk 16 | 17 | # Headers added to curl command 18 | CONTENT_HEADER_JSON := --header 'Content-Type: application/json' 19 | ACCEPT_HEADER_JSON := --header 'Accept: application/json' -------------------------------------------------------------------------------- /appscan/Makefile: -------------------------------------------------------------------------------- 1 | include Configfile 2 | 3 | # This will configure a 32-bit architecture on top of a 64-bit linux machine 4 | config-arch: 5 | sudo dpkg --add-architecture i386 6 | sudo apt-get update 7 | sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 8 | 9 | # Gets the ASoC Client Tool and configures it 10 | asoc-tool: config-arch 11 | $(eval DIR := $(shell pwd)) 12 | curl -o $(HOME)/client.zip $(APPSCAN_TOOL) 13 | mkdir $(HOME)/client ; mkdir $(HOME)/tool 14 | unzip -qq $(HOME)/client.zip -d $(HOME)/client 15 | cd $(HOME)/client ; ls | xargs -I {} sh -c "cp -r {}/* $(HOME)/tool" 16 | rm -rf client 17 | 18 | # Clone repo 19 | clone-repo: 20 | git clone $(GIT_REPO) 21 | 22 | # Generates the irx file for icp-cert-manager 23 | generate-irx: 24 | cd $(GOPATH)/src/github.com/ibm-watson/go-sdk 25 | $(HOME)/tool/bin/appscan.sh prepare -oso 26 | 27 | # Login to the AppScan API 28 | api-login: 29 | curl -o $(HOME)/token.json -X POST $(CONTENT_HEADER_JSON) $(ACCEPT_HEADER_JSON) -d '{"KeyId":"$(ASOC_APIKEY)", "KeySecret":"$(ASOC_SECRET)"}' $(LOGIN_URL) 30 | 31 | # Uploads the irx file to the AppScan API 32 | upload-file: api-login 33 | $(eval TOKE := $(shell python getJson.py $(HOME)/token.json "Token")) 34 | $(eval AUTH := --header 'Authorization: Bearer $(TOKE)') 35 | $(eval FILE := fileToUpload=@$(shell pwd)/$(notdir $(shell find $(pwd) -maxdepth 2 -name '*.irx' -print))) 36 | 37 | curl -o $(HOME)/file.json -X POST --header 'Content-Type: multipart/form-data' $(ACCEPT_HEADER_JSON) $(AUTH) -F $(FILE) $(UPLOAD_URL) 38 | 39 | # Checks to see if Cert-Manager-Application already exists. 40 | # TODO: Error with the url, will come back to this later. 41 | get-app: 42 | $(eval TOKE := $(shell python getJson.py $(HOME)/token.json "Token")) 43 | $(eval AUTH := --header 'Authorization: Bearer $(TOKE)') 44 | $(eval URL := $(GET_APP_URL)'$(APP_NAME)''') 45 | 46 | curl -X GET $(ACCEPT_HEADER_JSON) $(AUTH) $(URL) 47 | 48 | # Assume we have an existing application, then we'll simply run the static scan 49 | run-scan: 50 | $(eval TOKE := $(shell python getJson.py $(HOME)/token.json "Token")) 51 | $(eval AUTH := --header 'Authorization: Bearer $(TOKE)') 52 | $(eval FILE_ID := "$(shell python getJson.py $(HOME)/file.json "FileId")") 53 | $(eval APP_ID := "$(shell python getJson.py app.json "Id")") 54 | 55 | curl -X POST $(CONTENT_HEADER_JSON) $(ACCEPT_HEADER_JSON) $(AUTH) -d '{"ARSAFileId": $(FILE_ID), "ApplicationFileId": $(FILE_ID), "ScanName": "$(TRAVIS_TAG):$(TRAVIS_JOB_NUMBER):$(TRAVIS_COMMIT)", "EnableMailNotification": false, "Locale": "en-US", "AppId": $(APP_ID), "Execute": true, "Personal": false}' $(STATIC_SCAN_URL) 56 | 57 | get-asset-group: 58 | $(eval TOKE := $(shell python getJson.py $(HOME)/token.json "Token")) 59 | $(eval AUTH := --header 'Authorization: Bearer $(TOKE)') 60 | 61 | curl -o asset.json -X GET $(ACCEPT_HEADER_JSON) $(AUTH) $(GET_ASSET_GROUP_URL) 62 | 63 | # Create the application only if the application doesn't already exist. 64 | create-app: get-asset-group 65 | $(eval ASSET_GROUP_ID := "$(shell python getJson.py asset.json "Id")") 66 | $(eval TOKE := $(shell python getJson.py $(HOME)/token.json "Token")) 67 | $(eval AUTH := --header 'Authorization: Bearer $(TOKE)') 68 | 69 | curl -o app.json -X POST $(CONTENT_HEADER_JSON) $(ACCEPT_HEADER_JSON) $(AUTH) -d '{"Name": $(APP_NAME), "AssetGroupId": $(ASSET_GROUP_ID), "BusinessImpact": "Unspecified"}' $(CREATE_APP_URL) -------------------------------------------------------------------------------- /appscan/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "Id": "0bd486dd-eb35-4383-8472-e430c09e49dc", 3 | "AssetGroupName": "IBM Watson and Cloud Platform", 4 | "DateCreated": null, 5 | "LastUpdated": null, 6 | "LastComment": null, 7 | "RiskRating": "Unknown", 8 | "CreatedBy": null, 9 | "CriticalIssues": 0, 10 | "HighIssues": 0, 11 | "MediumIssues": 0, 12 | "LowIssues": 0, 13 | "IssuesInProgress": 0, 14 | "MaxSeverity": "Undetermined", 15 | "RR_MaxSeverity": 0, 16 | "NewIssues": 0, 17 | "OpenIssues": 0, 18 | "TotalIssues": 0, 19 | "OverallCompliance": null, 20 | "ComplianceStatuses": [], 21 | "CanBeDeleted": true, 22 | "LockedToSubscription": false, 23 | "Name": "Watson Go SDK", 24 | "AssetGroupId": null, 25 | "BusinessImpact": "Unspecified", 26 | "Url": null, 27 | "Description": null, 28 | "BusinessUnit": null, 29 | "Type": null, 30 | "Technology": null, 31 | "TestingStatus": "NotStarted", 32 | "Hosts": null, 33 | "CollateralDamagePotential": "NotDefined", 34 | "TargetDistribution": "NotDefined", 35 | "ConfidentialityRequirement": "NotDefined", 36 | "IntegrityRequirement": "NotDefined", 37 | "AvailabilityRequirement": "NotDefined", 38 | "Tester": null, 39 | "BusinessOwner": null, 40 | "DevelopmentContact": null, 41 | "PreferredOfferingType": "None" 42 | } 43 | -------------------------------------------------------------------------------- /appscan/getJson.py: -------------------------------------------------------------------------------- 1 | import json 2 | import sys 3 | 4 | def main(): 5 | data = load_data() 6 | printFields(data) 7 | 8 | def load_data(): 9 | data = "" 10 | filename = sys.argv[1] 11 | with open(filename, "r") as read: 12 | data = json.load(read) 13 | if isinstance(data, list): 14 | data = data[0] 15 | return data 16 | 17 | def printFields(data): 18 | fields = sys.argv[2:] 19 | for i in fields: 20 | print(data[i]) 21 | 22 | main() 23 | -------------------------------------------------------------------------------- /docker/Dockerfile: -------------------------------------------------------------------------------- 1 | #Import Golang base image(change version as needed) 2 | FROM golang:latest 3 | 4 | #Install go SDK 5 | RUN go get -u github.com/watson-developer-cloud/go-sdk/... 6 | -------------------------------------------------------------------------------- /docker/README.md: -------------------------------------------------------------------------------- 1 | ## Docker 2 | You can use docker to test issues you have with the SDK. 3 | 4 | 1. Install docker 5 | - Mac: 6 | - Windows: 7 | 8 | 2. Download the dockerfile for this SDK and edit as needed. 9 | - Change the go version as needed `FROM golang:` 10 | - For valid go base images on docker see 11 | 12 | - Copy code/file that you wish to test into the dockerfile 13 | - Add line `COPY ... ` 14 | 15 | - Set dockerfile to execute code file 16 | - Add line `CMD [ "" ]` 17 | 18 | - For more information on dockerfile construction please visit 19 | 20 | 3. Build and run the docker image. 21 | - Navigate to docker file directory 22 | - To build the docker image run `docker build --tag= .` 23 | - To run the docker image run `docker run ` 24 | -------------------------------------------------------------------------------- /v2/assistantv1/assistant_v1_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2018, 2021. 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 | package assistantv1_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestAssistantV1(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "AssistantV1 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v2/assistantv2/assistant_v2_integration_test.go: -------------------------------------------------------------------------------- 1 | //go:build integration 2 | // +build integration 3 | 4 | package assistantv2_test 5 | 6 | /** 7 | * (C) Copyright IBM Corp. 2018, 2022. 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | import ( 23 | "net/http" 24 | "os" 25 | "testing" 26 | 27 | "github.com/IBM/go-sdk-core/v5/core" 28 | "github.com/joho/godotenv" 29 | "github.com/stretchr/testify/assert" 30 | "github.com/watson-developer-cloud/go-sdk/v2/assistantv2" 31 | ) 32 | 33 | const skipMessage = "External configuration could not be loaded, skipping..." 34 | 35 | var configLoaded bool 36 | var configFile = "../../.env" 37 | 38 | var service *assistantv2.AssistantV2 39 | var assistantId string 40 | 41 | func shouldSkipTest(t *testing.T) { 42 | if !configLoaded { 43 | t.Skip(skipMessage) 44 | } 45 | } 46 | 47 | func TestLoadConfig(t *testing.T) { 48 | err := godotenv.Load(configFile) 49 | if err != nil { 50 | t.Skip(skipMessage) 51 | } 52 | 53 | assistantId = os.Getenv("ASSISTANT_ID") 54 | assert.NotEmpty(t, assistantId) 55 | if assistantId != "" { 56 | configLoaded = true 57 | } 58 | } 59 | 60 | func TestConstructService(t *testing.T) { 61 | shouldSkipTest(t) 62 | 63 | var err error 64 | 65 | service, err = assistantv2.NewAssistantV2(&assistantv2.AssistantV2Options{ 66 | Version: core.StringPtr("2020-04-01"), 67 | ServiceName: "assistant", 68 | }) 69 | assert.Nil(t, err) 70 | assert.NotNil(t, service) 71 | 72 | if err == nil { 73 | customHeaders := http.Header{} 74 | customHeaders.Add("X-Watson-Learning-Opt-Out", "1") 75 | customHeaders.Add("X-Watson-Test", "1") 76 | service.Service.SetDefaultHeaders(customHeaders) 77 | } 78 | } 79 | 80 | func TestSession(t *testing.T) { 81 | shouldSkipTest(t) 82 | 83 | // Create session 84 | createSession, _, responseErr := service.CreateSession( 85 | &assistantv2.CreateSessionOptions{ 86 | AssistantID: core.StringPtr(assistantId), 87 | }, 88 | ) 89 | assert.Nil(t, responseErr) 90 | assert.NotNil(t, createSession) 91 | 92 | // Message 93 | message, _, responseErr := service.Message( 94 | &assistantv2.MessageOptions{ 95 | AssistantID: core.StringPtr(assistantId), 96 | SessionID: createSession.SessionID, 97 | UserID: core.StringPtr("dummy"), 98 | Input: &assistantv2.MessageInput{ 99 | Text: core.StringPtr("Whats the weather like?"), 100 | }, 101 | Context: &assistantv2.MessageContext{ 102 | Skills: map[string]assistantv2.MessageContextSkill{ 103 | "main_skill": { 104 | UserDefined: map[string]interface{}{ 105 | "user_defined": map[string]string{ 106 | "account_number": "12345", 107 | }, 108 | }, 109 | }, 110 | }, 111 | }, 112 | }, 113 | ) 114 | assert.Nil(t, responseErr) 115 | assert.NotNil(t, message) 116 | 117 | // Delete session 118 | _, responseErr = service.DeleteSession( 119 | &assistantv2.DeleteSessionOptions{ 120 | AssistantID: core.StringPtr(assistantId), 121 | SessionID: createSession.SessionID, 122 | }, 123 | ) 124 | assert.Nil(t, responseErr) 125 | } 126 | 127 | func TestMessageStateless(t *testing.T) { 128 | shouldSkipTest(t) 129 | 130 | message, _, responseErr := service.MessageStateless( 131 | &assistantv2.MessageStatelessOptions{ 132 | AssistantID: core.StringPtr(assistantId), 133 | Input: &assistantv2.MessageInputStateless{ 134 | MessageType: core.StringPtr("text"), 135 | Text: core.StringPtr("Hello, this is test."), 136 | }, 137 | }, 138 | ) 139 | 140 | assert.Nil(t, responseErr) 141 | assert.NotNil(t, message) 142 | } 143 | 144 | func TestListLogs(t *testing.T) { 145 | t.Skip("endpoint only available on premium instance") 146 | 147 | options := service.NewListLogsOptions(assistantId) 148 | logs, _, responseErr := service.ListLogs(options) 149 | 150 | assert.Nil(t, responseErr) 151 | assert.NotNil(t, logs) 152 | } 153 | -------------------------------------------------------------------------------- /v2/assistantv2/assistant_v2_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2018, 2021. 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 | package assistantv2_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestAssistantV2(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "AssistantV2 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v2/common/headers.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | ) 7 | 8 | const ( 9 | HEADER_SDK_ANALYTICS = "X-IBMCloud-SDK-Analytics" 10 | HEADER_USER_AGENT = "User-Agent" 11 | 12 | SDK_NAME = "watson-apis-go-sdk" 13 | ) 14 | 15 | // GetSdkHeaders - returns the set of SDK-specific headers to be included in an outgoing request. 16 | func GetSdkHeaders(serviceName string, serviceVersion string, operationId string) map[string]string { 17 | sdkHeaders := make(map[string]string) 18 | 19 | sdkHeaders[HEADER_SDK_ANALYTICS] = fmt.Sprintf("service_name=%s;service_version=%s;operation_id=%s", 20 | serviceName, serviceVersion, operationId) 21 | 22 | sdkHeaders[HEADER_USER_AGENT] = GetUserAgentInfo() 23 | 24 | return sdkHeaders 25 | } 26 | 27 | var userAgent string = fmt.Sprintf("%s-%s %s", SDK_NAME, Version, GetSystemInfo()) 28 | 29 | func GetUserAgentInfo() string { 30 | return userAgent 31 | } 32 | 33 | var systemInfo = fmt.Sprintf("(arch=%s; os=%s; go.version=%s)", runtime.GOARCH, runtime.GOOS, runtime.Version()) 34 | 35 | func GetSystemInfo() string { 36 | return systemInfo 37 | } 38 | -------------------------------------------------------------------------------- /v2/common/headers_test.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "strings" 6 | "testing" 7 | ) 8 | 9 | func TestGetSystemInfo(t *testing.T) { 10 | var sysinfo = GetSystemInfo() 11 | assert.NotNil(t, sysinfo) 12 | assert.True(t, strings.Contains(sysinfo, "arch=")) 13 | assert.True(t, strings.Contains(sysinfo, "os=")) 14 | assert.True(t, strings.Contains(sysinfo, "go.version=")) 15 | } 16 | 17 | func TestGetSdkHeaders(t *testing.T) { 18 | var headers = GetSdkHeaders("myService", "v123", "myOperation") 19 | assert.NotNil(t, headers) 20 | 21 | var foundIt bool 22 | _, foundIt = headers[HEADER_SDK_ANALYTICS] 23 | assert.True(t, foundIt) 24 | 25 | _, foundIt = headers[HEADER_USER_AGENT] 26 | assert.True(t, foundIt) 27 | } 28 | -------------------------------------------------------------------------------- /v2/common/version.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | // Version of the SDK 4 | const Version = "3.0.0" 5 | -------------------------------------------------------------------------------- /v2/comparecomplyv1/compare_comply_v1_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2019, 2021. 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 | package comparecomplyv1_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestCompareComplyV1(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "CompareComplyV1 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v2/discoveryv1/discovery_v1_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2018, 2021. 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 | package discoveryv1_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestDiscoveryV1(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "DiscoveryV1 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v2/discoveryv2/discovery_v2_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2019, 2021. 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 | package discoveryv2_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestDiscoveryV2(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "DiscoveryV2 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v2/examples/assistantv1/assistant_v1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/IBM/go-sdk-core/v5/core" 7 | assistant "github.com/watson-developer-cloud/go-sdk/v2/assistantv1" 8 | ) 9 | 10 | func main() { 11 | // Instantiate the Watson Assistant service 12 | authenticator := &core.IamAuthenticator{ 13 | ApiKey: "my-iam-apikey", 14 | } 15 | service, serviceErr := assistant.NewAssistantV1(&assistant.AssistantV1Options{ 16 | URL: "YOUR SERVICE URL", 17 | Version: core.StringPtr("2018-07-10"), 18 | Authenticator: authenticator, 19 | }) 20 | 21 | // Check successful instantiation 22 | if serviceErr != nil { 23 | panic(serviceErr) 24 | } 25 | 26 | /* LIST WORKSPACES */ 27 | 28 | // Call the assistant ListWorkspaces method 29 | _, response, responseErr := service.ListWorkspaces(&assistant.ListWorkspacesOptions{}) 30 | 31 | if responseErr != nil { 32 | panic(responseErr) 33 | } 34 | 35 | fmt.Println(response) 36 | 37 | /* CREATE WORKSPACE */ 38 | 39 | metadata := make(map[string]interface{}) 40 | metadata["property"] = "value" 41 | 42 | createEntity := assistant.CreateEntity{ 43 | Entity: core.StringPtr("pizzatoppingstest"), 44 | Description: core.StringPtr("Tasty pizza topping"), 45 | Metadata: metadata, 46 | } 47 | createWorkspaceOptions := service.NewCreateWorkspaceOptions(). 48 | SetName("Test Workspace"). 49 | SetDescription("GO example workspace"). 50 | SetEntities([]assistant.CreateEntity{createEntity}) 51 | 52 | createWorkspaceResult, response, responseErr := service.CreateWorkspace(createWorkspaceOptions) 53 | 54 | // Check successful call 55 | if responseErr != nil { 56 | panic(responseErr) 57 | } 58 | 59 | fmt.Println(response) 60 | workspaceID := createWorkspaceResult.WorkspaceID 61 | 62 | // /* GET WORKSPACE */ 63 | 64 | // Call the assistant GetWorkspace method 65 | _, response, responseErr = service.GetWorkspace(service. 66 | NewGetWorkspaceOptions(*workspaceID). 67 | SetExport(true)) 68 | 69 | // Check successful call 70 | if responseErr != nil { 71 | panic(responseErr) 72 | } 73 | 74 | fmt.Println(response) 75 | 76 | // /* UPDATE WORKSPACE */ 77 | 78 | updateWorkspaceOptions := service.NewUpdateWorkspaceOptions(*workspaceID). 79 | SetName("Updated workspace name"). 80 | SetDescription("Updated description") 81 | 82 | _, response, responseErr = service.UpdateWorkspace(updateWorkspaceOptions) 83 | 84 | // Check successful call 85 | if responseErr != nil { 86 | panic(responseErr) 87 | } 88 | 89 | fmt.Println(response) 90 | 91 | // /* MESSAGE */ 92 | input := &assistant.MessageInput{ 93 | Text: core.StringPtr("Hello, how are you?"), 94 | } 95 | 96 | messageOptions := service.NewMessageOptions(*workspaceID). 97 | SetInput(input) 98 | 99 | // Call the Message method with no specified context 100 | messageResult, response, responseErr := service.Message(messageOptions) 101 | 102 | // Check successful call 103 | if responseErr != nil { 104 | panic(responseErr) 105 | } 106 | 107 | fmt.Println(response) 108 | 109 | // To continue with the same assistant, pass in the context from the previous call 110 | context := messageResult.Context 111 | 112 | input.Text = core.StringPtr("What's the weather right now?") 113 | messageOptions.SetContext(context). 114 | SetInput(input) 115 | 116 | _, response, responseErr = service.Message(messageOptions) 117 | 118 | // Check successful call 119 | if responseErr != nil { 120 | panic(responseErr) 121 | } 122 | 123 | fmt.Println(response) 124 | 125 | // /* DELETE WORKSPACE */ 126 | 127 | // Call the assistant DeleteWorkspace method 128 | response, responseErr = service.DeleteWorkspace(service.NewDeleteWorkspaceOptions(*workspaceID)) 129 | 130 | // Check successful call 131 | if responseErr != nil { 132 | panic(responseErr) 133 | } 134 | fmt.Println(response) 135 | } 136 | -------------------------------------------------------------------------------- /v2/examples/assistantv2/assistant_v2.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/IBM/go-sdk-core/v5/core" 7 | "github.com/watson-developer-cloud/go-sdk/v2/assistantv2" 8 | ) 9 | 10 | func main() { 11 | // Instantiate the Watson AssistantV2 service 12 | authenticator := &core.IamAuthenticator{ 13 | ApiKey: "my-iam-apikey", 14 | } 15 | service, serviceErr := assistantv2. 16 | NewAssistantV2(&assistantv2.AssistantV2Options{ 17 | URL: "YOUR SERVICE URL", 18 | Version: core.StringPtr("2017-04-21"), 19 | Authenticator: authenticator, 20 | }) 21 | 22 | // Check successful instantiation 23 | if serviceErr != nil { 24 | panic(serviceErr) 25 | } 26 | 27 | /* CREATE SESSION */ 28 | 29 | assistantID := "" 30 | // Call the assistant CreateSession method 31 | createSessionResult, _, responseErr := service. 32 | CreateSession(&assistantv2.CreateSessionOptions{ 33 | AssistantID: core.StringPtr(assistantID), 34 | }) 35 | 36 | if responseErr != nil { 37 | panic(responseErr) 38 | } 39 | sessionID := createSessionResult.SessionID 40 | 41 | // /* MESSAGE */ 42 | 43 | // Call the assistant Message method 44 | _, response, responseErr := service. 45 | Message(&assistantv2.MessageOptions{ 46 | AssistantID: core.StringPtr(assistantID), 47 | SessionID: sessionID, 48 | Input: &assistantv2.MessageInput{ 49 | Text: core.StringPtr("Whats the weather like?"), 50 | }, 51 | Context: &assistantv2.MessageContext{ 52 | Global: &assistantv2.MessageContextGlobal{ 53 | System: &assistantv2.MessageContextGlobalSystem{ 54 | UserID: core.StringPtr("dummy"), 55 | }, 56 | }, 57 | }, 58 | }) 59 | 60 | // Check successful call 61 | if responseErr != nil { 62 | panic(responseErr) 63 | } 64 | 65 | core.PrettyPrint(response.GetResult(), "Message") 66 | 67 | // /* DELETE SESSION */ 68 | 69 | // Call the assistant DeleteSession method 70 | _, responseErr = service. 71 | DeleteSession(&assistantv2.DeleteSessionOptions{ 72 | AssistantID: core.StringPtr(assistantID), 73 | SessionID: sessionID, 74 | }) 75 | 76 | // Check successful call 77 | if responseErr != nil { 78 | panic(responseErr) 79 | } 80 | fmt.Println("Session deleted successfully") 81 | } 82 | -------------------------------------------------------------------------------- /v2/examples/discoveryv1/discovery_v1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/IBM/go-sdk-core/v5/core" 8 | 9 | discovery "github.com/watson-developer-cloud/go-sdk/v2/discoveryv1" 10 | ) 11 | 12 | func main() { 13 | // Instantiate the Watson Discovery service 14 | authenticator := &core.IamAuthenticator{ 15 | ApiKey: os.Getenv("YOUR IAM API KEY"), 16 | } 17 | service, serviceErr := discovery.NewDiscoveryV1(&discovery.DiscoveryV1Options{ 18 | URL: "YOUR SERVICE URL", 19 | Version: core.StringPtr("2018-03-05"), 20 | Authenticator: authenticator, 21 | }) 22 | // Check successful instantiation 23 | if serviceErr != nil { 24 | fmt.Println(serviceErr) 25 | return 26 | } 27 | 28 | /* LIST ENVIRONMENTS */ 29 | 30 | // Create a new ListEnvironmentsOptions and set optional parameter Name 31 | listEnvironmentsOptions := service.NewListEnvironmentsOptions() 32 | 33 | // Call the discovery ListEnvironments method 34 | listEnvironmentResult, response, responseErr := service.ListEnvironments(listEnvironmentsOptions) 35 | 36 | // Check successful call 37 | if responseErr != nil { 38 | fmt.Println(responseErr) 39 | return 40 | } 41 | 42 | fmt.Println(response) 43 | 44 | // Check successful casting 45 | if listEnvironmentResult != nil { 46 | fmt.Println(listEnvironmentResult.Environments[0]) 47 | } 48 | 49 | /* ADD DOCUMENT */ 50 | 51 | environmentID := "" 52 | collectionID := "" 53 | 54 | pwd, _ := os.Getwd() 55 | file, fileErr := os.Open(pwd + "/../../resources/example.html") 56 | 57 | if fileErr != nil { 58 | panic(fileErr) 59 | } 60 | 61 | addDocumentOptions := service.NewAddDocumentOptions(environmentID, 62 | collectionID). 63 | SetFile(file). 64 | SetMetadata("{\"Creator\": \"Johnny Appleseed\", \"Subject\": \"Apples\" }") 65 | 66 | _, response, responseErr = service.AddDocument(addDocumentOptions) 67 | 68 | if responseErr != nil { 69 | panic(responseErr) 70 | } 71 | 72 | defer file.Close() 73 | 74 | core.PrettyPrint(response.GetResult(), "Add document: ") 75 | 76 | /* QUERY */ 77 | 78 | queryOptions := service.NewQueryOptions(environmentID, collectionID). 79 | SetFilter("extracted_metadata.sha1::9181d244*"). 80 | SetReturn("extracted_metadata.sha1") 81 | 82 | _, response, responseErr = service.Query(queryOptions) 83 | if responseErr != nil { 84 | panic(responseErr) 85 | } 86 | 87 | fmt.Println(response) 88 | } 89 | -------------------------------------------------------------------------------- /v2/examples/discoveryv2/discovery_v2.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/IBM/go-sdk-core/v5/core" 8 | 9 | discovery "github.com/watson-developer-cloud/go-sdk/v2/discoveryv2" 10 | ) 11 | 12 | func main() { 13 | // Discovery v2 is only available on Cloud Pak for Data. 14 | // Instantiate the Watson Discovery service 15 | authenticator := &core.CloudPakForDataAuthenticator{ 16 | URL: "", 17 | Username: "", 18 | Password: "", 19 | DisableSSLVerification: true, 20 | } 21 | service, serviceErr := discovery.NewDiscoveryV2(&discovery.DiscoveryV2Options{ 22 | URL: "", 23 | Version: core.StringPtr("2019-11-22"), 24 | Authenticator: authenticator, 25 | }) 26 | service.DisableSSLVerification() 27 | 28 | // Check successful instantiation 29 | if serviceErr != nil { 30 | fmt.Println(serviceErr) 31 | return 32 | } 33 | 34 | PROJECT_ID := "" 35 | 36 | // LIST COLLECTIONS 37 | listCollectionsResult, _, responseErr := service.ListCollections(&discovery.ListCollectionsOptions{ 38 | ProjectID: core.StringPtr(PROJECT_ID), 39 | }) 40 | 41 | if responseErr != nil { 42 | fmt.Println(responseErr) 43 | return 44 | } 45 | 46 | if listCollectionsResult != nil { 47 | core.PrettyPrint(listCollectionsResult, "Collections: ") 48 | } 49 | 50 | // COMPONENT SETTINGS 51 | settingsResult, _, responseErr := service.GetComponentSettings(&discovery.GetComponentSettingsOptions{ 52 | ProjectID: core.StringPtr(PROJECT_ID), 53 | }) 54 | 55 | if responseErr != nil { 56 | fmt.Println(responseErr) 57 | return 58 | } 59 | 60 | if settingsResult != nil { 61 | core.PrettyPrint(settingsResult, "Component Settings: ") 62 | } 63 | 64 | // ADD DOCUMENT 65 | COLLECTION_ID := "" 66 | pwd, _ := os.Getwd() 67 | file, fileErr := os.Open(pwd + "/../../resources/example.html") 68 | 69 | if fileErr != nil { 70 | panic(fileErr) 71 | } 72 | 73 | documentResult, response, responseErr := service.AddDocument(&discovery.AddDocumentOptions{ 74 | ProjectID: core.StringPtr(PROJECT_ID), 75 | CollectionID: core.StringPtr(COLLECTION_ID), 76 | File: file, 77 | Filename: core.StringPtr("example.html"), 78 | FileContentType: core.StringPtr("text/html"), 79 | }) 80 | 81 | if responseErr != nil { 82 | fmt.Println(responseErr) 83 | fmt.Println(response) 84 | return 85 | } 86 | 87 | if documentResult != nil { 88 | core.PrettyPrint(documentResult, "Document: ") 89 | } 90 | documentID := documentResult.DocumentID 91 | 92 | // CREATE TRAINING DATA 93 | trainingResult, _, responseErr := service.CreateTrainingQuery(&discovery.CreateTrainingQueryOptions{ 94 | ProjectID: core.StringPtr(PROJECT_ID), 95 | NaturalLanguageQuery: core.StringPtr("How is the weather today?"), 96 | Examples: []discovery.TrainingExample{ 97 | { 98 | DocumentID: documentID, 99 | CollectionID: core.StringPtr(COLLECTION_ID), 100 | Relevance: core.Int64Ptr(1), 101 | }, 102 | }, 103 | }) 104 | 105 | if responseErr != nil { 106 | fmt.Println(responseErr) 107 | return 108 | } 109 | 110 | if trainingResult != nil { 111 | core.PrettyPrint(trainingResult, "Training : ") 112 | } 113 | 114 | // TRAINING QUERIES 115 | trainingQueriesResult, _, responseErr := service.ListTrainingQueries(&discovery.ListTrainingQueriesOptions{ 116 | ProjectID: core.StringPtr(PROJECT_ID), 117 | }) 118 | 119 | if responseErr != nil { 120 | fmt.Println(responseErr) 121 | return 122 | } 123 | 124 | if trainingQueriesResult != nil { 125 | core.PrettyPrint(trainingQueriesResult, "Training queries: ") 126 | } 127 | 128 | // QUERIES // 129 | // query 130 | queryResult, _, responseErr := service.Query(&discovery.QueryOptions{ 131 | ProjectID: core.StringPtr(PROJECT_ID), 132 | CollectionIds: []string{COLLECTION_ID}, 133 | NaturalLanguageQuery: core.StringPtr("How is the weather today?"), 134 | }) 135 | 136 | if responseErr != nil { 137 | fmt.Println(responseErr) 138 | return 139 | } 140 | 141 | if queryResult != nil { 142 | core.PrettyPrint(queryResult, "Query: ") 143 | } 144 | 145 | // get autocomplete 146 | getAutocompletionResult, _, responseErr := service.GetAutocompletion(&discovery.GetAutocompletionOptions{ 147 | ProjectID: core.StringPtr(PROJECT_ID), 148 | Prefix: core.StringPtr("IBM"), 149 | }) 150 | 151 | if responseErr != nil { 152 | fmt.Println(responseErr) 153 | return 154 | } 155 | 156 | if getAutocompletionResult != nil { 157 | core.PrettyPrint(getAutocompletionResult, "Autocompletion: ") 158 | } 159 | 160 | // get notices 161 | noticesResult, _, responseErr := service.QueryNotices(&discovery.QueryNoticesOptions{ 162 | ProjectID: core.StringPtr(PROJECT_ID), 163 | NaturalLanguageQuery: core.StringPtr("warning"), 164 | }) 165 | 166 | if responseErr != nil { 167 | fmt.Println(responseErr) 168 | return 169 | } 170 | 171 | if noticesResult != nil { 172 | core.PrettyPrint(noticesResult, "Notices: ") 173 | } 174 | 175 | // list fields 176 | fieldsResult, _, responseErr := service.ListFields(&discovery.ListFieldsOptions{ 177 | ProjectID: core.StringPtr(PROJECT_ID), 178 | }) 179 | 180 | if responseErr != nil { 181 | fmt.Println(responseErr) 182 | return 183 | } 184 | 185 | if fieldsResult != nil { 186 | core.PrettyPrint(fieldsResult, "List fields: ") 187 | } 188 | 189 | // CLEANUP 190 | //delete training queries 191 | _, responseErr = service.DeleteTrainingQueries(&discovery.DeleteTrainingQueriesOptions{ 192 | ProjectID: core.StringPtr(PROJECT_ID), 193 | }) 194 | 195 | // delete document 196 | deleteDocumentResult, _, responseErr := service.DeleteDocument(&discovery.DeleteDocumentOptions{ 197 | ProjectID: core.StringPtr(PROJECT_ID), 198 | CollectionID: core.StringPtr(COLLECTION_ID), 199 | DocumentID: documentID, 200 | }) 201 | 202 | if responseErr != nil { 203 | fmt.Println(responseErr) 204 | return 205 | } 206 | 207 | if deleteDocumentResult != nil { 208 | core.PrettyPrint(deleteDocumentResult, "Document result: ") 209 | } 210 | } 211 | -------------------------------------------------------------------------------- /v2/examples/languagetranslatorv3/language_translator_v3.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/IBM/go-sdk-core/v5/core" 8 | languagetranslator "github.com/watson-developer-cloud/go-sdk/v2/languagetranslatorv3" 9 | ) 10 | 11 | func main() { 12 | // Instantiate the Watson Language Translator service 13 | authenticator := &core.IamAuthenticator{ 14 | ApiKey: os.Getenv("YOUR IAM API KEY"), 15 | } 16 | service, serviceErr := languagetranslator. 17 | NewLanguageTranslatorV3(&languagetranslator.LanguageTranslatorV3Options{ 18 | URL: "YOUR SERVICE URL", 19 | Version: core.StringPtr("2018-02-16"), 20 | Authenticator: authenticator, 21 | }) 22 | 23 | // Check successful instantiation 24 | if serviceErr != nil { 25 | fmt.Println(serviceErr) 26 | return 27 | } 28 | 29 | /* TRANSLATE */ 30 | 31 | textToTranslate := []string{ 32 | "Let's translate this message", 33 | "And this one", 34 | } 35 | 36 | translateOptions := service.NewTranslateOptions(textToTranslate). 37 | SetModelID("en-es") 38 | 39 | // Call the languageTranslator Translate method 40 | translateResult, response, responseErr := service.Translate(translateOptions) 41 | 42 | // Check successful call 43 | if responseErr != nil { 44 | panic(responseErr) 45 | } 46 | 47 | fmt.Println(response) 48 | 49 | // Check successful casting 50 | if translateResult != nil { 51 | fmt.Println("The word count is ", *translateResult.WordCount) 52 | } 53 | 54 | /* LIST IDENTIFIABLE LANGUAGES */ 55 | 56 | listIdentifiableLanguagesOptions := service.NewListIdentifiableLanguagesOptions() 57 | 58 | // Call the languageTranslator ListIdentifiableLanguages method 59 | listLanguageResult, response, responseErr := service.ListIdentifiableLanguages(listIdentifiableLanguagesOptions) 60 | 61 | // Check successful call 62 | if responseErr != nil { 63 | panic(responseErr) 64 | } 65 | 66 | // Check successful casting 67 | if listLanguageResult != nil { 68 | core.PrettyPrint(listLanguageResult, "Identifiable Languages") 69 | } 70 | 71 | /* IDENTIFY */ 72 | 73 | textToIdentify := "What language is this message in?" 74 | identifyOptions := service.NewIdentifyOptions(textToIdentify) 75 | 76 | // Call the languageTranslator Identify method 77 | identifyResult, response, responseErr := service.Identify(identifyOptions) 78 | 79 | // Check successful call 80 | if responseErr != nil { 81 | panic(responseErr) 82 | } 83 | 84 | // Check successful casting 85 | if identifyResult != nil { 86 | core.PrettyPrint(identifyResult, "Identify") 87 | } 88 | 89 | /* LIST MODELS */ 90 | 91 | listModelsOptions := service.NewListModelsOptions(). 92 | SetSource("es"). 93 | SetTarget("en"). 94 | SetDefault(true) 95 | 96 | // Call the languageTranslator ListModels method 97 | listModelResult, response, responseErr := service.ListModels(listModelsOptions) 98 | 99 | // Check successful call 100 | if responseErr != nil { 101 | panic(responseErr) 102 | } 103 | 104 | // Check successful casting 105 | if listModelResult != nil { 106 | core.PrettyPrint(listModelResult, "Models") 107 | } 108 | 109 | /* CREATE MODEL */ 110 | 111 | pwd, _ := os.Getwd() 112 | 113 | glossary, glossaryErr := os.Open(pwd + "/../../resources/glossary.tmx") 114 | fmt.Println(glossary) 115 | if glossaryErr != nil { 116 | fmt.Println(glossaryErr) 117 | } 118 | 119 | createModelOptions := service.NewCreateModelOptions("en-fr"). 120 | SetName("custom-en-fr"). 121 | SetForcedGlossary(glossary) 122 | 123 | // Call the languageTranslator CreateModel method 124 | createModelResult, response, responseErr := service.CreateModel(createModelOptions) 125 | 126 | // Check successful call 127 | if responseErr != nil { 128 | panic(responseErr) 129 | } 130 | 131 | // Check successful casting 132 | if createModelResult != nil { 133 | core.PrettyPrint(createModelResult, "Create Model") 134 | } 135 | 136 | /* GET MODEL */ 137 | 138 | // Call the languageTranslator GetModel method 139 | getModelOptions := service.NewGetModelOptions(*createModelResult.ModelID) 140 | getModelResult, response, getModelErr := service.GetModel(getModelOptions) 141 | 142 | // Check successful call 143 | if getModelErr != nil { 144 | panic(getModelErr) 145 | } 146 | 147 | // Check successful casting 148 | if getModelResult != nil { 149 | core.PrettyPrint(getModelResult, "Get Model") 150 | } 151 | 152 | /* DELETE MODEL */ 153 | 154 | // Call the languageTranslator DeleteModel method 155 | deleteModelOptions := service.NewDeleteModelOptions(*getModelResult.ModelID) 156 | deleteModelResult, response, responseErr := service.DeleteModel(deleteModelOptions) 157 | 158 | // Check successful call 159 | if responseErr != nil { 160 | panic(responseErr) 161 | } 162 | 163 | // Check successful casting 164 | if deleteModelResult != nil { 165 | core.PrettyPrint(deleteModelResult, "Delete Model") 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /v2/examples/naturallanguageclassifierv1/natural_language_classifier_v1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | 7 | "github.com/IBM/go-sdk-core/v5/core" 8 | nlc "github.com/watson-developer-cloud/go-sdk/v2/naturallanguageclassifierv1" 9 | ) 10 | 11 | func main() { 12 | // Instantiate the Watson Natural Language Classifier service 13 | authenticator := &core.IamAuthenticator{ 14 | ApiKey: os.Getenv("YOUR API KEY"), 15 | } 16 | service, serviceErr := nlc.NewNaturalLanguageClassifierV1(&nlc.NaturalLanguageClassifierV1Options{ 17 | URL: "YOUR SERVICE URL", 18 | Authenticator: authenticator, 19 | }) 20 | 21 | // Check successful instantiation 22 | if serviceErr != nil { 23 | panic(serviceErr) 24 | } 25 | 26 | /* CREATE CLASSIFIER */ 27 | 28 | pwd, _ := os.Getwd() 29 | 30 | metadata, metadataErr := os.Open(pwd + "/../../resources/weather_training_metadata.json") 31 | if metadataErr != nil { 32 | fmt.Println(metadataErr) 33 | } 34 | 35 | data, dataErr := os.Open(pwd + "/../../resources/weather_training_data.csv") 36 | if dataErr != nil { 37 | fmt.Println(dataErr) 38 | } 39 | 40 | createClassifierOptions := service.NewCreateClassifierOptions(metadata, data) 41 | 42 | // Call the natural language classifier CreateClassifier method 43 | createResult, _, responseErr := service.CreateClassifier(createClassifierOptions) 44 | 45 | // Check successful call 46 | if responseErr != nil { 47 | panic(responseErr) 48 | } 49 | 50 | // Check successful casting 51 | if createResult != nil { 52 | core.PrettyPrint(createResult, "Create Classifier") 53 | } 54 | 55 | /* CLASSIFY */ 56 | 57 | if *createResult.Status == "Available" { 58 | classifyOptions := service.NewClassifyOptions(*createResult.ClassifierID, "How hot will it be tomorrow?") 59 | 60 | // Call the natural language classifier Classify method 61 | classifyResult, _, responseErr := service.Classify(classifyOptions) 62 | 63 | // Check successful call 64 | if responseErr != nil { 65 | panic(responseErr) 66 | } 67 | 68 | // Check successful casting 69 | if classifyResult != nil { 70 | core.PrettyPrint(classifyResult, "Classify") 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /v2/examples/naturallanguageunderstandingv1/natural_language_understanding_v1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "os" 7 | 8 | "github.com/IBM/go-sdk-core/v5/core" 9 | nlu "github.com/watson-developer-cloud/go-sdk/v2/naturallanguageunderstandingv1" 10 | ) 11 | 12 | func main() { 13 | // Instantiate the Watson Natural Language Understanding service 14 | authenticator := &core.IamAuthenticator{ 15 | ApiKey: os.Getenv("YOUR IAM API KEY"), 16 | } 17 | service, serviceErr := nlu. 18 | NewNaturalLanguageUnderstandingV1(&nlu.NaturalLanguageUnderstandingV1Options{ 19 | URL: "YOUR SERVICE URL", 20 | Version: core.StringPtr("2017-02-27"), 21 | Authenticator: authenticator, 22 | }) 23 | 24 | // Check successful instantiation 25 | if serviceErr != nil { 26 | panic(serviceErr) 27 | } 28 | 29 | /* ANALYZE */ 30 | 31 | pwd, _ := os.Getwd() 32 | file, fileErr := ioutil.ReadFile(pwd + "/../../resources/energy-policy.html") 33 | 34 | // Check successful file read 35 | if fileErr != nil { 36 | panic(fileErr) 37 | } 38 | 39 | analyzeOptions := service.NewAnalyzeOptions(&nlu.Features{ 40 | Entities: &nlu.EntitiesOptions{}, 41 | Keywords: &nlu.KeywordsOptions{}, 42 | }). 43 | SetHTML(string(file)) 44 | 45 | // Call the naturalLanguageUnderstanding Analyze method 46 | analyzeResult, response, responseErr := service.Analyze(analyzeOptions) 47 | 48 | // Check successful call 49 | if responseErr != nil { 50 | panic(responseErr) 51 | } 52 | 53 | // Print the entire detailed response 54 | fmt.Println(response) 55 | 56 | // Check successful casting 57 | if analyzeResult != nil { 58 | core.PrettyPrint(analyzeResult, "Analyze") 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /v2/examples/personalityinsightsv3/personality_insights_v3.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "io/ioutil" 6 | "os" 7 | 8 | "github.com/IBM/go-sdk-core/v5/core" 9 | "github.com/watson-developer-cloud/go-sdk/v2/personalityinsightsv3" 10 | ) 11 | 12 | func main() { 13 | // Instantiate the Watson Personality Insights service 14 | authenticator := &core.IamAuthenticator{ 15 | ApiKey: os.Getenv("YOUR API KEY"), 16 | } 17 | service, serviceErr := personalityinsightsv3. 18 | NewPersonalityInsightsV3(&personalityinsightsv3.PersonalityInsightsV3Options{ 19 | URL: "YOUR SERVICE URL", 20 | Version: core.StringPtr("2017-10-13"), 21 | Authenticator: authenticator, 22 | }) 23 | 24 | // Check successful instantiation 25 | if serviceErr != nil { 26 | panic(serviceErr) 27 | } 28 | 29 | /* PROFILE */ 30 | 31 | // Read txt file with example speech 32 | pwd, _ := os.Getwd() 33 | fileName := "personality-v3.txt" 34 | file, fileErr := ioutil.ReadFile(pwd + "/../../resources/" + fileName) 35 | 36 | // Check successful file read 37 | if fileErr != nil { 38 | panic(fileErr) 39 | } 40 | 41 | // Create a new ProfileOptions for ContentType "text/plain" 42 | profileOptions := service. 43 | NewProfileOptions(). 44 | SetContentType("text/plain") 45 | profileOptions.SetBody(string(file)) 46 | profileOptions.ContentLanguage = core.StringPtr("en") 47 | profileOptions.AcceptLanguage = core.StringPtr("en") 48 | 49 | // Call the personality insights Profile method 50 | profResult, _, responseErr := service.Profile(profileOptions) 51 | 52 | // Check successful call 53 | if responseErr != nil { 54 | panic(responseErr) 55 | } 56 | 57 | // Check successful casting 58 | if profResult != nil { 59 | core.PrettyPrint(profResult, "Profile for "+fileName) 60 | } 61 | 62 | // Read JSON file with example tweets 63 | fileName = "personality-v3.json" 64 | file, fileErr = ioutil.ReadFile(pwd + "/../../resources/" + fileName) 65 | 66 | // Check successful file read 67 | if fileErr != nil { 68 | panic(fileErr) 69 | } 70 | 71 | // Unmarshal JSON into Content struct 72 | content := new(personalityinsightsv3.Content) 73 | json.Unmarshal(file, content) 74 | 75 | // Set Content of profileOptions 76 | profileOptions.Content = content 77 | 78 | // Call the personality insights Profile method now with JSON Content 79 | profResult, _, responseErr = service.Profile(profileOptions) 80 | 81 | // Check successful call 82 | if responseErr != nil { 83 | panic(responseErr) 84 | } 85 | 86 | // Check successful casting 87 | if profResult != nil { 88 | core.PrettyPrint(profResult, "Profile for "+fileName) 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /v2/examples/speechtotextv1/speech_to_text_v1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "os" 7 | 8 | "github.com/IBM/go-sdk-core/v5/core" 9 | "github.com/watson-developer-cloud/go-sdk/v2/speechtotextv1" 10 | ) 11 | 12 | func main() { 13 | // Instantiate the Watson Speech To Text service 14 | authenticator := &core.IamAuthenticator{ 15 | ApiKey: os.Getenv("YOUR API KEY"), 16 | } 17 | service, serviceErr := speechtotextv1. 18 | NewSpeechToTextV1(&speechtotextv1.SpeechToTextV1Options{ 19 | URL: "YOUR SERVICE URL", 20 | Authenticator: authenticator, 21 | }) 22 | 23 | // Check successful instantiation 24 | if serviceErr != nil { 25 | panic(serviceErr) 26 | } 27 | 28 | /* RECOGNIZE */ 29 | 30 | pwd, _ := os.Getwd() 31 | 32 | // Open file with mp3 to recognize 33 | audio, audioErr := os.Open(pwd + "/../../resources/audio_example.mp3") 34 | if audioErr != nil { 35 | panic(audioErr) 36 | } 37 | 38 | // Create a new RecognizeOptions for ContentType "audio/mp3" 39 | recognizeOptions := service. 40 | NewRecognizeOptions(audio). 41 | SetContentType("audio/mp3") 42 | 43 | // Call the speechToText Recognize method 44 | recognizeResult, _, responseErr := service.Recognize(recognizeOptions) 45 | 46 | // Check successful call 47 | if responseErr != nil { 48 | panic(responseErr) 49 | } 50 | 51 | // Check successful casting 52 | if recognizeResult != nil { 53 | core.PrettyPrint(recognizeResult, "Recognize") 54 | } 55 | 56 | // Example using websockets! 57 | audio, _ = os.Open(pwd + "/../../resources/audio_example.mp3") 58 | 59 | // callbook can have `OnOpen`, `onData`, `OnClose` and `onError` functions 60 | callback := myCallBack{} 61 | 62 | recognizeUsingWebsocketOptions := service. 63 | NewRecognizeUsingWebsocketOptions(audio, "audio/mp3") 64 | 65 | recognizeUsingWebsocketOptions. 66 | SetModel("en-US_BroadbandModel"). 67 | SetWordConfidence(true). 68 | SetSpeakerLabels(true). 69 | SetTimestamps(true) 70 | 71 | service.RecognizeUsingWebsocket(recognizeUsingWebsocketOptions, callback) 72 | } 73 | 74 | type myCallBack struct{} 75 | 76 | func (cb myCallBack) OnOpen() { 77 | fmt.Println("Handshake successful") 78 | } 79 | 80 | func (cb myCallBack) OnClose() { 81 | fmt.Println("Closing connection") 82 | } 83 | 84 | func (cb myCallBack) OnData(resp *core.DetailedResponse) { 85 | var speechResults speechtotextv1.SpeechRecognitionResults 86 | result := resp.GetResult().([]byte) 87 | json.Unmarshal(result, &speechResults) 88 | core.PrettyPrint(speechResults, "Recognized audio: ") 89 | } 90 | 91 | func (cb myCallBack) OnError(err error) { 92 | panic(err) 93 | } 94 | -------------------------------------------------------------------------------- /v2/examples/texttospeechv1/text_to_speech_v1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "io/ioutil" 7 | "os" 8 | 9 | "github.com/IBM/go-sdk-core/v5/core" 10 | "github.com/watson-developer-cloud/go-sdk/v2/texttospeechv1" 11 | ) 12 | 13 | func main() { 14 | // Instantiate the Watson Text To Speech service 15 | authenticator := &core.IamAuthenticator{ 16 | ApiKey: "YOUR SERVICE API KEY", 17 | } 18 | 19 | service, serviceErr := texttospeechv1. 20 | NewTextToSpeechV1(&texttospeechv1.TextToSpeechV1Options{ 21 | Authenticator: authenticator, 22 | }) 23 | 24 | // Check successful instantiation 25 | if serviceErr != nil { 26 | panic(serviceErr) 27 | } 28 | 29 | /* SYNTHESIZE */ 30 | 31 | synthesizeOptions := service.NewSynthesizeOptions("Hello World"). 32 | SetAccept("audio/mp3"). 33 | SetVoice("en-GB_KateVoice") 34 | 35 | // Call the textToSpeech Synthesize method 36 | synthesizeResult, _, responseErr := service.Synthesize(synthesizeOptions) 37 | 38 | // Check successful call 39 | if responseErr != nil { 40 | panic(responseErr) 41 | } 42 | 43 | // Check successful casting 44 | if synthesizeResult != nil { 45 | buff := new(bytes.Buffer) 46 | buff.ReadFrom(synthesizeResult) 47 | 48 | fileName := "synthesize_example_output.mp3" 49 | file, _ := os.Create(fileName) 50 | file.Write(buff.Bytes()) 51 | file.Close() 52 | 53 | fmt.Println("Wrote synthesized text to " + fileName) 54 | } 55 | synthesizeResult.Close() 56 | 57 | /* SYNTHESIZE USING WEBSOCKET*/ 58 | // create a file for websocket output 59 | fileName := "synthesize_ws_example_output.mp3" 60 | file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY, 0777) 61 | if err != nil { 62 | panic(err) 63 | } 64 | 65 | callback := myCallBack{f: file} 66 | 67 | synthesizeUsingWebsocketOptions := service. 68 | NewSynthesizeUsingWebsocketOptions("This is a simple example.", callback) 69 | 70 | synthesizeUsingWebsocketOptions. 71 | SetAccept("audio/mp3"). 72 | SetVoice("en-US_AllisonVoice") 73 | synthesizeUsingWebsocketOptions.SetTimings([]string{"words"}) 74 | err = service.SynthesizeUsingWebsocket(synthesizeUsingWebsocketOptions) 75 | if err != nil { 76 | fmt.Println(err) 77 | } 78 | } 79 | 80 | type myCallBack struct { 81 | f *os.File 82 | } 83 | 84 | func (cb myCallBack) OnOpen() { 85 | fmt.Println("Handshake successful") 86 | } 87 | 88 | func (cb myCallBack) OnClose() { 89 | fmt.Println("Closing connection") 90 | cb.f.Close() 91 | } 92 | 93 | func (cb myCallBack) OnAudioStream(b []byte) { 94 | bytes, err := ioutil.ReadAll(bytes.NewReader(b)) 95 | if err != nil { 96 | panic(err) 97 | } 98 | _, err = cb.f.Write(bytes) 99 | if err != nil { 100 | panic(err) 101 | } 102 | } 103 | 104 | func (cb myCallBack) OnData(response *core.DetailedResponse) {} 105 | 106 | func (cb myCallBack) OnError(err error) { 107 | fmt.Println("Received error") 108 | panic(err) 109 | } 110 | 111 | func (cb myCallBack) OnTimingInformation(timings texttospeechv1.Timings) { 112 | core.PrettyPrint(timings, "Timing information: ") 113 | } 114 | 115 | func (cb myCallBack) OnMarks(marks texttospeechv1.Marks) { 116 | core.PrettyPrint(marks, "Mark timings: ") 117 | } 118 | 119 | func (cb myCallBack) OnContentType(contentType string) { 120 | fmt.Println("The content type identified is:", contentType) 121 | } 122 | -------------------------------------------------------------------------------- /v2/examples/toneanalyzerv3/tone_analyzer_v3.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | 7 | "github.com/IBM/go-sdk-core/v5/core" 8 | "github.com/watson-developer-cloud/go-sdk/v2/toneanalyzerv3" 9 | ) 10 | 11 | func main() { 12 | // Instantiate the Watson Tone Analyzer service 13 | authenticator := &core.IamAuthenticator{ 14 | ApiKey: os.Getenv("YOUR API KEY"), 15 | } 16 | service, serviceErr := toneanalyzerv3. 17 | NewToneAnalyzerV3(&toneanalyzerv3.ToneAnalyzerV3Options{ 18 | URL: "YOUR SERVICE URL", 19 | Version: core.StringPtr("2017-09-21"), 20 | Authenticator: authenticator, 21 | }) 22 | 23 | // Check successful instantiation 24 | if serviceErr != nil { 25 | panic(serviceErr) 26 | } 27 | 28 | /* TONE CHAT */ 29 | 30 | utterances := []toneanalyzerv3.Utterance{ 31 | { 32 | Text: core.StringPtr("Hello World"), 33 | User: core.StringPtr("Watson"), 34 | }, 35 | { 36 | Text: core.StringPtr("World Hello"), 37 | User: core.StringPtr("John Doe"), 38 | }, 39 | } 40 | 41 | toneChatOptions := service.NewToneChatOptions(utterances). 42 | SetAcceptLanguage("en"). 43 | SetContentLanguage("en") 44 | 45 | // Call the toneAnalyzer ToneChat method 46 | toneChatResult, _, responseErr := service.ToneChat(toneChatOptions) 47 | 48 | // Check successful call 49 | if responseErr != nil { 50 | panic(responseErr) 51 | } 52 | 53 | // Check successful casting 54 | if toneChatResult != nil { 55 | core.PrettyPrint(toneChatResult, "Tone Chat") 56 | } 57 | 58 | /* TONE */ 59 | 60 | // Call the toneAnalyzer Tone method 61 | toneOptions := service.NewToneOptions(). 62 | SetBody("I am very happy. It is a good day"). 63 | SetContentType("text/plain") 64 | toneResult, _, responseErr := service.Tone(toneOptions) 65 | 66 | if responseErr != nil { 67 | panic(responseErr) 68 | } 69 | 70 | if toneResult != nil { 71 | core.PrettyPrint(toneResult, "Tone using plain text") 72 | } 73 | 74 | // Call the toneAnalyzer Tone method 75 | toneInput := &toneanalyzerv3.ToneInput{ 76 | Text: core.StringPtr("Team, I know that times are tough! Product sales have been disappointing for the past three quarters. We have a competitive product, but we need to do a better job of selling it!"), 77 | } 78 | toneOptions = service. 79 | NewToneOptions(). 80 | SetToneInput(toneInput). 81 | SetContentType("application/json") 82 | toneResult, _, responseErr = service.Tone(toneOptions) 83 | 84 | if responseErr != nil { 85 | panic(responseErr) 86 | } 87 | 88 | if toneResult != nil { 89 | core.PrettyPrint(toneResult, "Tone using toneInput") 90 | } 91 | 92 | // Call the toneAnalyzer Tone method 93 | pwd, _ := os.Getwd() 94 | htmlByte, htmlByteErr := ioutil.ReadFile(pwd + "/../../resources/tone-example.html") 95 | if htmlByteErr != nil { 96 | panic(htmlByteErr) 97 | } 98 | toneOptions = service.NewToneOptions(). 99 | SetBody(string(htmlByte)). 100 | SetContentType("text/html") 101 | toneResult, _, responseErr = service.Tone(toneOptions) 102 | 103 | if responseErr != nil { 104 | panic(responseErr) 105 | } 106 | 107 | if toneResult != nil { 108 | core.PrettyPrint(toneResult, "Tone using toneInput") 109 | } 110 | 111 | } 112 | -------------------------------------------------------------------------------- /v2/examples/visualrecognitionv3/visual_recognition_v3.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/IBM/go-sdk-core/v5/core" 7 | "github.com/watson-developer-cloud/go-sdk/v2/visualrecognitionv3" 8 | ) 9 | 10 | func main() { 11 | // Instantiate the Watson Visual Recognition service 12 | service, serviceErr := visualrecognitionv3. 13 | NewVisualRecognitionV3(&visualrecognitionv3.VisualRecognitionV3Options{ 14 | URL: "YOUR SERVICE URL", 15 | Version: core.StringPtr("2018-03-19"), 16 | Authenticator: &core.IamAuthenticator{ 17 | ApiKey: "YOUR API KEY", 18 | }, 19 | }) 20 | 21 | // Check successful instantiation 22 | if serviceErr != nil { 23 | panic(serviceErr) 24 | } 25 | 26 | /* CLASSIFY */ 27 | 28 | // Open file with image to classify 29 | pwd, _ := os.Getwd() 30 | imageFile, imageFileErr := os.Open(pwd + "/../../resources/kitty.jpg") 31 | 32 | // Check successful file read 33 | if imageFileErr != nil { 34 | panic(imageFileErr) 35 | } 36 | 37 | classifyOptions := service.NewClassifyOptions() 38 | classifyOptions.ImagesFile = imageFile 39 | classifyOptions.URL = core.StringPtr("https://www.readersdigest.ca/wp-content/uploads/sites/14/2011/01/4-ways-cheer-up-depressed-cat.jpg") 40 | classifyOptions.Threshold = core.Float32Ptr(0.6) 41 | classifyOptions.ClassifierIds = []string{"default", "food", "explicit"} 42 | 43 | // Call the visual recognition Classify method 44 | classifyResult, _, responseErr := service.Classify(classifyOptions) 45 | 46 | // Check successful call 47 | if responseErr != nil { 48 | panic(responseErr) 49 | } 50 | 51 | // Check successful casting 52 | if classifyResult != nil { 53 | core.PrettyPrint(classifyResult, "Classify") 54 | } 55 | 56 | /* CREATE CLASSIFIER */ 57 | 58 | carsFile, carsFileErr := os.Open(pwd + "/../../resources/cars.zip") 59 | if carsFileErr != nil { 60 | panic(carsFileErr) 61 | } 62 | 63 | trucksFile, trucksFileErr := os.Open(pwd + "/../../resources/trucks.zip") 64 | if trucksFileErr != nil { 65 | panic(trucksFileErr) 66 | } 67 | 68 | createClassifierOptions := service. 69 | NewCreateClassifierOptions("Cars vs Trucks"). 70 | AddPositiveExamples("cars", carsFile) 71 | createClassifierOptions.NegativeExamples = trucksFile 72 | 73 | createResult, _, responseErr := service.CreateClassifier(createClassifierOptions) 74 | if responseErr != nil { 75 | panic(responseErr) 76 | } 77 | 78 | if createResult != nil { 79 | core.PrettyPrint(createResult, "Create Classifier") 80 | } 81 | 82 | // Test classifier 83 | imageFile, imageFileErr = os.Open(pwd + "/../../resources/car.jpg") 84 | if imageFileErr != nil { 85 | panic(imageFileErr) 86 | } 87 | 88 | classifyOptions = service.NewClassifyOptions() 89 | classifyOptions.ImagesFile = imageFile 90 | 91 | classifyResult, _, responseErr = service.Classify(classifyOptions) 92 | if responseErr != nil { 93 | panic(responseErr) 94 | } 95 | 96 | if classifyResult != nil { 97 | core.PrettyPrint(classifyResult, "Classify") 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /v2/examples/visualrecognitionv4/visual_recognition_v4.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | 6 | "github.com/IBM/go-sdk-core/v5/core" 7 | "github.com/watson-developer-cloud/go-sdk/v2/visualrecognitionv4" 8 | ) 9 | 10 | func main() { 11 | // Instantiate the Watson Visual Recognition service 12 | service, serviceErr := visualrecognitionv4. 13 | NewVisualRecognitionV4(&visualrecognitionv4.VisualRecognitionV4Options{ 14 | Version: core.StringPtr("2019-02-11"), 15 | Authenticator: &core.IamAuthenticator{ 16 | ApiKey: "YOUR APIKEY", 17 | }, 18 | }) 19 | 20 | // Check successful instantiation 21 | if serviceErr != nil { 22 | panic(serviceErr) 23 | } 24 | service.SetServiceURL("https://api.us-south.visual-recognition.watson.cloud.ibm.com") 25 | 26 | /* CREATE COLLLECTION */ 27 | collection, _, responseErr := service.CreateCollection( 28 | &visualrecognitionv4.CreateCollectionOptions{ 29 | Name: core.StringPtr("my_go_collection_for_training"), 30 | Description: core.StringPtr("simple collection for go"), 31 | }, 32 | ) 33 | if responseErr != nil { 34 | panic(responseErr) 35 | } 36 | collectionId := collection.CollectionID 37 | core.PrettyPrint(collection, "Collection") 38 | 39 | /* ADD IMAGES */ 40 | pwd, _ := os.Getwd() 41 | giraffeFile, _ := os.Open(pwd + "/../../resources/South_Africa_Luca_Galuzzi_2004.jpeg") 42 | defer giraffeFile.Close() 43 | 44 | addImages, _, responseErr := service.AddImages( 45 | &visualrecognitionv4.AddImagesOptions{ 46 | CollectionID: collectionId, 47 | ImagesFile: []visualrecognitionv4.FileWithMetadata{ 48 | { 49 | Data: giraffeFile, 50 | Filename: core.StringPtr("hello giraffe"), 51 | }, 52 | }, 53 | }, 54 | ) 55 | core.PrettyPrint(addImages, "Add images result: ") 56 | 57 | /* ADD IMAGE TRAINING DATA */ 58 | trainingData, _, responseErr := service.AddImageTrainingData( 59 | &visualrecognitionv4.AddImageTrainingDataOptions{ 60 | CollectionID: collectionId, 61 | ImageID: addImages.Images[0].ImageID, 62 | Objects: []visualrecognitionv4.TrainingDataObject{ 63 | { 64 | Object: core.StringPtr("giraffe training data"), 65 | Location: &visualrecognitionv4.Location{ 66 | Top: core.Int64Ptr(64), 67 | Left: core.Int64Ptr(270), 68 | Width: core.Int64Ptr(755), 69 | Height: core.Int64Ptr(784), 70 | }, 71 | }, 72 | }, 73 | }, 74 | ) 75 | core.PrettyPrint(trainingData, "Training data: ") 76 | 77 | /* UPDATE OBJECT METADATA */ 78 | updateObjectMetadata, _, responseErr := service.UpdateObjectMetadata( 79 | &visualrecognitionv4.UpdateObjectMetadataOptions{ 80 | CollectionID: collectionId, 81 | Object: core.StringPtr("giraffe training data"), 82 | NewObject: core.StringPtr("updated giraffe training data"), 83 | }, 84 | ) 85 | core.PrettyPrint(updateObjectMetadata, "Updated object metadata: ") 86 | 87 | /* TRAIN */ 88 | train, _, responseErr := service.Train( 89 | &visualrecognitionv4.TrainOptions{ 90 | CollectionID: collectionId, 91 | }, 92 | ) 93 | core.PrettyPrint(train, "Training result: ") 94 | 95 | /* ANALYZE */ 96 | imageFile, _ := os.Open(pwd + "/../../resources/my-giraffe.jpeg") 97 | defer imageFile.Close() 98 | 99 | result, _, _ := service.Analyze( 100 | &visualrecognitionv4.AnalyzeOptions{ 101 | CollectionIds: []string{*collectionId}, 102 | Features: []string{visualrecognitionv4.AnalyzeOptionsFeaturesObjectsConst}, 103 | ImagesFile: []visualrecognitionv4.FileWithMetadata{ 104 | { 105 | Data: imageFile, 106 | Filename: core.StringPtr("random name"), 107 | }, 108 | }, 109 | }, 110 | ) 111 | core.PrettyPrint(result, "Analyze result: ") 112 | } 113 | -------------------------------------------------------------------------------- /v2/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/watson-developer-cloud/go-sdk/v2 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/IBM/go-sdk-core/v5 v5.5.0 7 | github.com/go-openapi/strfmt v0.20.1 8 | github.com/gorilla/websocket v1.4.2 9 | github.com/joho/godotenv v1.3.0 10 | github.com/onsi/ginkgo v1.14.2 11 | github.com/onsi/gomega v1.10.3 12 | github.com/stretchr/testify v1.6.1 13 | ) 14 | -------------------------------------------------------------------------------- /v2/languagetranslatorv3/language_translator_v3_integration_test.go: -------------------------------------------------------------------------------- 1 | //go:build integration 2 | // +build integration 3 | 4 | package languagetranslatorv3_test 5 | 6 | /** 7 | * (C) Copyright IBM Corp. 2018, 2022. 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | import ( 23 | "net/http" 24 | "os" 25 | "testing" 26 | 27 | "github.com/IBM/go-sdk-core/v5/core" 28 | "github.com/joho/godotenv" 29 | "github.com/stretchr/testify/assert" 30 | "github.com/watson-developer-cloud/go-sdk/v2/languagetranslatorv3" 31 | ) 32 | 33 | const skipMessage = "External configuration could not be loaded, skipping..." 34 | 35 | var configLoaded bool 36 | var configFile = "../../.env" 37 | 38 | var service *languagetranslatorv3.LanguageTranslatorV3 39 | 40 | func shouldSkipTest(t *testing.T) { 41 | if !configLoaded { 42 | t.Skip(skipMessage) 43 | } 44 | } 45 | 46 | func TestLoadConfig(t *testing.T) { 47 | err := godotenv.Load(configFile) 48 | if err != nil { 49 | t.Skip(skipMessage) 50 | } else { 51 | configLoaded = true 52 | } 53 | } 54 | 55 | func TestConstructService(t *testing.T) { 56 | shouldSkipTest(t) 57 | 58 | var err error 59 | 60 | service, err = languagetranslatorv3.NewLanguageTranslatorV3( 61 | &languagetranslatorv3.LanguageTranslatorV3Options{ 62 | Version: core.StringPtr("2020-04-01"), 63 | }) 64 | assert.Nil(t, err) 65 | assert.NotNil(t, service) 66 | 67 | if err == nil { 68 | customHeaders := http.Header{} 69 | customHeaders.Add("X-Watson-Learning-Opt-Out", "1") 70 | customHeaders.Add("X-Watson-Test", "1") 71 | service.Service.SetDefaultHeaders(customHeaders) 72 | } 73 | } 74 | 75 | func TestModels(t *testing.T) { 76 | shouldSkipTest(t) 77 | 78 | // List models 79 | listModels, response, responseErr := service.ListModels( 80 | &languagetranslatorv3.ListModelsOptions{}, 81 | ) 82 | assert.Nil(t, responseErr) 83 | assert.NotNil(t, response) 84 | assert.NotNil(t, listModels) 85 | 86 | // Create model 87 | glossary, glossaryErr := os.Open("../resources/glossary.tmx") 88 | assert.Nil(t, glossaryErr) 89 | 90 | createModel, _, responseErr := service.CreateModel( 91 | &languagetranslatorv3.CreateModelOptions{ 92 | BaseModelID: core.StringPtr("en-fr"), 93 | Name: core.StringPtr("custom-en-fr"), 94 | ForcedGlossary: glossary, 95 | }, 96 | ) 97 | assert.Nil(t, responseErr) 98 | assert.NotNil(t, createModel) 99 | 100 | // Get model 101 | getModel, _, responseErr := service.GetModel( 102 | &languagetranslatorv3.GetModelOptions{ 103 | ModelID: createModel.ModelID, 104 | }, 105 | ) 106 | assert.Nil(t, responseErr) 107 | assert.NotNil(t, getModel) 108 | 109 | // Delete model 110 | _, _, responseErr = service.DeleteModel( 111 | &languagetranslatorv3.DeleteModelOptions{ 112 | ModelID: createModel.ModelID, 113 | }, 114 | ) 115 | assert.Nil(t, responseErr) 116 | } 117 | 118 | func TestTranslate(t *testing.T) { 119 | shouldSkipTest(t) 120 | 121 | translate, _, responseErr := service.Translate( 122 | &languagetranslatorv3.TranslateOptions{ 123 | Text: []string{"Hello"}, 124 | ModelID: core.StringPtr("en-es"), 125 | }, 126 | ) 127 | assert.Nil(t, responseErr) 128 | assert.NotNil(t, translate) 129 | } 130 | 131 | func TestIdentifiableLanguage(t *testing.T) { 132 | shouldSkipTest(t) 133 | 134 | identifiableLanguage, _, responseErr := service.ListIdentifiableLanguages( 135 | &languagetranslatorv3.ListIdentifiableLanguagesOptions{}, 136 | ) 137 | assert.Nil(t, responseErr) 138 | assert.NotNil(t, identifiableLanguage) 139 | } 140 | 141 | func TestIdentify(t *testing.T) { 142 | shouldSkipTest(t) 143 | 144 | identify, _, responseErr := service.Identify( 145 | &languagetranslatorv3.IdentifyOptions{ 146 | Text: core.StringPtr("Language translator translates text from one language to another"), 147 | }, 148 | ) 149 | assert.Nil(t, responseErr) 150 | assert.NotNil(t, identify) 151 | } 152 | 153 | func TestDocumentTranslation(t *testing.T) { 154 | shouldSkipTest(t) 155 | 156 | // List documents 157 | listDocuments, _, responseErr := service.ListDocuments( 158 | &languagetranslatorv3.ListDocumentsOptions{}, 159 | ) 160 | assert.Nil(t, responseErr) 161 | assert.NotNil(t, listDocuments) 162 | 163 | // translate document 164 | pwd, _ := os.Getwd() 165 | document, documentErr := os.Open(pwd + "/../resources/hello_world.txt") 166 | assert.Nil(t, documentErr) 167 | 168 | translateDocument, _, responseErr := service.TranslateDocument( 169 | &languagetranslatorv3.TranslateDocumentOptions{ 170 | File: document, 171 | Filename: core.StringPtr("hello_world"), 172 | FileContentType: core.StringPtr("text/plain"), 173 | ModelID: core.StringPtr("en-es"), 174 | }, 175 | ) 176 | assert.Nil(t, responseErr) 177 | assert.NotNil(t, translateDocument) 178 | 179 | // Document status 180 | documentStatus, _, responseErr := service.GetDocumentStatus( 181 | &languagetranslatorv3.GetDocumentStatusOptions{ 182 | DocumentID: translateDocument.DocumentID, 183 | }, 184 | ) 185 | assert.Nil(t, responseErr) 186 | assert.NotNil(t, documentStatus) 187 | 188 | // Delete document 189 | _, responseErr = service.DeleteDocument( 190 | &languagetranslatorv3.DeleteDocumentOptions{ 191 | DocumentID: translateDocument.DocumentID, 192 | }, 193 | ) 194 | assert.Nil(t, responseErr) 195 | } 196 | 197 | func TestListLanguages(t *testing.T) { 198 | shouldSkipTest(t) 199 | 200 | listLanguages, _, listErr := service.ListLanguages( 201 | &languagetranslatorv3.ListLanguagesOptions{}, 202 | ) 203 | 204 | assert.NotNil(t, listLanguages) 205 | assert.Nil(t, listErr) 206 | } 207 | -------------------------------------------------------------------------------- /v2/languagetranslatorv3/language_translator_v3_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2018, 2021. 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 | package languagetranslatorv3_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestLanguageTranslatorV3(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "LanguageTranslatorV3 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v2/naturallanguageclassifierv1/natural_language_classifier_v1_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2018, 2021. 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 | package naturallanguageclassifierv1_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestNaturalLanguageClassifierV1(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "NaturalLanguageClassifierV1 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v2/naturallanguageunderstandingv1/natural_language_understanding_v1_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2018, 2021. 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 | package naturallanguageunderstandingv1_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestNaturalLanguageUnderstandingV1(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "NaturalLanguageUnderstandingV1 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v2/personalityinsightsv3/personality_insights_v3_examples_test.go: -------------------------------------------------------------------------------- 1 | //go:build examples 2 | // +build examples 3 | 4 | /** 5 | * (C) Copyright IBM Corp. 2021, 2022. 6 | * 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | package personalityinsightsv3_test 21 | 22 | import ( 23 | "encoding/json" 24 | "fmt" 25 | "os" 26 | 27 | "github.com/IBM/go-sdk-core/v5/core" 28 | . "github.com/onsi/ginkgo" 29 | . "github.com/onsi/gomega" 30 | "github.com/watson-developer-cloud/go-sdk/v2/personalityinsightsv3" 31 | ) 32 | 33 | // 34 | // This file provides an example of how to use the Personality Insights service. 35 | // 36 | // The following configuration properties are assumed to be defined: 37 | // PERSONALITY_INSIGHTS_URL= 38 | // PERSONALITY_INSIGHTS_AUTH_TYPE=iam 39 | // PERSONALITY_INSIGHTS_APIKEY= 40 | // PERSONALITY_INSIGHTS_AUTH_URL= 41 | // 42 | // These configuration properties can be exported as environment variables, or stored 43 | // in a configuration file and then: 44 | // export IBM_CREDENTIALS_FILE= 45 | // 46 | const externalConfigFile = "../personality_insights_v3.env" 47 | 48 | var ( 49 | personalityInsightsService *personalityinsightsv3.PersonalityInsightsV3 50 | config map[string]string 51 | configLoaded bool = false 52 | ) 53 | 54 | func shouldSkipTest() { 55 | if !configLoaded { 56 | Skip("External configuration is not available, skipping tests...") 57 | } 58 | } 59 | 60 | var _ = Describe(`PersonalityInsightsV3 Examples Tests`, func() { 61 | Describe(`External configuration`, func() { 62 | It("Successfully load the configuration", func() { 63 | var err error 64 | _, err = os.Stat(externalConfigFile) 65 | if err != nil { 66 | Skip("External configuration file not found, skipping tests: " + err.Error()) 67 | } 68 | 69 | os.Setenv("IBM_CREDENTIALS_FILE", externalConfigFile) 70 | config, err = core.GetServiceProperties(personalityinsightsv3.DefaultServiceName) 71 | if err != nil { 72 | Skip("Error loading service properties, skipping tests: " + err.Error()) 73 | } 74 | 75 | configLoaded = len(config) > 0 76 | }) 77 | }) 78 | 79 | Describe(`Client initialization`, func() { 80 | BeforeEach(func() { 81 | shouldSkipTest() 82 | }) 83 | It("Successfully construct the service client instance", func() { 84 | var err error 85 | 86 | // begin-common 87 | 88 | personalityInsightsServiceOptions := &personalityinsightsv3.PersonalityInsightsV3Options{ 89 | Version: core.StringPtr("testString"), 90 | } 91 | 92 | personalityInsightsService, err = personalityinsightsv3.NewPersonalityInsightsV3(personalityInsightsServiceOptions) 93 | 94 | if err != nil { 95 | panic(err) 96 | } 97 | 98 | // end-common 99 | 100 | Expect(personalityInsightsService).ToNot(BeNil()) 101 | }) 102 | }) 103 | 104 | Describe(`PersonalityInsightsV3 request examples`, func() { 105 | BeforeEach(func() { 106 | shouldSkipTest() 107 | }) 108 | It(`Profile request example`, func() { 109 | fmt.Println("\nProfile() result:") 110 | // begin-profile 111 | 112 | contentItemModel := &personalityinsightsv3.ContentItem{ 113 | Content: core.StringPtr("testString"), 114 | } 115 | 116 | contentModel := &personalityinsightsv3.Content{ 117 | ContentItems: []personalityinsightsv3.ContentItem{*contentItemModel}, 118 | } 119 | 120 | profileOptions := personalityInsightsService.NewProfileOptions() 121 | profileOptions.SetContent(contentModel) 122 | 123 | profile, response, err := personalityInsightsService.Profile(profileOptions) 124 | if err != nil { 125 | panic(err) 126 | } 127 | b, _ := json.MarshalIndent(profile, "", " ") 128 | fmt.Println(string(b)) 129 | 130 | // end-profile 131 | 132 | Expect(err).To(BeNil()) 133 | Expect(response.StatusCode).To(Equal(200)) 134 | Expect(profile).ToNot(BeNil()) 135 | 136 | }) 137 | It(`ProfileAsCSV request example`, func() { 138 | fmt.Println("\nProfileAsCSV() result:") 139 | // begin-profileAsCsv 140 | 141 | contentItemModel := &personalityinsightsv3.ContentItem{ 142 | Content: core.StringPtr("testString"), 143 | } 144 | 145 | contentModel := &personalityinsightsv3.Content{ 146 | ContentItems: []personalityinsightsv3.ContentItem{*contentItemModel}, 147 | } 148 | 149 | profileOptions := personalityInsightsService.NewProfileOptions() 150 | profileOptions.SetContent(contentModel) 151 | 152 | csvFile, response, err := personalityInsightsService.ProfileAsCSV(profileOptions) 153 | if err != nil { 154 | panic(err) 155 | } 156 | b, _ := json.MarshalIndent(csvFile, "", " ") 157 | fmt.Println(string(b)) 158 | 159 | // end-profileAsCsv 160 | 161 | Expect(err).To(BeNil()) 162 | Expect(response.StatusCode).To(Equal(200)) 163 | Expect(csvFile).ToNot(BeNil()) 164 | 165 | }) 166 | }) 167 | }) 168 | -------------------------------------------------------------------------------- /v2/personalityinsightsv3/personality_insights_v3_integration_test.go: -------------------------------------------------------------------------------- 1 | //go:build integration 2 | // +build integration 3 | 4 | package personalityinsightsv3_test 5 | 6 | /** 7 | * (C) Copyright IBM Corp. 2018, 2022. 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | import ( 23 | "encoding/json" 24 | "io/ioutil" 25 | "net/http" 26 | "os" 27 | "testing" 28 | 29 | "github.com/IBM/go-sdk-core/v5/core" 30 | "github.com/joho/godotenv" 31 | "github.com/stretchr/testify/assert" 32 | "github.com/watson-developer-cloud/go-sdk/v2/personalityinsightsv3" 33 | ) 34 | 35 | const skipMessage = "External configuration could not be loaded, skipping..." 36 | 37 | var configLoaded bool 38 | var configFile = "../../.env" 39 | var serviceURL *string 40 | 41 | var service *personalityinsightsv3.PersonalityInsightsV3 42 | 43 | func shouldSkipTest(t *testing.T) { 44 | if !configLoaded { 45 | t.Skip(skipMessage) 46 | } 47 | } 48 | 49 | func TestLoadConfig(t *testing.T) { 50 | err := godotenv.Load(configFile) 51 | if err != nil { 52 | t.Skip(skipMessage) 53 | } else { 54 | configLoaded = true 55 | } 56 | 57 | url := os.Getenv("PERSONALITY_INSIGHTS_URL") 58 | assert.NotEmpty(t, url) 59 | 60 | if url != "" { 61 | configLoaded = true 62 | serviceURL = &url 63 | } 64 | } 65 | 66 | func TestConstructService(t *testing.T) { 67 | shouldSkipTest(t) 68 | 69 | var err error 70 | 71 | service, err = personalityinsightsv3.NewPersonalityInsightsV3( 72 | &personalityinsightsv3.PersonalityInsightsV3Options{ 73 | Version: core.StringPtr("2017-10-13"), 74 | }) 75 | 76 | setServiceURLErr := service.SetServiceURL(*serviceURL) 77 | assert.Nil(t, setServiceURLErr) 78 | 79 | assert.Nil(t, err) 80 | assert.NotNil(t, service) 81 | 82 | if err == nil { 83 | customHeaders := http.Header{} 84 | customHeaders.Add("X-Watson-Learning-Opt-Out", "1") 85 | customHeaders.Add("X-Watson-Test", "1") 86 | service.Service.SetDefaultHeaders(customHeaders) 87 | } 88 | } 89 | 90 | func TestProfile(t *testing.T) { 91 | shouldSkipTest(t) 92 | 93 | file, err := ioutil.ReadFile("../resources/personality-v3.json") 94 | assert.Nil(t, err) 95 | 96 | // Unmarshal JSON into Content struct 97 | content := new(personalityinsightsv3.Content) 98 | err = json.Unmarshal(file, content) 99 | assert.Nil(t, err) 100 | 101 | profile, response, responseErr := service.Profile( 102 | &personalityinsightsv3.ProfileOptions{ 103 | Content: content, 104 | ContentType: core.StringPtr("application/json"), 105 | RawScores: core.BoolPtr(true), 106 | ConsumptionPreferences: core.BoolPtr(true), 107 | }, 108 | ) 109 | assert.Nil(t, responseErr) 110 | assert.NotNil(t, response) 111 | assert.NotNil(t, profile) 112 | } 113 | -------------------------------------------------------------------------------- /v2/personalityinsightsv3/personality_insights_v3_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2018, 2021. 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 | package personalityinsightsv3_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestPersonalityInsightsV3(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "PersonalityInsightsV3 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v2/resources/CarsvsTrucks.mlmodel: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v2/resources/CarsvsTrucks.mlmodel -------------------------------------------------------------------------------- /v2/resources/South_Africa_Luca_Galuzzi_2004.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v2/resources/South_Africa_Luca_Galuzzi_2004.jpeg -------------------------------------------------------------------------------- /v2/resources/TestEnrichments.csv: -------------------------------------------------------------------------------- 1 | engine,gasket,carburetor,piston,valves 2 | racing,stock,open,indy,drag 3 | flag,checkered,green,caution,yellow,red 4 | -------------------------------------------------------------------------------- /v2/resources/audio_example.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v2/resources/audio_example.mp3 -------------------------------------------------------------------------------- /v2/resources/audio_raw_example.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v2/resources/audio_raw_example.raw -------------------------------------------------------------------------------- /v2/resources/car.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v2/resources/car.jpg -------------------------------------------------------------------------------- /v2/resources/cars.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v2/resources/cars.zip -------------------------------------------------------------------------------- /v2/resources/confirm-grammar.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | affirmative 5 | nah 6 | no 7 | nope 8 | yeah 9 | yep 10 | yes 11 | yup 12 | fine 13 | negative 14 | OK 15 | sure 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /v2/resources/contract_A.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v2/resources/contract_A.pdf -------------------------------------------------------------------------------- /v2/resources/contract_B.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v2/resources/contract_B.pdf -------------------------------------------------------------------------------- /v2/resources/corpus-short-1.txt: -------------------------------------------------------------------------------- 1 | Am I at risk for health problems during travel 2 | Some people are more likely to have health problems when traveling outside the United States Visit your doctor before planning a trip to another country especially if you 3 | How Is Coronary Microvascular Disease Treated 4 | If youre diagnosed with coronary MVD and also have anemia you may benefit from treatment for that condition Anemia is thought to slow the growth of cells needed to repair damaged blood vessels 5 | What causes autoimmune hepatitis 6 | A combination of autoimmunity environmental triggers and a genetic predisposition can lead to autoimmune hepatitis 7 | What research is being done for Spinal Cord Injury 8 | The National Institute of Neurological Disorders and Stroke NINDS conducts spinal cord research in its laboratories at the National Institutes of Health NIH and also supports additional research through grants to major research institutions across the country Advances in research are giving doctors and patients hope that repairing injured spinal cords is a reachable goal Advances in basic research are also being matched by progress in clinical research especially in understanding the kinds of physical rehabilitation that work best to restore function Some of the more promising rehabilitation techniques are helping spinal cord injury patients become more mobile 9 | What is Osteogenesis imperfecta OI 10 | Osteogenesis imperfecta OI is a rare genetic disorder that like juvenile osteoporosis is characterized by bones that break easily often from little or no apparent cause 11 | -------------------------------------------------------------------------------- /v2/resources/corpus.tmx: -------------------------------------------------------------------------------- 1 | 2 | 3 |
11 | 12 | 13 | RESOLUTION 55/100 14 | RÉSOLUTION 55/100 15 | 16 | 17 | Adopted at the 81st plenary meeting, on 4 December 2000, on the recommendation of the Committee (A/55/602/Add.2 and Corr.1, para. 94),The draft resolution recommended in the report was sponsored in the Committee by: Bolivia, Cuba, El Salvador, Ghana and Honduras. by a recorded vote of 106 to 1, with 67 abstentions, as follows: 18 | Adoptée à la 81e séance plénière, le 4 décembre 2000, sur la recommandation de la Commission (A/55/602/Add.2, par. 94)Le projet de résolution recommandé dans le rapport de la Commission avait pour auteurs les pays suivants: Bolivie, Cuba, El Salvador, Ghana et Honduras., par 106 voix contre une, avec 67 abstentions, à la suite d'un vote enregistré, les voix s'étant réparties comme suit: 19 | 20 | 21 | -------------------------------------------------------------------------------- /v2/resources/dummy-storage-credentials.json: -------------------------------------------------------------------------------- 1 | { 2 | "apikey": "random-apikey", 3 | "cos_hmac_keys": { 4 | "access_key_id": "aaaa", 5 | "secret_access_key": "bbb" 6 | }, 7 | "endpoints": "https://cos-service.bluemix.net/endpoints", 8 | "iam_apikey_description": "Auto generated apikey during resource-key operation for Instance - crn:v1:bluemix:public:cloud-object-storage:global:a/070794137072b93b6eb44420201f6194:c290d41e-c445-420e-ad44-65b2a15a7c6c::", 9 | "iam_apikey_name": "auto-generated-apikey-5a3550b4-e3af-40b7-8bda-0fb839533c02", 10 | "iam_role_crn": "crn:v1:bluemix:public:iam::::serviceRole:Manager", 11 | "iam_serviceid_crn": "crn:v1:bluemix:public:iam-identity::a/070794137072b93b6eb44420201f6194::serviceid:ServiceId-3ff1a723-d223-41ff-99e4-32ff8d022549", 12 | "resource_instance_id": "crn:v1:bluemix:public:cloud-object-storage:global:a/xxx:yyy::" 13 | } -------------------------------------------------------------------------------- /v2/resources/face.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v2/resources/face.jpg -------------------------------------------------------------------------------- /v2/resources/glossary.tmx: -------------------------------------------------------------------------------- 1 | 2 | 3 |
6 | 7 | 8 | 9 | International Business Machines 10 | 11 | 12 | International Business Machines 13 | 14 | 15 | 16 | 17 | patent 18 | 19 | 20 | brevent 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /v2/resources/hello_world.txt: -------------------------------------------------------------------------------- 1 | hello world 2 | -------------------------------------------------------------------------------- /v2/resources/kitty.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v2/resources/kitty.jpg -------------------------------------------------------------------------------- /v2/resources/language_translator_model.tmx: -------------------------------------------------------------------------------- 1 | 2 | 3 |
6 | 7 | 8 | 9 | International Business Machines 10 | 11 | 12 | International Business Machines 13 | 14 | 15 | 16 | 17 | patent 18 | 19 | 20 | brevent 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /v2/resources/my-giraffe.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v2/resources/my-giraffe.jpeg -------------------------------------------------------------------------------- /v2/resources/nlu_categories_training.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "labels": [ 4 | "level1" 5 | ], 6 | "key_phrases": [ 7 | "key phrase", 8 | "key phrase 2" 9 | ] 10 | }, 11 | { 12 | "labels": [ 13 | "level1", 14 | "level2" 15 | ], 16 | "key_phrases": [ 17 | "key phrase 3", 18 | "key phrase 4" 19 | ] 20 | } 21 | ] 22 | 23 | -------------------------------------------------------------------------------- /v2/resources/nlu_classifications_training.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "text": "Example 1", 4 | "labels": ["label1"] 5 | }, 6 | { 7 | "text": "Example 2", 8 | "labels": ["label1", "label2"] 9 | }, 10 | { 11 | "text": "Example 3", 12 | "labels": ["label1"] 13 | }, 14 | { 15 | "text": "Example 4", 16 | "labels": ["label1", "label2"] 17 | }, 18 | { 19 | "text": "Example 5", 20 | "labels": ["label1"] 21 | }, 22 | { 23 | "text": "Example 6", 24 | "labels": ["label1", "label2"] 25 | }, 26 | { 27 | "text": "Example 7", 28 | "labels": ["label1"] 29 | }, 30 | { 31 | "text": "Example 8", 32 | "labels": ["label1", "label2"] 33 | }, 34 | { 35 | "text": "Example 9", 36 | "labels": ["label1"] 37 | }, 38 | { 39 | "text": "Example 10", 40 | "labels": ["label1", "label2"] 41 | } 42 | ] 43 | -------------------------------------------------------------------------------- /v2/resources/nlu_training_data.csv: -------------------------------------------------------------------------------- 1 | doc,label 2 | Today is a great day,positive 3 | Tomorrow will be a great day,positive 4 | I am really happy,positive 5 | This is amazing,positive 6 | Wow that’s really cool,positive 7 | That looks great on you,positive 8 | This outfit is really nice,positive 9 | I think you did a great job,positive 10 | Nice work!,positive 11 | This is ok,neutral 12 | Ehh I've seen this before,neutral 13 | No comment,neutral 14 | How are you?,neutral 15 | Hello,neutral 16 | I don’t have an opinion on that subject,neutral 17 | I enjoyed it more or less,neutral 18 | This product stinks!,negative 19 | I did not have a good time,negative 20 | Worst game ever!,negative -------------------------------------------------------------------------------- /v2/resources/output.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v2/resources/output.wav -------------------------------------------------------------------------------- /v2/resources/sample-tables.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v2/resources/sample-tables.pdf -------------------------------------------------------------------------------- /v2/resources/sample-tables.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v2/resources/sample-tables.png -------------------------------------------------------------------------------- /v2/resources/simple.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Simple HTML Page 4 | 5 | 6 |

Chapter 1

7 |

The content of the first chapter.

8 | 9 | -------------------------------------------------------------------------------- /v2/resources/tone-example.html: -------------------------------------------------------------------------------- 1 |

Team, I know that times are tough!

Product sales have been disappointing for the past three quarters.

We have a competitive product, but we need to do a better job of selling it!

2 | 3 | -------------------------------------------------------------------------------- /v2/resources/trucks.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v2/resources/trucks.zip -------------------------------------------------------------------------------- /v2/resources/tts_audio.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v2/resources/tts_audio.wav -------------------------------------------------------------------------------- /v2/resources/weather_training_data.csv: -------------------------------------------------------------------------------- 1 | How hot is it today?,temperature 2 | Is it hot outside?,temperature 3 | Will it be uncomfortably hot?,temperature 4 | Will it be sweltering?,temperature 5 | How cold is it today?,temperature 6 | Is it cold outside?,temperature 7 | Will it be uncomfortably cold?,temperature 8 | Will it be frigid?,temperature 9 | What is the expected high for today?,temperature 10 | What is the expected temperature?,temperature 11 | Will high temperatures be dangerous?,temperature 12 | Is it dangerously cold?,temperature 13 | When will the heat subside?,temperature 14 | Is it hot?,temperature 15 | Is it cold?,temperature 16 | How cold is it now?,temperature 17 | Will we have a cold day today?,temperature 18 | When will the cold subside?,temperature 19 | What highs are we expecting?,temperature 20 | What lows are we expecting?,temperature 21 | Is it warm?,temperature 22 | Is it chilly?,temperature 23 | What's the current temp in Celsius?,temperature 24 | What is the temperature in Fahrenheit?,temperature 25 | Is it windy?,conditions 26 | Will it rain today?,conditions 27 | What are the chances for rain?,conditions 28 | Will we get snow?,conditions 29 | Are we expecting sunny conditions?,conditions 30 | Is it overcast?,conditions 31 | Will it be cloudy?,conditions 32 | How much rain will fall today?,conditions 33 | How much snow are we expecting?,conditions 34 | Is it windy outside?,conditions 35 | How much snow do we expect?,conditions 36 | Is the forecast calling for snow today?,conditions 37 | Will we see some sun?,conditions 38 | When will the rain subside?,conditions 39 | Is it cloudy?,conditions 40 | Is it sunny now?,conditions 41 | Will it rain?,conditions 42 | Will we have much snow?,conditions 43 | Are the winds dangerous?,conditions 44 | What is the expected snowfall today?,conditions 45 | Will it be dry?,conditions 46 | Will it be breezy?,conditions 47 | Will it be humid?,conditions 48 | What is today's expected humidity?,conditions 49 | Will the blizzard hit us?,conditions 50 | Is it drizzling?,conditions -------------------------------------------------------------------------------- /v2/resources/weather_training_metadata.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "test_classifier", 3 | "language": "en" 4 | } 5 | -------------------------------------------------------------------------------- /v2/speechtotextv1/speech_to_text_v1_adapter.go: -------------------------------------------------------------------------------- 1 | package speechtotextv1 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | 7 | "github.com/IBM/go-sdk-core/v5/core" 8 | 9 | "net/http" 10 | "net/url" 11 | "strings" 12 | "time" 13 | ) 14 | 15 | const ( 16 | ONE_KB = 1024 17 | TEN_MILLISECONDS = 10 * time.Millisecond 18 | SUCCESS = 200 19 | RECOGNIZE_ENDPOINT = "/v1/recognize" 20 | ) 21 | 22 | type RecognizeUsingWebsocketOptions struct { 23 | RecognizeOptions 24 | 25 | // Action that is to be performed. Allowable values: start, stop 26 | Action *string `json:"action,omitempty"` 27 | 28 | // If true, the service returns interim results as a stream of JSON SpeechRecognitionResults objects. 29 | // If false, the service returns a single SpeechRecognitionResults object with final results only. 30 | InterimResults *bool `json:"interim_results,omitempty"` 31 | 32 | // If `true`, requests processing metrics about the service's transcription of the input audio. The service returns 33 | // processing metrics at the interval specified by the `processing_metrics_interval` parameter. It also returns 34 | // processing metrics for transcription events, for example, for final and interim results. By default, the service 35 | // returns no processing metrics. 36 | ProcessingMetrics *bool `json:"processing_metrics,omitempty"` 37 | 38 | // Specifies the interval in real wall-clock seconds at which the service is to return processing metrics. The 39 | // parameter is ignored unless the `processing_metrics` parameter is set to `true`. 40 | // 41 | // The parameter accepts a minimum value of 0.1 seconds. The level of precision is not restricted, so you can specify 42 | // values such as 0.25 and 0.125. 43 | // 44 | // The service does not impose a maximum value. If you want to receive processing metrics only for transcription events 45 | // instead of at periodic intervals, set the value to a large number. If the value is larger than the duration of the 46 | // audio, the service returns processing metrics only for transcription events. 47 | ProcessingMetricsInterval *float32 `json:"processing_metrics_interval,omitempty"` 48 | } 49 | 50 | // SetAction: Allows user to set the Action 51 | func (recognizeWSOptions *RecognizeUsingWebsocketOptions) SetAction(action string) *RecognizeUsingWebsocketOptions { 52 | recognizeWSOptions.Action = core.StringPtr(action) 53 | return recognizeWSOptions 54 | } 55 | 56 | // SetInterimResults: Allows user to set InterimResults 57 | func (recognizeWSOptions *RecognizeUsingWebsocketOptions) SetInterimResults(interimResults bool) *RecognizeUsingWebsocketOptions { 58 | recognizeWSOptions.InterimResults = core.BoolPtr(interimResults) 59 | return recognizeWSOptions 60 | } 61 | 62 | // SetProcessingMetrics : Allow user to set ProcessingMetrics 63 | func (recognizeWSOptions *RecognizeUsingWebsocketOptions) SetProcessingMetrics(processingMetrics bool) *RecognizeUsingWebsocketOptions { 64 | recognizeWSOptions.ProcessingMetrics = core.BoolPtr(processingMetrics) 65 | return recognizeWSOptions 66 | } 67 | 68 | // SetProcessingMetricsInterval : Allow user to set ProcessingMetricsInterval 69 | func (recognizeWSOptions *RecognizeUsingWebsocketOptions) SetProcessingMetricsInterval(processingMetricsInterval float32) *RecognizeUsingWebsocketOptions { 70 | recognizeWSOptions.ProcessingMetricsInterval = core.Float32Ptr(processingMetricsInterval) 71 | return recognizeWSOptions 72 | } 73 | 74 | // NewRecognizeUsingWebsocketOptions: Instantiate RecognizeOptions to enable websocket support 75 | func (speechToText *SpeechToTextV1) NewRecognizeUsingWebsocketOptions(audio io.ReadCloser, contentType string) *RecognizeUsingWebsocketOptions { 76 | recognizeOptions := speechToText.NewRecognizeOptions(audio) 77 | recognizeOptions.SetContentType(contentType) 78 | recognizeWSOptions := &RecognizeUsingWebsocketOptions{*recognizeOptions, nil, nil, nil, nil} 79 | return recognizeWSOptions 80 | } 81 | 82 | type WebsocketRecognitionResults struct { 83 | // Acknowledges that a start/end message was received, and indicates 84 | // the start/end of the audio data 85 | State string `json:"state,omitempty"` 86 | Error string `json:"error,omitempty"` 87 | 88 | SpeechRecognitionResults 89 | } 90 | 91 | type RecognizeCallbackWrapper interface { 92 | OnOpen() 93 | OnClose() 94 | OnData(*core.DetailedResponse) 95 | OnError(error) 96 | } 97 | 98 | // RecognizeUsingWebsocket: Recognize audio over websocket connection 99 | func (speechToText *SpeechToTextV1) RecognizeUsingWebsocket(recognizeWSOptions *RecognizeUsingWebsocketOptions, callback RecognizeCallbackWrapper) { 100 | if err := core.ValidateNotNil(recognizeWSOptions, "recognizeOptions cannot be nil"); err != nil { 101 | panic(err) 102 | } 103 | if err := core.ValidateStruct(recognizeWSOptions, "recognizeOptions"); err != nil { 104 | panic(err) 105 | } 106 | 107 | // Add authentication to the outbound request. 108 | if speechToText.Service.Options.Authenticator == nil { 109 | panic(fmt.Errorf("Authentication information was not properly configured.")) 110 | } 111 | 112 | // Create a dummy request for authenticate 113 | // Need to update design to let recognizeListener take in a request object 114 | req, _ := http.NewRequest("POST", speechToText.Service.Options.URL, nil) 115 | err := speechToText.Service.Options.Authenticator.Authenticate(req) 116 | if err != nil { 117 | panic(err) 118 | } 119 | headers := req.Header 120 | 121 | headers.Set("Content-Type", *recognizeWSOptions.ContentType) 122 | 123 | dialURL := strings.Replace(speechToText.Service.Options.URL, "https", "wss", 1) 124 | param := url.Values{} 125 | 126 | if recognizeWSOptions.Model != nil { 127 | param.Set("model", *recognizeWSOptions.Model) 128 | } 129 | if recognizeWSOptions.LanguageCustomizationID != nil { 130 | param.Set("language_customization_id", *recognizeWSOptions.LanguageCustomizationID) 131 | } 132 | if recognizeWSOptions.AcousticCustomizationID != nil { 133 | param.Set("acoustic_customization_id", *recognizeWSOptions.AcousticCustomizationID) 134 | } 135 | if recognizeWSOptions.BaseModelVersion != nil { 136 | param.Set("base_model_version", *recognizeWSOptions.BaseModelVersion) 137 | } 138 | 139 | speechToText.NewRecognizeListener(callback, recognizeWSOptions, dialURL, param, headers) 140 | } 141 | -------------------------------------------------------------------------------- /v2/speechtotextv1/speech_to_text_v1_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2018, 2021. 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 | package speechtotextv1_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestSpeechToTextV1(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "SpeechToTextV1 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v2/speechtotextv1/websocket_listener.go: -------------------------------------------------------------------------------- 1 | package speechtotextv1 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "io" 8 | "net/http" 9 | "net/url" 10 | "time" 11 | 12 | "github.com/IBM/go-sdk-core/v5/core" 13 | "github.com/gorilla/websocket" 14 | ) 15 | 16 | type RecognizeListener struct { 17 | IsClosed chan bool 18 | Callback RecognizeCallbackWrapper 19 | } 20 | 21 | /* 22 | OnOpen: Sends start message to server when connection created 23 | */ 24 | func (wsHandle RecognizeListener) OnOpen(recognizeOpt *RecognizeUsingWebsocketOptions, conn *websocket.Conn) { 25 | wsHandle.Callback.OnOpen() 26 | sendStartMessage(conn, recognizeOpt, &wsHandle) 27 | } 28 | 29 | /* 30 | OnClose: Callback when websocket connection is closed 31 | */ 32 | func (wsHandle RecognizeListener) OnClose() { 33 | <-wsHandle.IsClosed 34 | wsHandle.Callback.OnClose() 35 | } 36 | 37 | /* 38 | OnData: Callback when websocket connection receives data 39 | */ 40 | func (wsHandle RecognizeListener) OnData(conn *websocket.Conn, recognizeOptions *RecognizeUsingWebsocketOptions) { 41 | isListening := false 42 | for { 43 | var websocketResponse WebsocketRecognitionResults 44 | _, result, err := conn.ReadMessage() 45 | if err != nil { 46 | wsHandle.OnError(err) 47 | break 48 | } 49 | err = json.Unmarshal(result, &websocketResponse) 50 | if err != nil { 51 | wsHandle.OnError(err) 52 | break 53 | } 54 | 55 | if websocketResponse.State == "listening" { 56 | if !isListening { 57 | isListening = true 58 | continue 59 | } else { 60 | break 61 | } 62 | } 63 | 64 | if len(websocketResponse.Error) > 0 { 65 | wsHandle.OnError(errors.New(websocketResponse.Error)) 66 | break 67 | } 68 | 69 | detailResp := core.DetailedResponse{} 70 | detailResp.Result = result 71 | detailResp.StatusCode = SUCCESS 72 | wsHandle.Callback.OnData(&detailResp) 73 | } 74 | conn.Close() 75 | wsHandle.IsClosed <- true 76 | } 77 | 78 | /* 79 | OnError: Callback when error encountered 80 | */ 81 | func (wsHandle RecognizeListener) OnError(err error) { 82 | wsHandle.Callback.OnError(err) 83 | } 84 | 85 | /* 86 | sendStartMessage : Sends start message to server 87 | */ 88 | func sendStartMessage(conn *websocket.Conn, textParams *RecognizeUsingWebsocketOptions, recognizeListener *RecognizeListener) { 89 | action := "start" 90 | textParams.Action = &action 91 | startMsgBytes, _ := json.Marshal(textParams) 92 | err := conn.WriteMessage(websocket.TextMessage, startMsgBytes) 93 | if err != nil { 94 | recognizeListener.OnError(err) 95 | } 96 | } 97 | 98 | /* 99 | sendCloseMessage : Sends end message to server 100 | */ 101 | func sendCloseMessage(conn *websocket.Conn) { 102 | stop := "stop" 103 | closeMsgBytes, _ := json.Marshal(RecognizeUsingWebsocketOptions{Action: &stop}) 104 | _ = conn.WriteMessage(websocket.TextMessage, closeMsgBytes) 105 | } 106 | 107 | /* 108 | sendAudio : Sends audio data to the server 109 | */ 110 | func sendAudio(conn *websocket.Conn, recognizeOptions *RecognizeUsingWebsocketOptions, recognizeListener *RecognizeListener) { 111 | chunk := make([]byte, ONE_KB*2) 112 | for { 113 | bytesRead, err := (recognizeOptions.Audio).Read(chunk) 114 | if err != nil { 115 | if err == io.EOF { 116 | break 117 | } else { 118 | recognizeListener.OnError(err) 119 | } 120 | } 121 | err = conn.WriteMessage(websocket.BinaryMessage, chunk[:bytesRead]) 122 | if err != nil { 123 | recognizeListener.OnError(err) 124 | } 125 | time.Sleep(TEN_MILLISECONDS) 126 | } 127 | sendCloseMessage(conn) 128 | } 129 | 130 | /* 131 | NewRecognizeListener : Instantiates a listener instance to control the sending/receiving of audio/text 132 | */ 133 | func (speechToText *SpeechToTextV1) NewRecognizeListener(callback RecognizeCallbackWrapper, recognizeWSOptions *RecognizeUsingWebsocketOptions, dialURL string, param url.Values, headers http.Header) { 134 | recognizeListener := RecognizeListener{Callback: callback, IsClosed: make(chan bool, 1)} 135 | conn, _, err := websocket.DefaultDialer.Dial(fmt.Sprintf("%s%s?%s", dialURL, RECOGNIZE_ENDPOINT, param.Encode()), headers) 136 | if err != nil { 137 | recognizeListener.OnError(err) 138 | } 139 | recognizeListener.OnOpen(recognizeWSOptions, conn) 140 | go recognizeListener.OnData(conn, recognizeWSOptions) 141 | go sendAudio(conn, recognizeWSOptions, &recognizeListener) 142 | recognizeListener.OnClose() 143 | } 144 | -------------------------------------------------------------------------------- /v2/texttospeechv1/synthesize_listener.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2019, 2021. 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 | package texttospeechv1 18 | 19 | import ( 20 | "bytes" 21 | "encoding/json" 22 | "fmt" 23 | "io/ioutil" 24 | "net/http" 25 | 26 | "github.com/IBM/go-sdk-core/v5/core" 27 | "github.com/gorilla/websocket" 28 | ) 29 | 30 | const ( 31 | SUCCESS = 200 32 | ) 33 | 34 | type SynthesizeListener struct { 35 | IsClosed chan bool 36 | Callback SynthesizeCallbackWrapper 37 | } 38 | 39 | func decode(b []byte, target interface{}) { 40 | _ = json.NewDecoder(bytes.NewReader(b)).Decode(&target) 41 | } 42 | 43 | // OnError: Callback when error encountered 44 | func (listener SynthesizeListener) OnError(err error) { 45 | listener.Callback.OnError(err) 46 | } 47 | 48 | // SendText: Sends the text message 49 | // Note: The service handles one request per connection 50 | func (listener SynthesizeListener) SendText(conn *websocket.Conn, req *http.Request) { 51 | listener.OnOpen(conn) 52 | 53 | body, err := ioutil.ReadAll(req.Body) 54 | if err != nil { 55 | listener.OnError(err) 56 | } 57 | err = conn.WriteMessage(websocket.TextMessage, body) 58 | if err != nil { 59 | listener.OnError(err) 60 | } 61 | } 62 | 63 | // OnOpen: Sends start message to server when connection created 64 | func (listener SynthesizeListener) OnOpen(conn *websocket.Conn) { 65 | listener.Callback.OnOpen() 66 | } 67 | 68 | // OnClose: Callback when websocket connection is closed 69 | func (listener SynthesizeListener) OnClose() { 70 | <-listener.IsClosed 71 | listener.Callback.OnClose() 72 | } 73 | 74 | // OnData: Callback when websocket connection receives data 75 | func (listener SynthesizeListener) OnData(conn *websocket.Conn) { 76 | for { 77 | messageType, result, err := conn.ReadMessage() 78 | 79 | // The service will close the connection. We need to decipher 80 | // if the error is a normal close signal 81 | if err != nil { 82 | listener.IsClosed <- true 83 | 84 | if !websocket.IsCloseError(err, websocket.CloseNormalClosure) { 85 | listener.OnError(err) 86 | conn.Close() 87 | } 88 | break 89 | } 90 | 91 | if messageType == websocket.TextMessage { 92 | var r map[string]interface{} 93 | err = json.NewDecoder(bytes.NewReader(result)).Decode(&r) 94 | if err != nil { 95 | listener.OnError(fmt.Errorf(err.Error())) 96 | listener.IsClosed <- true 97 | break 98 | } 99 | if err, ok := r["error"]; ok { 100 | listener.OnError(fmt.Errorf(err.(string))) 101 | listener.IsClosed <- true 102 | break 103 | } 104 | 105 | if _, ok := r["binary_streams"]; ok { 106 | audioContentTypeWrapper := new(AudioContentTypeWrapper) 107 | decode(result, audioContentTypeWrapper) 108 | listener.Callback.OnContentType(audioContentTypeWrapper.BinaryStreams[0].ContentType) 109 | } else if _, ok := r["words"]; ok { 110 | timings := new(Timings) 111 | decode(result, timings) 112 | listener.Callback.OnTimingInformation(*timings) 113 | } else if _, ok := r["marks"]; ok { 114 | marks := new(Marks) 115 | decode(result, marks) 116 | listener.Callback.OnMarks(*marks) 117 | } 118 | } else if messageType == websocket.BinaryMessage { 119 | listener.Callback.OnAudioStream(result) 120 | } 121 | 122 | detailResponse := core.DetailedResponse{} 123 | detailResponse.Result = result 124 | detailResponse.StatusCode = SUCCESS 125 | listener.Callback.OnData(&detailResponse) 126 | } 127 | } 128 | 129 | func (textToSpeechV1 *TextToSpeechV1) NewSynthesizeListener(callback SynthesizeCallbackWrapper, req *http.Request) { 130 | synthesizeListener := SynthesizeListener{Callback: callback, IsClosed: make(chan bool, 1)} 131 | conn, _, err := websocket.DefaultDialer.Dial(req.URL.String(), req.Header) 132 | if err != nil { 133 | synthesizeListener.OnError(err) 134 | } 135 | 136 | go synthesizeListener.OnData(conn) 137 | go synthesizeListener.SendText(conn, req) 138 | synthesizeListener.OnClose() 139 | } 140 | -------------------------------------------------------------------------------- /v2/texttospeechv1/text_to_speech_v1_adapter.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2019, 2021. 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 | package texttospeechv1 18 | 19 | import ( 20 | "fmt" 21 | "strings" 22 | 23 | "github.com/IBM/go-sdk-core/v5/core" 24 | common "github.com/watson-developer-cloud/go-sdk/v2/common" 25 | ) 26 | 27 | // Timings : An array of words and their start and end times in seconds from the beginning of the synthesized audio. 28 | type Timings struct { 29 | Words [][]interface{} `json:"words,omitempty"` 30 | } 31 | 32 | // Timings : An array of mark times 33 | type Marks struct { 34 | Marks [][]interface{} `json:"marks"` 35 | } 36 | 37 | // AudioContentTypeWrapper : The service sends this message to confirm the audio format 38 | type AudioContentTypeWrapper struct { 39 | BinaryStreams []struct { 40 | ContentType string `json:"content_type"` 41 | } `json:"binary_streams"` 42 | } 43 | 44 | // SynthesizeCallbackWrapper : callback for synthesize using websocket 45 | type SynthesizeCallbackWrapper interface { 46 | OnOpen() 47 | OnError(error) 48 | OnContentType(string) 49 | OnTimingInformation(Timings) 50 | OnMarks(Marks) 51 | OnAudioStream([]byte) 52 | OnData(*core.DetailedResponse) 53 | OnClose() 54 | } 55 | 56 | // SynthesizeOptions : The SynthesizeUsingWebsocket options 57 | type SynthesizeUsingWebsocketOptions struct { 58 | SynthesizeOptions 59 | 60 | // Callback to listen to events 61 | Callback SynthesizeCallbackWrapper `json:"callback" validate:"required"` 62 | 63 | // Timings specifies that the service is to return word timing information for all strings of the 64 | // input text. The service returns the start and end time of each string of the input. Specify words as the lone element 65 | // of the array to request word timings. Specify an empty array or omit the parameter to receive no word timings. For 66 | // more information, see [Obtaining word timings](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-timing#timing). 67 | // Not supported for Japanese input text. 68 | Timings []string `json:"action,omitempty"` 69 | } 70 | 71 | // NewSynthesizeUsingWebsocketOptions: Instantiate SynthesizeOptions to enable websocket support 72 | func (textToSpeech *TextToSpeechV1) NewSynthesizeUsingWebsocketOptions(text string, callback SynthesizeCallbackWrapper) *SynthesizeUsingWebsocketOptions { 73 | synthesizeOptions := textToSpeech.NewSynthesizeOptions(text) 74 | synthesizeWSOptions := &SynthesizeUsingWebsocketOptions{*synthesizeOptions, callback, nil} 75 | return synthesizeWSOptions 76 | } 77 | 78 | // SetCallback: Allows user to set the Callback 79 | func (options *SynthesizeUsingWebsocketOptions) SetCallback(callback SynthesizeCallbackWrapper) *SynthesizeUsingWebsocketOptions { 80 | options.Callback = callback 81 | return options 82 | } 83 | 84 | // SetTimings: Allows user to set the Timings 85 | func (options *SynthesizeUsingWebsocketOptions) SetTimings(timings []string) *SynthesizeUsingWebsocketOptions { 86 | options.Timings = timings 87 | return options 88 | } 89 | 90 | // SynthesizeUsingWebsocket: Synthesize text over websocket connection 91 | func (textToSpeech *TextToSpeechV1) SynthesizeUsingWebsocket(synthesizeOptions *SynthesizeUsingWebsocketOptions) error { 92 | if err := core.ValidateNotNil(synthesizeOptions, "synthesizeOptions cannot be nil"); err != nil { 93 | return err 94 | } 95 | if err := core.ValidateStruct(synthesizeOptions, "synthesizeOptions"); err != nil { 96 | return err 97 | } 98 | 99 | // Add authentication to the outbound request. 100 | if textToSpeech.Service.Options.Authenticator == nil { 101 | return fmt.Errorf("Authentication information was not properly configured.") 102 | } 103 | 104 | pathSegments := []string{"v1/synthesize"} 105 | pathParameters := []string{} 106 | 107 | builder := core.NewRequestBuilder(core.POST) 108 | dialURL := strings.Replace(textToSpeech.Service.Options.URL, "https", "wss", 1) 109 | _, err := builder.ConstructHTTPURL(dialURL, pathSegments, pathParameters) 110 | if err != nil { 111 | return err 112 | } 113 | 114 | for headerName, headerValue := range synthesizeOptions.Headers { 115 | builder.AddHeader(headerName, headerValue) 116 | } 117 | 118 | sdkHeaders := common.GetSdkHeaders("text_to_speech", "V1", "Synthesize") 119 | for headerName, headerValue := range sdkHeaders { 120 | builder.AddHeader(headerName, headerValue) 121 | } 122 | 123 | builder.AddHeader("Content-Type", "application/json") 124 | 125 | if synthesizeOptions.Voice != nil { 126 | builder.AddQuery("voice", fmt.Sprint(*synthesizeOptions.Voice)) 127 | } 128 | if synthesizeOptions.CustomizationID != nil { 129 | builder.AddQuery("customization_id", fmt.Sprint(*synthesizeOptions.CustomizationID)) 130 | } 131 | 132 | body := make(map[string]interface{}) 133 | if synthesizeOptions.Text != nil { 134 | body["text"] = synthesizeOptions.Text 135 | } 136 | if synthesizeOptions.Accept != nil { 137 | body["accept"] = synthesizeOptions.Accept 138 | } 139 | if synthesizeOptions.Timings != nil { 140 | body["timings"] = synthesizeOptions.Timings 141 | } 142 | 143 | if _, err := builder.SetBodyContentJSON(body); err != nil { 144 | return err 145 | } 146 | 147 | request, err := builder.Build() 148 | if err != nil { 149 | return err 150 | } 151 | 152 | // Add the authentication header 153 | err = textToSpeech.Service.Options.Authenticator.Authenticate(request) 154 | if err != nil { 155 | return err 156 | } 157 | 158 | textToSpeech.NewSynthesizeListener(synthesizeOptions.Callback, request) 159 | return nil 160 | } 161 | -------------------------------------------------------------------------------- /v2/texttospeechv1/text_to_speech_v1_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2018, 2021. 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 | package texttospeechv1_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestTextToSpeechV1(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "TextToSpeechV1 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v2/toneanalyzerv3/tone_analyzer_v3_examples_test.go: -------------------------------------------------------------------------------- 1 | //go:build examples 2 | // +build examples 3 | 4 | /** 5 | * (C) Copyright IBM Corp. 2021, 2022. 6 | * 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | package toneanalyzerv3_test 21 | 22 | import ( 23 | "encoding/json" 24 | "fmt" 25 | "os" 26 | 27 | "github.com/IBM/go-sdk-core/v5/core" 28 | . "github.com/onsi/ginkgo" 29 | . "github.com/onsi/gomega" 30 | "github.com/watson-developer-cloud/go-sdk/v2/toneanalyzerv3" 31 | ) 32 | 33 | // 34 | // This file provides an example of how to use the Tone Analyzer service. 35 | // 36 | // The following configuration properties are assumed to be defined: 37 | // TONE_ANALYZER_URL= 38 | // TONE_ANALYZER_AUTH_TYPE=iam 39 | // TONE_ANALYZER_APIKEY= 40 | // TONE_ANALYZER_AUTH_URL= 41 | // 42 | // These configuration properties can be exported as environment variables, or stored 43 | // in a configuration file and then: 44 | // export IBM_CREDENTIALS_FILE= 45 | // 46 | const externalConfigFile = "../tone_analyzer_v3.env" 47 | 48 | var ( 49 | toneAnalyzerService *toneanalyzerv3.ToneAnalyzerV3 50 | config map[string]string 51 | configLoaded bool = false 52 | ) 53 | 54 | func shouldSkipTest() { 55 | if !configLoaded { 56 | Skip("External configuration is not available, skipping tests...") 57 | } 58 | } 59 | 60 | var _ = Describe(`ToneAnalyzerV3 Examples Tests`, func() { 61 | Describe(`External configuration`, func() { 62 | It("Successfully load the configuration", func() { 63 | var err error 64 | _, err = os.Stat(externalConfigFile) 65 | if err != nil { 66 | Skip("External configuration file not found, skipping tests: " + err.Error()) 67 | } 68 | 69 | os.Setenv("IBM_CREDENTIALS_FILE", externalConfigFile) 70 | config, err = core.GetServiceProperties(toneanalyzerv3.DefaultServiceName) 71 | if err != nil { 72 | Skip("Error loading service properties, skipping tests: " + err.Error()) 73 | } 74 | 75 | configLoaded = len(config) > 0 76 | }) 77 | }) 78 | 79 | Describe(`Client initialization`, func() { 80 | BeforeEach(func() { 81 | shouldSkipTest() 82 | }) 83 | It("Successfully construct the service client instance", func() { 84 | var err error 85 | 86 | // begin-common 87 | 88 | toneAnalyzerServiceOptions := &toneanalyzerv3.ToneAnalyzerV3Options{ 89 | Version: core.StringPtr("testString"), 90 | } 91 | 92 | toneAnalyzerService, err = toneanalyzerv3.NewToneAnalyzerV3(toneAnalyzerServiceOptions) 93 | 94 | if err != nil { 95 | panic(err) 96 | } 97 | 98 | // end-common 99 | 100 | Expect(toneAnalyzerService).ToNot(BeNil()) 101 | }) 102 | }) 103 | 104 | Describe(`ToneAnalyzerV3 request examples`, func() { 105 | BeforeEach(func() { 106 | shouldSkipTest() 107 | }) 108 | It(`Tone request example`, func() { 109 | fmt.Println("\nTone() result:") 110 | // begin-tone 111 | 112 | toneInputModel := &toneanalyzerv3.ToneInput{ 113 | Text: core.StringPtr("testString"), 114 | } 115 | 116 | toneOptions := toneAnalyzerService.NewToneOptions() 117 | toneOptions.SetToneInput(toneInputModel) 118 | 119 | toneAnalysis, response, err := toneAnalyzerService.Tone(toneOptions) 120 | if err != nil { 121 | panic(err) 122 | } 123 | b, _ := json.MarshalIndent(toneAnalysis, "", " ") 124 | fmt.Println(string(b)) 125 | 126 | // end-tone 127 | 128 | Expect(err).To(BeNil()) 129 | Expect(response.StatusCode).To(Equal(200)) 130 | Expect(toneAnalysis).ToNot(BeNil()) 131 | 132 | }) 133 | It(`ToneChat request example`, func() { 134 | fmt.Println("\nToneChat() result:") 135 | // begin-toneChat 136 | 137 | utteranceModel := &toneanalyzerv3.Utterance{ 138 | Text: core.StringPtr("testString"), 139 | } 140 | 141 | toneChatOptions := toneAnalyzerService.NewToneChatOptions( 142 | []toneanalyzerv3.Utterance{*utteranceModel}, 143 | ) 144 | 145 | utteranceAnalyses, response, err := toneAnalyzerService.ToneChat(toneChatOptions) 146 | if err != nil { 147 | panic(err) 148 | } 149 | b, _ := json.MarshalIndent(utteranceAnalyses, "", " ") 150 | fmt.Println(string(b)) 151 | 152 | // end-toneChat 153 | 154 | Expect(err).To(BeNil()) 155 | Expect(response.StatusCode).To(Equal(200)) 156 | Expect(utteranceAnalyses).ToNot(BeNil()) 157 | 158 | }) 159 | }) 160 | }) 161 | -------------------------------------------------------------------------------- /v2/toneanalyzerv3/tone_analyzer_v3_integration_test.go: -------------------------------------------------------------------------------- 1 | //go:build integration 2 | // +build integration 3 | 4 | package toneanalyzerv3_test 5 | 6 | /** 7 | * (C) Copyright IBM Corp. 2018, 2022. 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | import ( 23 | "net/http" 24 | "testing" 25 | 26 | "github.com/IBM/go-sdk-core/v5/core" 27 | "github.com/joho/godotenv" 28 | "github.com/stretchr/testify/assert" 29 | "github.com/watson-developer-cloud/go-sdk/v2/toneanalyzerv3" 30 | ) 31 | 32 | const skipMessage = "External configuration could not be loaded, skipping..." 33 | 34 | var configLoaded bool 35 | var configFile = "../../.env" 36 | 37 | var service *toneanalyzerv3.ToneAnalyzerV3 38 | 39 | func shouldSkipTest(t *testing.T) { 40 | if !configLoaded { 41 | t.Skip(skipMessage) 42 | } 43 | } 44 | 45 | func TestLoadConfig(t *testing.T) { 46 | err := godotenv.Load(configFile) 47 | if err != nil { 48 | t.Skip(skipMessage) 49 | } else { 50 | configLoaded = true 51 | } 52 | } 53 | 54 | func TestConstructService(t *testing.T) { 55 | shouldSkipTest(t) 56 | 57 | var err error 58 | 59 | service, err = toneanalyzerv3.NewToneAnalyzerV3( 60 | &toneanalyzerv3.ToneAnalyzerV3Options{ 61 | Version: core.StringPtr("2017-09-21"), 62 | }) 63 | assert.Nil(t, err) 64 | assert.NotNil(t, service) 65 | 66 | if err == nil { 67 | customHeaders := http.Header{} 68 | customHeaders.Add("X-Watson-Learning-Opt-Out", "1") 69 | customHeaders.Add("X-Watson-Test", "1") 70 | service.Service.SetDefaultHeaders(customHeaders) 71 | } 72 | } 73 | 74 | func TestTone(t *testing.T) { 75 | shouldSkipTest(t) 76 | 77 | text := "Team, I know that times are tough! Product sales have been disappointing for the past three quarters. We have a competitive product, but we need to do a better job of selling it!" 78 | tone, _, responseErr := service.Tone( 79 | &toneanalyzerv3.ToneOptions{ 80 | ToneInput: &toneanalyzerv3.ToneInput{ 81 | Text: &text, 82 | }, 83 | ContentType: core.StringPtr("application/json"), 84 | }, 85 | ) 86 | assert.Nil(t, responseErr) 87 | assert.NotNil(t, tone) 88 | } 89 | 90 | func TestToneChat(t *testing.T) { 91 | shouldSkipTest(t) 92 | 93 | utterances := []toneanalyzerv3.Utterance{ 94 | { 95 | Text: core.StringPtr("Hello, I'm having a problem with your product."), 96 | User: core.StringPtr("customer"), 97 | }, 98 | { 99 | Text: core.StringPtr("OK, let me know what's going on, please."), 100 | User: core.StringPtr("agent"), 101 | }, 102 | { 103 | Text: core.StringPtr("Well, nothing is working :("), 104 | User: core.StringPtr("customer"), 105 | }, 106 | { 107 | Text: core.StringPtr("Sorry to hear that."), 108 | User: core.StringPtr("agent"), 109 | }, 110 | } 111 | 112 | options := service.NewToneChatOptions(utterances) 113 | toneChat, _, responseErr := service.ToneChat(options) 114 | assert.Nil(t, responseErr) 115 | assert.NotNil(t, toneChat) 116 | } 117 | -------------------------------------------------------------------------------- /v2/toneanalyzerv3/tone_analyzer_v3_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2018, 2021. 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 | package toneanalyzerv3_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestToneAnalyzerV3(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "ToneAnalyzerV3 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v2/visualrecognitionv3/visual_recognition_v3_integration_test.go: -------------------------------------------------------------------------------- 1 | //go:build integration 2 | // +build integration 3 | 4 | package visualrecognitionv3_test 5 | 6 | /** 7 | * (C) Copyright IBM Corp. 2018, 2022. 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | import ( 23 | "io" 24 | "net/http" 25 | "os" 26 | "testing" 27 | 28 | "github.com/IBM/go-sdk-core/v5/core" 29 | "github.com/joho/godotenv" 30 | "github.com/stretchr/testify/assert" 31 | "github.com/watson-developer-cloud/go-sdk/v2/visualrecognitionv3" 32 | ) 33 | 34 | const skipMessage = "External configuration could not be loaded, skipping..." 35 | 36 | var configLoaded bool 37 | var configFile = "../../.env" 38 | 39 | var service *visualrecognitionv3.VisualRecognitionV3 40 | 41 | func shouldSkipTest(t *testing.T) { 42 | if !configLoaded { 43 | t.Skip(skipMessage) 44 | } 45 | } 46 | 47 | func TestLoadConfig(t *testing.T) { 48 | err := godotenv.Load(configFile) 49 | if err != nil { 50 | t.Skip(skipMessage) 51 | } else { 52 | configLoaded = true 53 | } 54 | } 55 | 56 | func TestConstructService(t *testing.T) { 57 | shouldSkipTest(t) 58 | 59 | var err error 60 | 61 | service, err = visualrecognitionv3.NewVisualRecognitionV3( 62 | &visualrecognitionv3.VisualRecognitionV3Options{ 63 | Version: core.StringPtr("2018-03-19"), 64 | ServiceName: "visual_recognition", 65 | }) 66 | assert.Nil(t, err) 67 | assert.NotNil(t, service) 68 | 69 | if err == nil { 70 | customHeaders := http.Header{} 71 | customHeaders.Add("X-Watson-Learning-Opt-Out", "1") 72 | customHeaders.Add("X-Watson-Test", "1") 73 | service.Service.SetDefaultHeaders(customHeaders) 74 | } 75 | } 76 | 77 | func TestClassify(t *testing.T) { 78 | shouldSkipTest(t) 79 | 80 | // Classify 81 | imageFile, imageFileErr := os.Open("../resources/kitty.jpg") 82 | assert.Nil(t, imageFileErr) 83 | defer imageFile.Close() 84 | 85 | classify, _, responseErr := service.Classify( 86 | &visualrecognitionv3.ClassifyOptions{ 87 | ImagesFile: imageFile, 88 | Threshold: core.Float32Ptr(0.6), 89 | ClassifierIds: []string{"default"}, 90 | }, 91 | ) 92 | assert.Nil(t, responseErr) 93 | assert.NotNil(t, classify) 94 | } 95 | 96 | func TestClassifiers(t *testing.T) { 97 | shouldSkipTest(t) 98 | 99 | // Create classifier 100 | carsFile, carsFileErr := os.Open("../resources/cars.zip") 101 | assert.Nil(t, carsFileErr) 102 | defer carsFile.Close() 103 | 104 | trucksFile, trucksFileErr := os.Open("../resources/trucks.zip") 105 | assert.Nil(t, trucksFileErr) 106 | defer trucksFile.Close() 107 | 108 | positiveExamples := make(map[string]io.ReadCloser) 109 | positiveExamples["cars"] = carsFile 110 | 111 | createClassifier, _, responseErr := service.CreateClassifier( 112 | &visualrecognitionv3.CreateClassifierOptions{ 113 | Name: core.StringPtr("Cars vs trucks"), 114 | PositiveExamples: positiveExamples, 115 | NegativeExamples: trucksFile, 116 | }, 117 | ) 118 | assert.Nil(t, responseErr) 119 | assert.NotNil(t, createClassifier) 120 | 121 | // List classifiers 122 | listClassifiers, _, responseErr := service.ListClassifiers( 123 | &visualrecognitionv3.ListClassifiersOptions{ 124 | Verbose: core.BoolPtr(true), 125 | }, 126 | ) 127 | assert.Nil(t, responseErr) 128 | assert.NotNil(t, listClassifiers) 129 | 130 | // Get classifier 131 | getClassifier, _, responseErr := service.GetClassifier( 132 | &visualrecognitionv3.GetClassifierOptions{ 133 | ClassifierID: createClassifier.ClassifierID, 134 | }, 135 | ) 136 | assert.Nil(t, responseErr) 137 | assert.NotNil(t, getClassifier) 138 | 139 | // Delete classifier 140 | _, responseErr = service.DeleteClassifier( 141 | &visualrecognitionv3.DeleteClassifierOptions{ 142 | ClassifierID: createClassifier.ClassifierID, 143 | }, 144 | ) 145 | assert.Nil(t, responseErr) 146 | } 147 | -------------------------------------------------------------------------------- /v2/visualrecognitionv3/visual_recognition_v3_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2018, 2021. 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 | package visualrecognitionv3_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestVisualRecognitionV3(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "VisualRecognitionV3 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v2/visualrecognitionv4/visual_recognition_v4_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2019, 2021. 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 | package visualrecognitionv4_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestVisualRecognitionV4(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "VisualRecognitionV4 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v3/assistantv1/assistant_v1_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2018, 2022. 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 | package assistantv1_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestAssistantV1(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "AssistantV1 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v3/assistantv2/assistant_v2_integration_test.go: -------------------------------------------------------------------------------- 1 | //go:build integration 2 | // +build integration 3 | 4 | package assistantv2_test 5 | 6 | /** 7 | * (C) Copyright IBM Corp. 2018, 2022. 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | import ( 23 | "net/http" 24 | "os" 25 | "testing" 26 | 27 | "github.com/IBM/go-sdk-core/v5/core" 28 | "github.com/joho/godotenv" 29 | "github.com/stretchr/testify/assert" 30 | "github.com/watson-developer-cloud/go-sdk/v3/assistantv2" 31 | ) 32 | 33 | const skipMessage = "External configuration could not be loaded, skipping..." 34 | 35 | var configLoaded bool 36 | var configFile = "../../.env" 37 | 38 | var service *assistantv2.AssistantV2 39 | var assistantId string 40 | 41 | func shouldSkipTest(t *testing.T) { 42 | if !configLoaded { 43 | t.Skip(skipMessage) 44 | } 45 | } 46 | 47 | func TestLoadConfig(t *testing.T) { 48 | err := godotenv.Load(configFile) 49 | if err != nil { 50 | t.Skip(skipMessage) 51 | } 52 | 53 | assistantId = os.Getenv("ASSISTANT_ID") 54 | assert.NotEmpty(t, assistantId) 55 | if assistantId != "" { 56 | configLoaded = true 57 | } 58 | } 59 | 60 | func TestConstructService(t *testing.T) { 61 | shouldSkipTest(t) 62 | 63 | var err error 64 | 65 | service, err = assistantv2.NewAssistantV2(&assistantv2.AssistantV2Options{ 66 | Version: core.StringPtr("2020-04-01"), 67 | ServiceName: "assistant", 68 | }) 69 | assert.Nil(t, err) 70 | assert.NotNil(t, service) 71 | 72 | if err == nil { 73 | customHeaders := http.Header{} 74 | customHeaders.Add("X-Watson-Learning-Opt-Out", "1") 75 | customHeaders.Add("X-Watson-Test", "1") 76 | service.Service.SetDefaultHeaders(customHeaders) 77 | } 78 | } 79 | 80 | func TestSession(t *testing.T) { 81 | shouldSkipTest(t) 82 | 83 | // Create session 84 | createSession, _, responseErr := service.CreateSession( 85 | &assistantv2.CreateSessionOptions{ 86 | AssistantID: core.StringPtr(assistantId), 87 | }, 88 | ) 89 | assert.Nil(t, responseErr) 90 | assert.NotNil(t, createSession) 91 | 92 | // Message 93 | message, _, responseErr := service.Message( 94 | &assistantv2.MessageOptions{ 95 | AssistantID: core.StringPtr(assistantId), 96 | SessionID: createSession.SessionID, 97 | UserID: core.StringPtr("dummy"), 98 | Input: &assistantv2.MessageInput{ 99 | Text: core.StringPtr("Whats the weather like?"), 100 | }, 101 | Context: &assistantv2.MessageContext{ 102 | Skills: map[string]assistantv2.MessageContextSkill{ 103 | "main_skill": { 104 | UserDefined: map[string]interface{}{ 105 | "user_defined": map[string]string{ 106 | "account_number": "12345", 107 | }, 108 | }, 109 | }, 110 | }, 111 | }, 112 | }, 113 | ) 114 | assert.Nil(t, responseErr) 115 | assert.NotNil(t, message) 116 | 117 | // Delete session 118 | _, responseErr = service.DeleteSession( 119 | &assistantv2.DeleteSessionOptions{ 120 | AssistantID: core.StringPtr(assistantId), 121 | SessionID: createSession.SessionID, 122 | }, 123 | ) 124 | assert.Nil(t, responseErr) 125 | } 126 | 127 | func TestMessageStateless(t *testing.T) { 128 | shouldSkipTest(t) 129 | 130 | message, _, responseErr := service.MessageStateless( 131 | &assistantv2.MessageStatelessOptions{ 132 | AssistantID: core.StringPtr(assistantId), 133 | Input: &assistantv2.MessageInputStateless{ 134 | MessageType: core.StringPtr("text"), 135 | Text: core.StringPtr("Hello, this is test."), 136 | }, 137 | }, 138 | ) 139 | 140 | assert.Nil(t, responseErr) 141 | assert.NotNil(t, message) 142 | } 143 | 144 | func TestListLogs(t *testing.T) { 145 | t.Skip("endpoint only available on premium instance") 146 | 147 | options := service.NewListLogsOptions(assistantId) 148 | logs, _, responseErr := service.ListLogs(options) 149 | 150 | assert.Nil(t, responseErr) 151 | assert.NotNil(t, logs) 152 | } 153 | -------------------------------------------------------------------------------- /v3/assistantv2/assistant_v2_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2018, 2022. 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 | package assistantv2_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestAssistantV2(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "AssistantV2 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v3/common/headers.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "fmt" 5 | "runtime" 6 | ) 7 | 8 | const ( 9 | HEADER_SDK_ANALYTICS = "X-IBMCloud-SDK-Analytics" 10 | HEADER_USER_AGENT = "User-Agent" 11 | 12 | SDK_NAME = "watson-apis-go-sdk" 13 | ) 14 | 15 | // GetSdkHeaders - returns the set of SDK-specific headers to be included in an outgoing request. 16 | func GetSdkHeaders(serviceName string, serviceVersion string, operationId string) map[string]string { 17 | sdkHeaders := make(map[string]string) 18 | 19 | sdkHeaders[HEADER_SDK_ANALYTICS] = fmt.Sprintf("service_name=%s;service_version=%s;operation_id=%s", 20 | serviceName, serviceVersion, operationId) 21 | 22 | sdkHeaders[HEADER_USER_AGENT] = GetUserAgentInfo() 23 | 24 | return sdkHeaders 25 | } 26 | 27 | var userAgent string = fmt.Sprintf("%s-%s %s", SDK_NAME, Version, GetSystemInfo()) 28 | 29 | func GetUserAgentInfo() string { 30 | return userAgent 31 | } 32 | 33 | var systemInfo = fmt.Sprintf("(arch=%s; os=%s; go.version=%s)", runtime.GOARCH, runtime.GOOS, runtime.Version()) 34 | 35 | func GetSystemInfo() string { 36 | return systemInfo 37 | } 38 | -------------------------------------------------------------------------------- /v3/common/headers_test.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "strings" 6 | "testing" 7 | ) 8 | 9 | func TestGetSystemInfo(t *testing.T) { 10 | var sysinfo = GetSystemInfo() 11 | assert.NotNil(t, sysinfo) 12 | assert.True(t, strings.Contains(sysinfo, "arch=")) 13 | assert.True(t, strings.Contains(sysinfo, "os=")) 14 | assert.True(t, strings.Contains(sysinfo, "go.version=")) 15 | } 16 | 17 | func TestGetSdkHeaders(t *testing.T) { 18 | var headers = GetSdkHeaders("myService", "v123", "myOperation") 19 | assert.NotNil(t, headers) 20 | 21 | var foundIt bool 22 | _, foundIt = headers[HEADER_SDK_ANALYTICS] 23 | assert.True(t, foundIt) 24 | 25 | _, foundIt = headers[HEADER_USER_AGENT] 26 | assert.True(t, foundIt) 27 | } 28 | -------------------------------------------------------------------------------- /v3/common/version.go: -------------------------------------------------------------------------------- 1 | package common 2 | 3 | // Version of the SDK 4 | const Version = "3.0.0" 5 | -------------------------------------------------------------------------------- /v3/discoveryv1/discovery_v1_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2018, 2022. 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 | package discoveryv1_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestDiscoveryV1(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "DiscoveryV1 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v3/discoveryv2/discovery_v2_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2019, 2022. 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 | package discoveryv2_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestDiscoveryV2(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "DiscoveryV2 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v3/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/watson-developer-cloud/go-sdk/v3 2 | 3 | go 1.14 4 | 5 | require ( 6 | github.com/IBM/go-sdk-core/v5 v5.9.2 7 | github.com/go-openapi/strfmt v0.21.2 8 | github.com/gorilla/websocket v1.5.0 9 | github.com/joho/godotenv v1.4.0 10 | github.com/onsi/ginkgo v1.16.5 11 | github.com/onsi/gomega v1.18.1 12 | github.com/stretchr/testify v1.7.0 13 | golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd // indirect 14 | ) 15 | -------------------------------------------------------------------------------- /v3/languagetranslatorv3/language_translator_v3_integration_test.go: -------------------------------------------------------------------------------- 1 | //go:build integration 2 | // +build integration 3 | 4 | package languagetranslatorv3_test 5 | 6 | /** 7 | * (C) Copyright IBM Corp. 2018, 2022. 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); 10 | * you may not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | import ( 23 | "net/http" 24 | "os" 25 | "testing" 26 | 27 | "github.com/IBM/go-sdk-core/v5/core" 28 | "github.com/joho/godotenv" 29 | "github.com/stretchr/testify/assert" 30 | "github.com/watson-developer-cloud/go-sdk/v3/languagetranslatorv3" 31 | ) 32 | 33 | const skipMessage = "External configuration could not be loaded, skipping..." 34 | 35 | var configLoaded bool 36 | var configFile = "../../.env" 37 | 38 | var service *languagetranslatorv3.LanguageTranslatorV3 39 | 40 | func shouldSkipTest(t *testing.T) { 41 | if !configLoaded { 42 | t.Skip(skipMessage) 43 | } 44 | } 45 | 46 | func TestLoadConfig(t *testing.T) { 47 | err := godotenv.Load(configFile) 48 | if err != nil { 49 | t.Skip(skipMessage) 50 | } else { 51 | configLoaded = true 52 | } 53 | } 54 | 55 | func TestConstructService(t *testing.T) { 56 | shouldSkipTest(t) 57 | 58 | var err error 59 | 60 | service, err = languagetranslatorv3.NewLanguageTranslatorV3( 61 | &languagetranslatorv3.LanguageTranslatorV3Options{ 62 | Version: core.StringPtr("2020-04-01"), 63 | }) 64 | assert.Nil(t, err) 65 | assert.NotNil(t, service) 66 | 67 | if err == nil { 68 | customHeaders := http.Header{} 69 | customHeaders.Add("X-Watson-Learning-Opt-Out", "1") 70 | customHeaders.Add("X-Watson-Test", "1") 71 | service.Service.SetDefaultHeaders(customHeaders) 72 | } 73 | } 74 | 75 | func TestModels(t *testing.T) { 76 | shouldSkipTest(t) 77 | 78 | // List models 79 | listModels, response, responseErr := service.ListModels( 80 | &languagetranslatorv3.ListModelsOptions{}, 81 | ) 82 | assert.Nil(t, responseErr) 83 | assert.NotNil(t, response) 84 | assert.NotNil(t, listModels) 85 | 86 | // Create model 87 | glossary, glossaryErr := os.Open("../resources/glossary.tmx") 88 | assert.Nil(t, glossaryErr) 89 | 90 | createModel, _, responseErr := service.CreateModel( 91 | &languagetranslatorv3.CreateModelOptions{ 92 | BaseModelID: core.StringPtr("en-fr"), 93 | Name: core.StringPtr("custom-en-fr"), 94 | ForcedGlossary: glossary, 95 | }, 96 | ) 97 | assert.Nil(t, responseErr) 98 | assert.NotNil(t, createModel) 99 | 100 | // Get model 101 | getModel, _, responseErr := service.GetModel( 102 | &languagetranslatorv3.GetModelOptions{ 103 | ModelID: createModel.ModelID, 104 | }, 105 | ) 106 | assert.Nil(t, responseErr) 107 | assert.NotNil(t, getModel) 108 | 109 | // Delete model 110 | _, _, responseErr = service.DeleteModel( 111 | &languagetranslatorv3.DeleteModelOptions{ 112 | ModelID: createModel.ModelID, 113 | }, 114 | ) 115 | assert.Nil(t, responseErr) 116 | } 117 | 118 | func TestTranslate(t *testing.T) { 119 | shouldSkipTest(t) 120 | 121 | translate, _, responseErr := service.Translate( 122 | &languagetranslatorv3.TranslateOptions{ 123 | Text: []string{"Hello"}, 124 | ModelID: core.StringPtr("en-es"), 125 | }, 126 | ) 127 | assert.Nil(t, responseErr) 128 | assert.NotNil(t, translate) 129 | } 130 | 131 | func TestIdentifiableLanguage(t *testing.T) { 132 | shouldSkipTest(t) 133 | 134 | identifiableLanguage, _, responseErr := service.ListIdentifiableLanguages( 135 | &languagetranslatorv3.ListIdentifiableLanguagesOptions{}, 136 | ) 137 | assert.Nil(t, responseErr) 138 | assert.NotNil(t, identifiableLanguage) 139 | } 140 | 141 | func TestIdentify(t *testing.T) { 142 | shouldSkipTest(t) 143 | 144 | identify, _, responseErr := service.Identify( 145 | &languagetranslatorv3.IdentifyOptions{ 146 | Text: core.StringPtr("Language translator translates text from one language to another"), 147 | }, 148 | ) 149 | assert.Nil(t, responseErr) 150 | assert.NotNil(t, identify) 151 | } 152 | 153 | func TestDocumentTranslation(t *testing.T) { 154 | shouldSkipTest(t) 155 | 156 | // List documents 157 | listDocuments, _, responseErr := service.ListDocuments( 158 | &languagetranslatorv3.ListDocumentsOptions{}, 159 | ) 160 | assert.Nil(t, responseErr) 161 | assert.NotNil(t, listDocuments) 162 | 163 | // translate document 164 | pwd, _ := os.Getwd() 165 | document, documentErr := os.Open(pwd + "/../resources/hello_world.txt") 166 | assert.Nil(t, documentErr) 167 | 168 | translateDocument, _, responseErr := service.TranslateDocument( 169 | &languagetranslatorv3.TranslateDocumentOptions{ 170 | File: document, 171 | Filename: core.StringPtr("hello_world"), 172 | FileContentType: core.StringPtr("text/plain"), 173 | ModelID: core.StringPtr("en-es"), 174 | }, 175 | ) 176 | assert.Nil(t, responseErr) 177 | assert.NotNil(t, translateDocument) 178 | 179 | // Document status 180 | documentStatus, _, responseErr := service.GetDocumentStatus( 181 | &languagetranslatorv3.GetDocumentStatusOptions{ 182 | DocumentID: translateDocument.DocumentID, 183 | }, 184 | ) 185 | assert.Nil(t, responseErr) 186 | assert.NotNil(t, documentStatus) 187 | 188 | // Delete document 189 | _, responseErr = service.DeleteDocument( 190 | &languagetranslatorv3.DeleteDocumentOptions{ 191 | DocumentID: translateDocument.DocumentID, 192 | }, 193 | ) 194 | assert.Nil(t, responseErr) 195 | } 196 | 197 | func TestListLanguages(t *testing.T) { 198 | shouldSkipTest(t) 199 | 200 | listLanguages, _, listErr := service.ListLanguages( 201 | &languagetranslatorv3.ListLanguagesOptions{}, 202 | ) 203 | 204 | assert.NotNil(t, listLanguages) 205 | assert.Nil(t, listErr) 206 | } 207 | -------------------------------------------------------------------------------- /v3/languagetranslatorv3/language_translator_v3_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2018, 2022. 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 | package languagetranslatorv3_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestLanguageTranslatorV3(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "LanguageTranslatorV3 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v3/naturallanguageunderstandingv1/natural_language_understanding_v1_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2018, 2022. 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 | package naturallanguageunderstandingv1_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestNaturalLanguageUnderstandingV1(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "NaturalLanguageUnderstandingV1 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v3/resources/CarsvsTrucks.mlmodel: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v3/resources/CarsvsTrucks.mlmodel -------------------------------------------------------------------------------- /v3/resources/South_Africa_Luca_Galuzzi_2004.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v3/resources/South_Africa_Luca_Galuzzi_2004.jpeg -------------------------------------------------------------------------------- /v3/resources/TestEnrichments.csv: -------------------------------------------------------------------------------- 1 | engine,gasket,carburetor,piston,valves 2 | racing,stock,open,indy,drag 3 | flag,checkered,green,caution,yellow,red 4 | -------------------------------------------------------------------------------- /v3/resources/audio_example.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v3/resources/audio_example.mp3 -------------------------------------------------------------------------------- /v3/resources/audio_raw_example.raw: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v3/resources/audio_raw_example.raw -------------------------------------------------------------------------------- /v3/resources/car.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v3/resources/car.jpg -------------------------------------------------------------------------------- /v3/resources/cars.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v3/resources/cars.zip -------------------------------------------------------------------------------- /v3/resources/confirm-grammar.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | affirmative 5 | nah 6 | no 7 | nope 8 | yeah 9 | yep 10 | yes 11 | yup 12 | fine 13 | negative 14 | OK 15 | sure 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /v3/resources/contract_A.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v3/resources/contract_A.pdf -------------------------------------------------------------------------------- /v3/resources/contract_B.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v3/resources/contract_B.pdf -------------------------------------------------------------------------------- /v3/resources/corpus-short-1.txt: -------------------------------------------------------------------------------- 1 | Am I at risk for health problems during travel 2 | Some people are more likely to have health problems when traveling outside the United States Visit your doctor before planning a trip to another country especially if you 3 | How Is Coronary Microvascular Disease Treated 4 | If youre diagnosed with coronary MVD and also have anemia you may benefit from treatment for that condition Anemia is thought to slow the growth of cells needed to repair damaged blood vessels 5 | What causes autoimmune hepatitis 6 | A combination of autoimmunity environmental triggers and a genetic predisposition can lead to autoimmune hepatitis 7 | What research is being done for Spinal Cord Injury 8 | The National Institute of Neurological Disorders and Stroke NINDS conducts spinal cord research in its laboratories at the National Institutes of Health NIH and also supports additional research through grants to major research institutions across the country Advances in research are giving doctors and patients hope that repairing injured spinal cords is a reachable goal Advances in basic research are also being matched by progress in clinical research especially in understanding the kinds of physical rehabilitation that work best to restore function Some of the more promising rehabilitation techniques are helping spinal cord injury patients become more mobile 9 | What is Osteogenesis imperfecta OI 10 | Osteogenesis imperfecta OI is a rare genetic disorder that like juvenile osteoporosis is characterized by bones that break easily often from little or no apparent cause 11 | -------------------------------------------------------------------------------- /v3/resources/corpus.tmx: -------------------------------------------------------------------------------- 1 | 2 | 3 |
11 | 12 | 13 | RESOLUTION 55/100 14 | RÉSOLUTION 55/100 15 | 16 | 17 | Adopted at the 81st plenary meeting, on 4 December 2000, on the recommendation of the Committee (A/55/602/Add.2 and Corr.1, para. 94),The draft resolution recommended in the report was sponsored in the Committee by: Bolivia, Cuba, El Salvador, Ghana and Honduras. by a recorded vote of 106 to 1, with 67 abstentions, as follows: 18 | Adoptée à la 81e séance plénière, le 4 décembre 2000, sur la recommandation de la Commission (A/55/602/Add.2, par. 94)Le projet de résolution recommandé dans le rapport de la Commission avait pour auteurs les pays suivants: Bolivie, Cuba, El Salvador, Ghana et Honduras., par 106 voix contre une, avec 67 abstentions, à la suite d'un vote enregistré, les voix s'étant réparties comme suit: 19 | 20 | 21 | -------------------------------------------------------------------------------- /v3/resources/dummy-storage-credentials.json: -------------------------------------------------------------------------------- 1 | { 2 | "apikey": "random-apikey", 3 | "cos_hmac_keys": { 4 | "access_key_id": "aaaa", 5 | "secret_access_key": "bbb" 6 | }, 7 | "endpoints": "https://cos-service.bluemix.net/endpoints", 8 | "iam_apikey_description": "Auto generated apikey during resource-key operation for Instance - crn:v1:bluemix:public:cloud-object-storage:global:a/070794137072b93b6eb44420201f6194:c290d41e-c445-420e-ad44-65b2a15a7c6c::", 9 | "iam_apikey_name": "auto-generated-apikey-5a3550b4-e3af-40b7-8bda-0fb839533c02", 10 | "iam_role_crn": "crn:v1:bluemix:public:iam::::serviceRole:Manager", 11 | "iam_serviceid_crn": "crn:v1:bluemix:public:iam-identity::a/070794137072b93b6eb44420201f6194::serviceid:ServiceId-3ff1a723-d223-41ff-99e4-32ff8d022549", 12 | "resource_instance_id": "crn:v1:bluemix:public:cloud-object-storage:global:a/xxx:yyy::" 13 | } -------------------------------------------------------------------------------- /v3/resources/face.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v3/resources/face.jpg -------------------------------------------------------------------------------- /v3/resources/glossary.tmx: -------------------------------------------------------------------------------- 1 | 2 | 3 |
6 | 7 | 8 | 9 | International Business Machines 10 | 11 | 12 | International Business Machines 13 | 14 | 15 | 16 | 17 | patent 18 | 19 | 20 | brevent 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /v3/resources/hello_world.txt: -------------------------------------------------------------------------------- 1 | hello world 2 | -------------------------------------------------------------------------------- /v3/resources/kitty.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v3/resources/kitty.jpg -------------------------------------------------------------------------------- /v3/resources/language_translator_model.tmx: -------------------------------------------------------------------------------- 1 | 2 | 3 |
6 | 7 | 8 | 9 | International Business Machines 10 | 11 | 12 | International Business Machines 13 | 14 | 15 | 16 | 17 | patent 18 | 19 | 20 | brevent 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /v3/resources/my-giraffe.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v3/resources/my-giraffe.jpeg -------------------------------------------------------------------------------- /v3/resources/nlu_categories_training.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "labels": [ 4 | "level1" 5 | ], 6 | "key_phrases": [ 7 | "key phrase", 8 | "key phrase 2" 9 | ] 10 | }, 11 | { 12 | "labels": [ 13 | "level1", 14 | "level2" 15 | ], 16 | "key_phrases": [ 17 | "key phrase 3", 18 | "key phrase 4" 19 | ] 20 | } 21 | ] 22 | 23 | -------------------------------------------------------------------------------- /v3/resources/nlu_classifications_training.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "text": "Example 1", 4 | "labels": ["label1"] 5 | }, 6 | { 7 | "text": "Example 2", 8 | "labels": ["label1", "label2"] 9 | }, 10 | { 11 | "text": "Example 3", 12 | "labels": ["label1"] 13 | }, 14 | { 15 | "text": "Example 4", 16 | "labels": ["label1", "label2"] 17 | }, 18 | { 19 | "text": "Example 5", 20 | "labels": ["label1"] 21 | }, 22 | { 23 | "text": "Example 6", 24 | "labels": ["label1", "label2"] 25 | }, 26 | { 27 | "text": "Example 7", 28 | "labels": ["label1"] 29 | }, 30 | { 31 | "text": "Example 8", 32 | "labels": ["label1", "label2"] 33 | }, 34 | { 35 | "text": "Example 9", 36 | "labels": ["label1"] 37 | }, 38 | { 39 | "text": "Example 10", 40 | "labels": ["label1", "label2"] 41 | } 42 | ] 43 | -------------------------------------------------------------------------------- /v3/resources/nlu_training_data.csv: -------------------------------------------------------------------------------- 1 | doc,label 2 | Today is a great day,positive 3 | Tomorrow will be a great day,positive 4 | I am really happy,positive 5 | This is amazing,positive 6 | Wow that’s really cool,positive 7 | That looks great on you,positive 8 | This outfit is really nice,positive 9 | I think you did a great job,positive 10 | Nice work!,positive 11 | This is ok,neutral 12 | Ehh I've seen this before,neutral 13 | No comment,neutral 14 | How are you?,neutral 15 | Hello,neutral 16 | I don’t have an opinion on that subject,neutral 17 | I enjoyed it more or less,neutral 18 | This product stinks!,negative 19 | I did not have a good time,negative 20 | Worst game ever!,negative -------------------------------------------------------------------------------- /v3/resources/output.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v3/resources/output.wav -------------------------------------------------------------------------------- /v3/resources/sample-tables.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v3/resources/sample-tables.pdf -------------------------------------------------------------------------------- /v3/resources/sample-tables.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v3/resources/sample-tables.png -------------------------------------------------------------------------------- /v3/resources/simple.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Simple HTML Page 4 | 5 | 6 |

Chapter 1

7 |

The content of the first chapter.

8 | 9 | -------------------------------------------------------------------------------- /v3/resources/tone-example.html: -------------------------------------------------------------------------------- 1 |

Team, I know that times are tough!

Product sales have been disappointing for the past three quarters.

We have a competitive product, but we need to do a better job of selling it!

2 | 3 | -------------------------------------------------------------------------------- /v3/resources/trucks.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v3/resources/trucks.zip -------------------------------------------------------------------------------- /v3/resources/tts_audio.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/watson-developer-cloud/go-sdk/cea2c2d14d2989b3d6d58a6a55a2477b00ff45a3/v3/resources/tts_audio.wav -------------------------------------------------------------------------------- /v3/resources/weather_training_data.csv: -------------------------------------------------------------------------------- 1 | How hot is it today?,temperature 2 | Is it hot outside?,temperature 3 | Will it be uncomfortably hot?,temperature 4 | Will it be sweltering?,temperature 5 | How cold is it today?,temperature 6 | Is it cold outside?,temperature 7 | Will it be uncomfortably cold?,temperature 8 | Will it be frigid?,temperature 9 | What is the expected high for today?,temperature 10 | What is the expected temperature?,temperature 11 | Will high temperatures be dangerous?,temperature 12 | Is it dangerously cold?,temperature 13 | When will the heat subside?,temperature 14 | Is it hot?,temperature 15 | Is it cold?,temperature 16 | How cold is it now?,temperature 17 | Will we have a cold day today?,temperature 18 | When will the cold subside?,temperature 19 | What highs are we expecting?,temperature 20 | What lows are we expecting?,temperature 21 | Is it warm?,temperature 22 | Is it chilly?,temperature 23 | What's the current temp in Celsius?,temperature 24 | What is the temperature in Fahrenheit?,temperature 25 | Is it windy?,conditions 26 | Will it rain today?,conditions 27 | What are the chances for rain?,conditions 28 | Will we get snow?,conditions 29 | Are we expecting sunny conditions?,conditions 30 | Is it overcast?,conditions 31 | Will it be cloudy?,conditions 32 | How much rain will fall today?,conditions 33 | How much snow are we expecting?,conditions 34 | Is it windy outside?,conditions 35 | How much snow do we expect?,conditions 36 | Is the forecast calling for snow today?,conditions 37 | Will we see some sun?,conditions 38 | When will the rain subside?,conditions 39 | Is it cloudy?,conditions 40 | Is it sunny now?,conditions 41 | Will it rain?,conditions 42 | Will we have much snow?,conditions 43 | Are the winds dangerous?,conditions 44 | What is the expected snowfall today?,conditions 45 | Will it be dry?,conditions 46 | Will it be breezy?,conditions 47 | Will it be humid?,conditions 48 | What is today's expected humidity?,conditions 49 | Will the blizzard hit us?,conditions 50 | Is it drizzling?,conditions -------------------------------------------------------------------------------- /v3/resources/weather_training_metadata.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "test_classifier", 3 | "language": "en" 4 | } 5 | -------------------------------------------------------------------------------- /v3/speechtotextv1/speech_to_text_v1_adapter.go: -------------------------------------------------------------------------------- 1 | package speechtotextv1 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | 7 | "github.com/IBM/go-sdk-core/v5/core" 8 | 9 | "net/http" 10 | "net/url" 11 | "strings" 12 | "time" 13 | ) 14 | 15 | const ( 16 | ONE_KB = 1024 17 | TEN_MILLISECONDS = 10 * time.Millisecond 18 | SUCCESS = 200 19 | RECOGNIZE_ENDPOINT = "/v1/recognize" 20 | ) 21 | 22 | type RecognizeUsingWebsocketOptions struct { 23 | RecognizeOptions 24 | 25 | // Action that is to be performed. Allowable values: start, stop 26 | Action *string `json:"action,omitempty"` 27 | 28 | // If true, the service returns interim results as a stream of JSON SpeechRecognitionResults objects. 29 | // If false, the service returns a single SpeechRecognitionResults object with final results only. 30 | InterimResults *bool `json:"interim_results,omitempty"` 31 | 32 | // If `true`, requests processing metrics about the service's transcription of the input audio. The service returns 33 | // processing metrics at the interval specified by the `processing_metrics_interval` parameter. It also returns 34 | // processing metrics for transcription events, for example, for final and interim results. By default, the service 35 | // returns no processing metrics. 36 | ProcessingMetrics *bool `json:"processing_metrics,omitempty"` 37 | 38 | // Specifies the interval in real wall-clock seconds at which the service is to return processing metrics. The 39 | // parameter is ignored unless the `processing_metrics` parameter is set to `true`. 40 | // 41 | // The parameter accepts a minimum value of 0.1 seconds. The level of precision is not restricted, so you can specify 42 | // values such as 0.25 and 0.125. 43 | // 44 | // The service does not impose a maximum value. If you want to receive processing metrics only for transcription events 45 | // instead of at periodic intervals, set the value to a large number. If the value is larger than the duration of the 46 | // audio, the service returns processing metrics only for transcription events. 47 | ProcessingMetricsInterval *float32 `json:"processing_metrics_interval,omitempty"` 48 | } 49 | 50 | // SetAction: Allows user to set the Action 51 | func (recognizeWSOptions *RecognizeUsingWebsocketOptions) SetAction(action string) *RecognizeUsingWebsocketOptions { 52 | recognizeWSOptions.Action = core.StringPtr(action) 53 | return recognizeWSOptions 54 | } 55 | 56 | // SetInterimResults: Allows user to set InterimResults 57 | func (recognizeWSOptions *RecognizeUsingWebsocketOptions) SetInterimResults(interimResults bool) *RecognizeUsingWebsocketOptions { 58 | recognizeWSOptions.InterimResults = core.BoolPtr(interimResults) 59 | return recognizeWSOptions 60 | } 61 | 62 | // SetProcessingMetrics : Allow user to set ProcessingMetrics 63 | func (recognizeWSOptions *RecognizeUsingWebsocketOptions) SetProcessingMetrics(processingMetrics bool) *RecognizeUsingWebsocketOptions { 64 | recognizeWSOptions.ProcessingMetrics = core.BoolPtr(processingMetrics) 65 | return recognizeWSOptions 66 | } 67 | 68 | // SetProcessingMetricsInterval : Allow user to set ProcessingMetricsInterval 69 | func (recognizeWSOptions *RecognizeUsingWebsocketOptions) SetProcessingMetricsInterval(processingMetricsInterval float32) *RecognizeUsingWebsocketOptions { 70 | recognizeWSOptions.ProcessingMetricsInterval = core.Float32Ptr(processingMetricsInterval) 71 | return recognizeWSOptions 72 | } 73 | 74 | // NewRecognizeUsingWebsocketOptions: Instantiate RecognizeOptions to enable websocket support 75 | func (speechToText *SpeechToTextV1) NewRecognizeUsingWebsocketOptions(audio io.ReadCloser, contentType string) *RecognizeUsingWebsocketOptions { 76 | recognizeOptions := speechToText.NewRecognizeOptions(audio) 77 | recognizeOptions.SetContentType(contentType) 78 | recognizeWSOptions := &RecognizeUsingWebsocketOptions{*recognizeOptions, nil, nil, nil, nil} 79 | return recognizeWSOptions 80 | } 81 | 82 | type WebsocketRecognitionResults struct { 83 | // Acknowledges that a start/end message was received, and indicates 84 | // the start/end of the audio data 85 | State string `json:"state,omitempty"` 86 | Error string `json:"error,omitempty"` 87 | 88 | SpeechRecognitionResults 89 | } 90 | 91 | type RecognizeCallbackWrapper interface { 92 | OnOpen() 93 | OnClose() 94 | OnData(*core.DetailedResponse) 95 | OnError(error) 96 | } 97 | 98 | // RecognizeUsingWebsocket: Recognize audio over websocket connection 99 | func (speechToText *SpeechToTextV1) RecognizeUsingWebsocket(recognizeWSOptions *RecognizeUsingWebsocketOptions, callback RecognizeCallbackWrapper) { 100 | if err := core.ValidateNotNil(recognizeWSOptions, "recognizeOptions cannot be nil"); err != nil { 101 | panic(err) 102 | } 103 | if err := core.ValidateStruct(recognizeWSOptions, "recognizeOptions"); err != nil { 104 | panic(err) 105 | } 106 | 107 | // Add authentication to the outbound request. 108 | if speechToText.Service.Options.Authenticator == nil { 109 | panic(fmt.Errorf("Authentication information was not properly configured.")) 110 | } 111 | 112 | // Create a dummy request for authenticate 113 | // Need to update design to let recognizeListener take in a request object 114 | req, _ := http.NewRequest("POST", speechToText.Service.Options.URL, nil) 115 | err := speechToText.Service.Options.Authenticator.Authenticate(req) 116 | if err != nil { 117 | panic(err) 118 | } 119 | headers := req.Header 120 | 121 | headers.Set("Content-Type", *recognizeWSOptions.ContentType) 122 | 123 | dialURL := strings.Replace(speechToText.Service.Options.URL, "https", "wss", 1) 124 | param := url.Values{} 125 | 126 | if recognizeWSOptions.Model != nil { 127 | param.Set("model", *recognizeWSOptions.Model) 128 | } 129 | if recognizeWSOptions.LanguageCustomizationID != nil { 130 | param.Set("language_customization_id", *recognizeWSOptions.LanguageCustomizationID) 131 | } 132 | if recognizeWSOptions.AcousticCustomizationID != nil { 133 | param.Set("acoustic_customization_id", *recognizeWSOptions.AcousticCustomizationID) 134 | } 135 | if recognizeWSOptions.BaseModelVersion != nil { 136 | param.Set("base_model_version", *recognizeWSOptions.BaseModelVersion) 137 | } 138 | 139 | speechToText.NewRecognizeListener(callback, recognizeWSOptions, dialURL, param, headers) 140 | } 141 | -------------------------------------------------------------------------------- /v3/speechtotextv1/speech_to_text_v1_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2018, 2022. 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 | package speechtotextv1_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestSpeechToTextV1(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "SpeechToTextV1 Suite") 29 | } 30 | -------------------------------------------------------------------------------- /v3/speechtotextv1/websocket_listener.go: -------------------------------------------------------------------------------- 1 | package speechtotextv1 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "io" 8 | "net/http" 9 | "net/url" 10 | "time" 11 | 12 | "github.com/IBM/go-sdk-core/v5/core" 13 | "github.com/gorilla/websocket" 14 | ) 15 | 16 | type RecognizeListener struct { 17 | IsClosed chan bool 18 | Callback RecognizeCallbackWrapper 19 | } 20 | 21 | /* 22 | OnOpen: Sends start message to server when connection created 23 | */ 24 | func (wsHandle RecognizeListener) OnOpen(recognizeOpt *RecognizeUsingWebsocketOptions, conn *websocket.Conn) { 25 | wsHandle.Callback.OnOpen() 26 | sendStartMessage(conn, recognizeOpt, &wsHandle) 27 | } 28 | 29 | /* 30 | OnClose: Callback when websocket connection is closed 31 | */ 32 | func (wsHandle RecognizeListener) OnClose() { 33 | <-wsHandle.IsClosed 34 | wsHandle.Callback.OnClose() 35 | } 36 | 37 | /* 38 | OnData: Callback when websocket connection receives data 39 | */ 40 | func (wsHandle RecognizeListener) OnData(conn *websocket.Conn, recognizeOptions *RecognizeUsingWebsocketOptions) { 41 | isListening := false 42 | for { 43 | var websocketResponse WebsocketRecognitionResults 44 | _, result, err := conn.ReadMessage() 45 | if err != nil { 46 | wsHandle.OnError(err) 47 | break 48 | } 49 | err = json.Unmarshal(result, &websocketResponse) 50 | if err != nil { 51 | wsHandle.OnError(err) 52 | break 53 | } 54 | 55 | if websocketResponse.State == "listening" { 56 | if !isListening { 57 | isListening = true 58 | continue 59 | } else { 60 | break 61 | } 62 | } 63 | 64 | if len(websocketResponse.Error) > 0 { 65 | wsHandle.OnError(errors.New(websocketResponse.Error)) 66 | break 67 | } 68 | 69 | detailResp := core.DetailedResponse{} 70 | detailResp.Result = result 71 | detailResp.StatusCode = SUCCESS 72 | wsHandle.Callback.OnData(&detailResp) 73 | } 74 | conn.Close() 75 | wsHandle.IsClosed <- true 76 | } 77 | 78 | /* 79 | OnError: Callback when error encountered 80 | */ 81 | func (wsHandle RecognizeListener) OnError(err error) { 82 | wsHandle.Callback.OnError(err) 83 | } 84 | 85 | /* 86 | sendStartMessage : Sends start message to server 87 | */ 88 | func sendStartMessage(conn *websocket.Conn, textParams *RecognizeUsingWebsocketOptions, recognizeListener *RecognizeListener) { 89 | action := "start" 90 | textParams.Action = &action 91 | startMsgBytes, _ := json.Marshal(textParams) 92 | err := conn.WriteMessage(websocket.TextMessage, startMsgBytes) 93 | if err != nil { 94 | recognizeListener.OnError(err) 95 | } 96 | } 97 | 98 | /* 99 | sendCloseMessage : Sends end message to server 100 | */ 101 | func sendCloseMessage(conn *websocket.Conn) { 102 | stop := "stop" 103 | closeMsgBytes, _ := json.Marshal(RecognizeUsingWebsocketOptions{Action: &stop}) 104 | _ = conn.WriteMessage(websocket.TextMessage, closeMsgBytes) 105 | } 106 | 107 | /* 108 | sendAudio : Sends audio data to the server 109 | */ 110 | func sendAudio(conn *websocket.Conn, recognizeOptions *RecognizeUsingWebsocketOptions, recognizeListener *RecognizeListener) { 111 | chunk := make([]byte, ONE_KB*2) 112 | for { 113 | bytesRead, err := (recognizeOptions.Audio).Read(chunk) 114 | if err != nil { 115 | if err == io.EOF { 116 | break 117 | } else { 118 | recognizeListener.OnError(err) 119 | } 120 | } 121 | err = conn.WriteMessage(websocket.BinaryMessage, chunk[:bytesRead]) 122 | if err != nil { 123 | recognizeListener.OnError(err) 124 | } 125 | time.Sleep(TEN_MILLISECONDS) 126 | } 127 | sendCloseMessage(conn) 128 | } 129 | 130 | /* 131 | NewRecognizeListener : Instantiates a listener instance to control the sending/receiving of audio/text 132 | */ 133 | func (speechToText *SpeechToTextV1) NewRecognizeListener(callback RecognizeCallbackWrapper, recognizeWSOptions *RecognizeUsingWebsocketOptions, dialURL string, param url.Values, headers http.Header) { 134 | recognizeListener := RecognizeListener{Callback: callback, IsClosed: make(chan bool, 1)} 135 | conn, _, err := websocket.DefaultDialer.Dial(fmt.Sprintf("%s%s?%s", dialURL, RECOGNIZE_ENDPOINT, param.Encode()), headers) 136 | if err != nil { 137 | recognizeListener.OnError(err) 138 | } 139 | recognizeListener.OnOpen(recognizeWSOptions, conn) 140 | go recognizeListener.OnData(conn, recognizeWSOptions) 141 | go sendAudio(conn, recognizeWSOptions, &recognizeListener) 142 | recognizeListener.OnClose() 143 | } 144 | -------------------------------------------------------------------------------- /v3/texttospeechv1/synthesize_listener.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2019, 2022. 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 | package texttospeechv1 18 | 19 | import ( 20 | "bytes" 21 | "encoding/json" 22 | "fmt" 23 | "io/ioutil" 24 | "net/http" 25 | 26 | "github.com/IBM/go-sdk-core/v5/core" 27 | "github.com/gorilla/websocket" 28 | ) 29 | 30 | const ( 31 | SUCCESS = 200 32 | ) 33 | 34 | type SynthesizeListener struct { 35 | IsClosed chan bool 36 | Callback SynthesizeCallbackWrapper 37 | } 38 | 39 | func decode(b []byte, target interface{}) { 40 | _ = json.NewDecoder(bytes.NewReader(b)).Decode(&target) 41 | } 42 | 43 | // OnError: Callback when error encountered 44 | func (listener SynthesizeListener) OnError(err error) { 45 | listener.Callback.OnError(err) 46 | } 47 | 48 | // SendText: Sends the text message 49 | // Note: The service handles one request per connection 50 | func (listener SynthesizeListener) SendText(conn *websocket.Conn, req *http.Request) { 51 | listener.OnOpen(conn) 52 | 53 | body, err := ioutil.ReadAll(req.Body) 54 | if err != nil { 55 | listener.OnError(err) 56 | } 57 | err = conn.WriteMessage(websocket.TextMessage, body) 58 | if err != nil { 59 | listener.OnError(err) 60 | } 61 | } 62 | 63 | // OnOpen: Sends start message to server when connection created 64 | func (listener SynthesizeListener) OnOpen(conn *websocket.Conn) { 65 | listener.Callback.OnOpen() 66 | } 67 | 68 | // OnClose: Callback when websocket connection is closed 69 | func (listener SynthesizeListener) OnClose() { 70 | <-listener.IsClosed 71 | listener.Callback.OnClose() 72 | } 73 | 74 | // OnData: Callback when websocket connection receives data 75 | func (listener SynthesizeListener) OnData(conn *websocket.Conn) { 76 | for { 77 | messageType, result, err := conn.ReadMessage() 78 | 79 | // The service will close the connection. We need to decipher 80 | // if the error is a normal close signal 81 | if err != nil { 82 | listener.IsClosed <- true 83 | 84 | if !websocket.IsCloseError(err, websocket.CloseNormalClosure) { 85 | listener.OnError(err) 86 | conn.Close() 87 | } 88 | break 89 | } 90 | 91 | if messageType == websocket.TextMessage { 92 | var r map[string]interface{} 93 | err = json.NewDecoder(bytes.NewReader(result)).Decode(&r) 94 | if err != nil { 95 | listener.OnError(fmt.Errorf(err.Error())) 96 | listener.IsClosed <- true 97 | break 98 | } 99 | if err, ok := r["error"]; ok { 100 | listener.OnError(fmt.Errorf(err.(string))) 101 | listener.IsClosed <- true 102 | break 103 | } 104 | 105 | if _, ok := r["binary_streams"]; ok { 106 | audioContentTypeWrapper := new(AudioContentTypeWrapper) 107 | decode(result, audioContentTypeWrapper) 108 | listener.Callback.OnContentType(audioContentTypeWrapper.BinaryStreams[0].ContentType) 109 | } else if _, ok := r["words"]; ok { 110 | timings := new(Timings) 111 | decode(result, timings) 112 | listener.Callback.OnTimingInformation(*timings) 113 | } else if _, ok := r["marks"]; ok { 114 | marks := new(Marks) 115 | decode(result, marks) 116 | listener.Callback.OnMarks(*marks) 117 | } 118 | } else if messageType == websocket.BinaryMessage { 119 | listener.Callback.OnAudioStream(result) 120 | } 121 | 122 | detailResponse := core.DetailedResponse{} 123 | detailResponse.Result = result 124 | detailResponse.StatusCode = SUCCESS 125 | listener.Callback.OnData(&detailResponse) 126 | } 127 | } 128 | 129 | func (textToSpeechV1 *TextToSpeechV1) NewSynthesizeListener(callback SynthesizeCallbackWrapper, req *http.Request) { 130 | synthesizeListener := SynthesizeListener{Callback: callback, IsClosed: make(chan bool, 1)} 131 | conn, _, err := websocket.DefaultDialer.Dial(req.URL.String(), req.Header) 132 | if err != nil { 133 | synthesizeListener.OnError(err) 134 | } 135 | 136 | go synthesizeListener.OnData(conn) 137 | go synthesizeListener.SendText(conn, req) 138 | synthesizeListener.OnClose() 139 | } 140 | -------------------------------------------------------------------------------- /v3/texttospeechv1/text_to_speech_v1_adapter.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2019, 2022. 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 | package texttospeechv1 18 | 19 | import ( 20 | "fmt" 21 | "strings" 22 | 23 | "github.com/IBM/go-sdk-core/v5/core" 24 | common "github.com/watson-developer-cloud/go-sdk/v3/common" 25 | ) 26 | 27 | // Timings : An array of words and their start and end times in seconds from the beginning of the synthesized audio. 28 | type Timings struct { 29 | Words [][]interface{} `json:"words,omitempty"` 30 | } 31 | 32 | // Timings : An array of mark times 33 | type Marks struct { 34 | Marks [][]interface{} `json:"marks"` 35 | } 36 | 37 | // AudioContentTypeWrapper : The service sends this message to confirm the audio format 38 | type AudioContentTypeWrapper struct { 39 | BinaryStreams []struct { 40 | ContentType string `json:"content_type"` 41 | } `json:"binary_streams"` 42 | } 43 | 44 | // SynthesizeCallbackWrapper : callback for synthesize using websocket 45 | type SynthesizeCallbackWrapper interface { 46 | OnOpen() 47 | OnError(error) 48 | OnContentType(string) 49 | OnTimingInformation(Timings) 50 | OnMarks(Marks) 51 | OnAudioStream([]byte) 52 | OnData(*core.DetailedResponse) 53 | OnClose() 54 | } 55 | 56 | // SynthesizeOptions : The SynthesizeUsingWebsocket options 57 | type SynthesizeUsingWebsocketOptions struct { 58 | SynthesizeOptions 59 | 60 | // Callback to listen to events 61 | Callback SynthesizeCallbackWrapper `json:"callback" validate:"required"` 62 | 63 | // Timings specifies that the service is to return word timing information for all strings of the 64 | // input text. The service returns the start and end time of each string of the input. Specify words as the lone element 65 | // of the array to request word timings. Specify an empty array or omit the parameter to receive no word timings. For 66 | // more information, see [Obtaining word timings](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-timing#timing). 67 | // Not supported for Japanese input text. 68 | Timings []string `json:"action,omitempty"` 69 | } 70 | 71 | // NewSynthesizeUsingWebsocketOptions: Instantiate SynthesizeOptions to enable websocket support 72 | func (textToSpeech *TextToSpeechV1) NewSynthesizeUsingWebsocketOptions(text string, callback SynthesizeCallbackWrapper) *SynthesizeUsingWebsocketOptions { 73 | synthesizeOptions := textToSpeech.NewSynthesizeOptions(text) 74 | synthesizeWSOptions := &SynthesizeUsingWebsocketOptions{*synthesizeOptions, callback, nil} 75 | return synthesizeWSOptions 76 | } 77 | 78 | // SetCallback: Allows user to set the Callback 79 | func (options *SynthesizeUsingWebsocketOptions) SetCallback(callback SynthesizeCallbackWrapper) *SynthesizeUsingWebsocketOptions { 80 | options.Callback = callback 81 | return options 82 | } 83 | 84 | // SetTimings: Allows user to set the Timings 85 | func (options *SynthesizeUsingWebsocketOptions) SetTimings(timings []string) *SynthesizeUsingWebsocketOptions { 86 | options.Timings = timings 87 | return options 88 | } 89 | 90 | // SynthesizeUsingWebsocket: Synthesize text over websocket connection 91 | func (textToSpeech *TextToSpeechV1) SynthesizeUsingWebsocket(synthesizeOptions *SynthesizeUsingWebsocketOptions) error { 92 | if err := core.ValidateNotNil(synthesizeOptions, "synthesizeOptions cannot be nil"); err != nil { 93 | return err 94 | } 95 | if err := core.ValidateStruct(synthesizeOptions, "synthesizeOptions"); err != nil { 96 | return err 97 | } 98 | 99 | // Add authentication to the outbound request. 100 | if textToSpeech.Service.Options.Authenticator == nil { 101 | return fmt.Errorf("Authentication information was not properly configured.") 102 | } 103 | 104 | pathSegments := []string{"v1/synthesize"} 105 | pathParameters := []string{} 106 | 107 | builder := core.NewRequestBuilder(core.POST) 108 | dialURL := strings.Replace(textToSpeech.Service.Options.URL, "https", "wss", 1) 109 | _, err := builder.ConstructHTTPURL(dialURL, pathSegments, pathParameters) 110 | if err != nil { 111 | return err 112 | } 113 | 114 | for headerName, headerValue := range synthesizeOptions.Headers { 115 | builder.AddHeader(headerName, headerValue) 116 | } 117 | 118 | sdkHeaders := common.GetSdkHeaders("text_to_speech", "V1", "Synthesize") 119 | for headerName, headerValue := range sdkHeaders { 120 | builder.AddHeader(headerName, headerValue) 121 | } 122 | 123 | builder.AddHeader("Content-Type", "application/json") 124 | 125 | if synthesizeOptions.Voice != nil { 126 | builder.AddQuery("voice", fmt.Sprint(*synthesizeOptions.Voice)) 127 | } 128 | if synthesizeOptions.CustomizationID != nil { 129 | builder.AddQuery("customization_id", fmt.Sprint(*synthesizeOptions.CustomizationID)) 130 | } 131 | 132 | body := make(map[string]interface{}) 133 | if synthesizeOptions.Text != nil { 134 | body["text"] = synthesizeOptions.Text 135 | } 136 | if synthesizeOptions.Accept != nil { 137 | body["accept"] = synthesizeOptions.Accept 138 | } 139 | if synthesizeOptions.Timings != nil { 140 | body["timings"] = synthesizeOptions.Timings 141 | } 142 | 143 | if _, err := builder.SetBodyContentJSON(body); err != nil { 144 | return err 145 | } 146 | 147 | request, err := builder.Build() 148 | if err != nil { 149 | return err 150 | } 151 | 152 | // Add the authentication header 153 | err = textToSpeech.Service.Options.Authenticator.Authenticate(request) 154 | if err != nil { 155 | return err 156 | } 157 | 158 | textToSpeech.NewSynthesizeListener(synthesizeOptions.Callback, request) 159 | return nil 160 | } 161 | -------------------------------------------------------------------------------- /v3/texttospeechv1/text_to_speech_v1_suite_test.go: -------------------------------------------------------------------------------- 1 | /** 2 | * (C) Copyright IBM Corp. 2018, 2022. 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 | package texttospeechv1_test 18 | 19 | import ( 20 | "testing" 21 | 22 | . "github.com/onsi/ginkgo" 23 | . "github.com/onsi/gomega" 24 | ) 25 | 26 | func TestTextToSpeechV1(t *testing.T) { 27 | RegisterFailHandler(Fail) 28 | RunSpecs(t, "TextToSpeechV1 Suite") 29 | } 30 | --------------------------------------------------------------------------------