Skip to content

Commit

Permalink
fix(python/sdk): Fix README for sentiment analysis example (#2472)
Browse files Browse the repository at this point in the history
GitOrigin-RevId: c2d97c625499679492c8d3c9083a39bc74211c83
  • Loading branch information
ploeber authored and jhazenaai committed Nov 20, 2023
1 parent d12a626 commit 1abf5d9
Show file tree
Hide file tree
Showing 11 changed files with 178 additions and 486 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,7 @@ for sentiment_result in transcript.sentiment_analysis:
print(sentiment_result.text)
print(sentiment_result.sentiment) # POSITIVE, NEUTRAL, or NEGATIVE
print(sentiment_result.confidence)
print(f"Timestamp: {sentiment_result.timestamp.start} - {sentiment_result.timestamp.end}")
print(f"Timestamp: {sentiment_result.start} - {sentiment_result.end}")
```

If `speaker_labels` is also enabled, then each sentiment analysis result will also include a `speaker` field.
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

setup(
name="assemblyai",
version="0.19.0",
version="0.18.0",
description="AssemblyAI Python SDK",
author="AssemblyAI",
author_email="[email protected]",
Expand Down
63 changes: 4 additions & 59 deletions tests/unit/test_auto_chapters.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
import json
from typing import Any, Dict, Tuple

import factory
import httpx
import pytest
from pytest_httpx import HTTPXMock

import tests.unit.unit_test_utils as unit_test_utils
import assemblyai as aai
from assemblyai.api import ENDPOINT_TRANSCRIPT
from tests.unit import factories

aai.settings.api_key = "test"
Expand All @@ -17,65 +13,14 @@ class AutoChaptersResponseFactory(factories.TranscriptCompletedResponseFactory):
chapters = factory.List([factory.SubFactory(factories.ChapterFactory)])


def __submit_mock_request(
httpx_mock: HTTPXMock,
mock_response: Dict[str, Any],
config: aai.TranscriptionConfig,
) -> Tuple[Dict[str, Any], aai.Transcript]:
"""
Helper function to abstract mock transcriber calls with given `TranscriptionConfig`,
and perform some common assertions.
"""

mock_transcript_id = mock_response.get("id", "mock_id")

# Mock initial submission response (transcript is processing)
mock_processing_response = factories.generate_dict_factory(
factories.TranscriptProcessingResponseFactory
)()

httpx_mock.add_response(
url=f"{aai.settings.base_url}{ENDPOINT_TRANSCRIPT}",
status_code=httpx.codes.OK,
method="POST",
json={
**mock_processing_response,
"id": mock_transcript_id, # inject ID from main mock response
},
)

# Mock polling-for-completeness response, with completed transcript
httpx_mock.add_response(
url=f"{aai.settings.base_url}{ENDPOINT_TRANSCRIPT}/{mock_transcript_id}",
status_code=httpx.codes.OK,
method="GET",
json=mock_response,
)

# == Make API request via SDK ==
transcript = aai.Transcriber().transcribe(
data="https://example.org/audio.wav",
config=config,
)

# Check that submission and polling requests were made
assert len(httpx_mock.get_requests()) == 2

# Extract body of initial submission request
request = httpx_mock.get_requests()[0]
request_body = json.loads(request.content.decode())

return request_body, transcript


def test_auto_chapters_fails_without_punctuation(httpx_mock: HTTPXMock):
"""
Tests whether the SDK raises an error before making a request
if `auto_chapters` is enabled and `punctuation` is disabled
"""

with pytest.raises(ValueError) as error:
__submit_mock_request(
unit_test_utils.submit_mock_transcription_request(
httpx_mock,
mock_response={}, # response doesn't matter, since it shouldn't occur
config=aai.TranscriptionConfig(
Expand All @@ -98,7 +43,7 @@ def test_auto_chapters_disabled_by_default(httpx_mock: HTTPXMock):
Tests that excluding `auto_chapters` from the `TranscriptionConfig` will
result in the default behavior of it being excluded from the request body
"""
request_body, transcript = __submit_mock_request(
request_body, transcript = unit_test_utils.submit_mock_transcription_request(
httpx_mock,
mock_response=factories.generate_dict_factory(
factories.TranscriptCompletedResponseFactory
Expand All @@ -116,7 +61,7 @@ def test_auto_chapters_enabled(httpx_mock: HTTPXMock):
response is properly parsed into a `Transcript` object
"""
mock_response = factories.generate_dict_factory(AutoChaptersResponseFactory)()
request_body, transcript = __submit_mock_request(
request_body, transcript = unit_test_utils.submit_mock_transcription_request(
httpx_mock,
mock_response=mock_response,
config=aai.TranscriptionConfig(auto_chapters=True),
Expand Down
61 changes: 3 additions & 58 deletions tests/unit/test_auto_highlights.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
import json
from typing import Any, Dict, Tuple

import factory
import httpx
from pytest_httpx import HTTPXMock

import tests.unit.unit_test_utils as unit_test_utils
import assemblyai as aai
from assemblyai.api import ENDPOINT_TRANSCRIPT
from tests.unit import factories

aai.settings.api_key = "test"
Expand Down Expand Up @@ -36,63 +32,12 @@ class AutohighlightTranscriptResponseFactory(
auto_highlights_result = factory.SubFactory(AutohighlightResponseFactory)


def __submit_mock_request(
httpx_mock: HTTPXMock,
mock_response: Dict[str, Any],
config: aai.TranscriptionConfig,
) -> Tuple[Dict[str, Any], aai.Transcript]:
"""
Helper function to abstract mock transcriber calls with given `TranscriptionConfig`,
and perform some common assertions.
"""

mock_transcript_id = mock_response.get("id", "mock_id")

# Mock initial submission response (transcript is processing)
mock_processing_response = factories.generate_dict_factory(
factories.TranscriptProcessingResponseFactory
)()

httpx_mock.add_response(
url=f"{aai.settings.base_url}{ENDPOINT_TRANSCRIPT}",
status_code=httpx.codes.OK,
method="POST",
json={
**mock_processing_response,
"id": mock_transcript_id, # inject ID from main mock response
},
)

# Mock polling-for-completeness response, with completed transcript
httpx_mock.add_response(
url=f"{aai.settings.base_url}{ENDPOINT_TRANSCRIPT}/{mock_transcript_id}",
status_code=httpx.codes.OK,
method="GET",
json=mock_response,
)

# == Make API request via SDK ==
transcript = aai.Transcriber().transcribe(
data="https://example.org/audio.wav",
config=config,
)

# Check that submission and polling requests were made
assert len(httpx_mock.get_requests()) == 2

# Extract body of initial submission request
request = httpx_mock.get_requests()[0]
request_body = json.loads(request.content.decode())

return request_body, transcript


def test_auto_highlights_disabled_by_default(httpx_mock: HTTPXMock):
"""
Tests that excluding `auto_highlights` from the `TranscriptionConfig` will
result in the default behavior of it being excluded from the request body
"""
request_body, transcript = __submit_mock_request(
request_body, transcript = unit_test_utils.submit_mock_transcription_request(
httpx_mock,
mock_response=factories.generate_dict_factory(
factories.TranscriptCompletedResponseFactory
Expand All @@ -112,7 +57,7 @@ def test_auto_highlights_enabled(httpx_mock: HTTPXMock):
mock_response = factories.generate_dict_factory(
AutohighlightTranscriptResponseFactory
)()
request_body, transcript = __submit_mock_request(
request_body, transcript = unit_test_utils.submit_mock_transcription_request(
httpx_mock,
mock_response=mock_response,
config=aai.TranscriptionConfig(auto_highlights=True),
Expand Down
64 changes: 5 additions & 59 deletions tests/unit/test_content_safety.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import json
import random
from typing import Any, Dict, Tuple

import factory
import httpx
import pytest
from pytest_httpx import HTTPXMock

import tests.unit.unit_test_utils as unit_test_utils
import assemblyai as aai
from assemblyai.api import ENDPOINT_TRANSCRIPT
from tests.unit import factories

aai.settings.api_key = "test"
Expand Down Expand Up @@ -69,63 +66,12 @@ class ContentSafetyTranscriptResponseFactory(
content_safety_labels = factory.SubFactory(ContentSafetyResponseFactory)


def __submit_mock_request(
httpx_mock: HTTPXMock,
mock_response: Dict[str, Any],
config: aai.TranscriptionConfig,
) -> Tuple[Dict[str, Any], aai.Transcript]:
"""
Helper function to abstract mock transcriber calls with given `TranscriptionConfig`,
and perform some common assertions.
"""

mock_transcript_id = mock_response.get("id", "mock_id")

# Mock initial submission response (transcript is processing)
mock_processing_response = factories.generate_dict_factory(
factories.TranscriptProcessingResponseFactory
)()

httpx_mock.add_response(
url=f"{aai.settings.base_url}{ENDPOINT_TRANSCRIPT}",
status_code=httpx.codes.OK,
method="POST",
json={
**mock_processing_response,
"id": mock_transcript_id, # inject ID from main mock response
},
)

# Mock polling-for-completeness response, with completed transcript
httpx_mock.add_response(
url=f"{aai.settings.base_url}{ENDPOINT_TRANSCRIPT}/{mock_transcript_id}",
status_code=httpx.codes.OK,
method="GET",
json=mock_response,
)

# == Make API request via SDK ==
transcript = aai.Transcriber().transcribe(
data="https://example.org/audio.wav",
config=config,
)

# Check that submission and polling requests were made
assert len(httpx_mock.get_requests()) == 2

# Extract body of initial submission request
request = httpx_mock.get_requests()[0]
request_body = json.loads(request.content.decode())

return request_body, transcript


def test_content_safety_disabled_by_default(httpx_mock: HTTPXMock):
"""
Tests that excluding `content_safety` from the `TranscriptionConfig` will
result in the default behavior of it being excluded from the request body
"""
request_body, transcript = __submit_mock_request(
request_body, transcript = unit_test_utils.submit_mock_transcription_request(
httpx_mock,
mock_response=factories.generate_dict_factory(
factories.TranscriptCompletedResponseFactory
Expand All @@ -145,7 +91,7 @@ def test_content_safety_enabled(httpx_mock: HTTPXMock):
mock_response = factories.generate_dict_factory(
ContentSafetyTranscriptResponseFactory
)()
request_body, transcript = __submit_mock_request(
request_body, transcript = unit_test_utils.submit_mock_transcription_request(
httpx_mock,
mock_response=mock_response,
config=aai.TranscriptionConfig(content_safety=True),
Expand Down Expand Up @@ -248,7 +194,7 @@ def test_content_safety_with_confidence_threshold(httpx_mock: HTTPXMock):
and will be included in the request body
"""
confidence = 40
request, _ = __submit_mock_request(
request, _ = unit_test_utils.submit_mock_transcription_request(
httpx_mock,
mock_response={}, # Response doesn't matter here; we're just testing the request body
config=aai.TranscriptionConfig(
Expand All @@ -269,7 +215,7 @@ def test_content_safety_with_invalid_confidence_threshold(
an exception to be raised before the request is sent
"""
with pytest.raises(ValueError) as error:
__submit_mock_request(
unit_test_utils.submit_mock_transcription_request(
httpx_mock,
mock_response={}, # We don't expect to produce a response
config=aai.TranscriptionConfig(
Expand Down
Loading

0 comments on commit 1abf5d9

Please sign in to comment.