appsocom 0.7.0__tar.gz → 0.9.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: appsocom
3
- Version: 0.7.0
3
+ Version: 0.9.0
4
4
  Summary: Python server SDK for Appsocom Live video calls: join tokens, rooms, moderation and webhook verification
5
5
  Author: Appsotech Limited
6
6
  License-Expression: MIT
@@ -86,7 +86,33 @@ def assistant_tools_route():
86
86
 
87
87
  `handle()` refuses bad or stale signatures with 401, answers `{"result": ...}` (`"done"` when a tool returns `None`) or `{"error": ...}`, and hides any exception other than `AssistantToolError` as "The tool failed." (pass `on_error=` to see it). Also: `get_assistant_config`, `delete_assistant_conversation(user_id, conversation_id)`, `verify_assistant_tool_call`.
88
88
 
89
- All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `set_assistant_config`, `get_assistant_config`, `create_assistant_token`, `delete_assistant_conversation`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`, `assistant_tools`, `verify_assistant_tool_call`.
89
+ ## AI Tasks, Speech and Videos
90
+
91
+ ```python
92
+ # AI Tasks: one Claude call from your server (a ready-made task, or your own prompt)
93
+ marked = kit.ai_task("mark", {"question": q, "answer": a, "rubric": rubric, "maxScore": 10}, user=student_id)
94
+ marked["json"]["score"], marked["usage"]["credits"]
95
+ draft = kit.ai_complete("Write a two-line welcome for new parents.", tier="standard")
96
+ data = kit.ai_complete("List the dates in this letter: ...", json={"type": "object", "properties": {"dates": {"type": "array"}}})
97
+ with kit.ai_stream("Tell a short story.") as story:
98
+ for piece in story:
99
+ print(piece, end="")
100
+ story.usage # model, tokens, cost, credits
101
+
102
+ # Speech
103
+ audio = kit.text_to_speech("Well done!", language="en") # mp3 bytes
104
+ link = kit.text_to_speech_url("Ẹ káàárọ̀", language="yo", expires_in=3600) # link["url"] plays without your key
105
+ heard = kit.speech_to_text(recording_bytes, content_type="audio/webm", language="ha") # heard["text"]
106
+
107
+ # Videos: an upload link for a browser, or send a file from your server
108
+ upload = kit.create_video_upload(3600, name="Lesson 1", upload_length=size)
109
+ kit.upload_video_file(upload, open("lesson.mp4", "rb"))
110
+ links = kit.video_playback(upload["videoId"]) # links["hls"], links["iframe"], links["thumbnail"]
111
+ ```
112
+
113
+ `ai_complete` and `ai_task` return the API's answer as a dict (`text`, `json`, `usage`); a call the kit refuses (daily limit, no credit) raises `SfuKitError` with the status, and `ai_stream` raises it at once. Settings and reports: `get_ai_settings`, `set_ai_settings`, `get_ai_usage(days)`, `get_ai_audit(day, user)`, `get_speech_usage`, `set_speech_daily_budget`, `get_video_usage`. Videos: `copy_video`, `list_videos`, `get_video`, `update_video`, `delete_video`. See [AI Tasks](https://docs.appsocom.dev/ai-tasks/), [Speech](https://docs.appsocom.dev/speech/) and [Videos](https://docs.appsocom.dev/videos/).
114
+
115
+ All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `set_assistant_config`, `get_assistant_config`, `create_assistant_token`, `delete_assistant_conversation`, `ai_complete`, `ai_task`, `ai_stream`, `get_ai_settings`, `set_ai_settings`, `get_ai_usage`, `get_ai_audit`, `text_to_speech`, `text_to_speech_url`, `speech_to_text`, `get_speech_usage`, `set_speech_daily_budget`, `create_video_upload`, `upload_video_file`, `copy_video`, `list_videos`, `get_video`, `update_video`, `delete_video`, `video_playback`, `get_video_usage`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`, `assistant_tools`, `verify_assistant_tool_call`.
90
116
 
91
117
  Self-hosting your own deployment instead? Point `url` at it and pass its admin key; the optional `jwt_secret` signs tokens locally without an HTTP call.
92
118
 
@@ -67,7 +67,33 @@ def assistant_tools_route():
67
67
 
68
68
  `handle()` refuses bad or stale signatures with 401, answers `{"result": ...}` (`"done"` when a tool returns `None`) or `{"error": ...}`, and hides any exception other than `AssistantToolError` as "The tool failed." (pass `on_error=` to see it). Also: `get_assistant_config`, `delete_assistant_conversation(user_id, conversation_id)`, `verify_assistant_tool_call`.
69
69
 
70
- All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `set_assistant_config`, `get_assistant_config`, `create_assistant_token`, `delete_assistant_conversation`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`, `assistant_tools`, `verify_assistant_tool_call`.
70
+ ## AI Tasks, Speech and Videos
71
+
72
+ ```python
73
+ # AI Tasks: one Claude call from your server (a ready-made task, or your own prompt)
74
+ marked = kit.ai_task("mark", {"question": q, "answer": a, "rubric": rubric, "maxScore": 10}, user=student_id)
75
+ marked["json"]["score"], marked["usage"]["credits"]
76
+ draft = kit.ai_complete("Write a two-line welcome for new parents.", tier="standard")
77
+ data = kit.ai_complete("List the dates in this letter: ...", json={"type": "object", "properties": {"dates": {"type": "array"}}})
78
+ with kit.ai_stream("Tell a short story.") as story:
79
+ for piece in story:
80
+ print(piece, end="")
81
+ story.usage # model, tokens, cost, credits
82
+
83
+ # Speech
84
+ audio = kit.text_to_speech("Well done!", language="en") # mp3 bytes
85
+ link = kit.text_to_speech_url("Ẹ káàárọ̀", language="yo", expires_in=3600) # link["url"] plays without your key
86
+ heard = kit.speech_to_text(recording_bytes, content_type="audio/webm", language="ha") # heard["text"]
87
+
88
+ # Videos: an upload link for a browser, or send a file from your server
89
+ upload = kit.create_video_upload(3600, name="Lesson 1", upload_length=size)
90
+ kit.upload_video_file(upload, open("lesson.mp4", "rb"))
91
+ links = kit.video_playback(upload["videoId"]) # links["hls"], links["iframe"], links["thumbnail"]
92
+ ```
93
+
94
+ `ai_complete` and `ai_task` return the API's answer as a dict (`text`, `json`, `usage`); a call the kit refuses (daily limit, no credit) raises `SfuKitError` with the status, and `ai_stream` raises it at once. Settings and reports: `get_ai_settings`, `set_ai_settings`, `get_ai_usage(days)`, `get_ai_audit(day, user)`, `get_speech_usage`, `set_speech_daily_budget`, `get_video_usage`. Videos: `copy_video`, `list_videos`, `get_video`, `update_video`, `delete_video`. See [AI Tasks](https://docs.appsocom.dev/ai-tasks/), [Speech](https://docs.appsocom.dev/speech/) and [Videos](https://docs.appsocom.dev/videos/).
95
+
96
+ All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `set_assistant_config`, `get_assistant_config`, `create_assistant_token`, `delete_assistant_conversation`, `ai_complete`, `ai_task`, `ai_stream`, `get_ai_settings`, `set_ai_settings`, `get_ai_usage`, `get_ai_audit`, `text_to_speech`, `text_to_speech_url`, `speech_to_text`, `get_speech_usage`, `set_speech_daily_budget`, `create_video_upload`, `upload_video_file`, `copy_video`, `list_videos`, `get_video`, `update_video`, `delete_video`, `video_playback`, `get_video_usage`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`, `assistant_tools`, `verify_assistant_tool_call`.
71
97
 
72
98
  Self-hosting your own deployment instead? Point `url` at it and pass its admin key; the optional `jwt_secret` signs tokens locally without an HTTP call.
73
99
 
@@ -21,6 +21,7 @@ from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
21
21
  __all__ = [
22
22
  "SfuKit",
23
23
  "SfuKitError",
24
+ "AiStream",
24
25
  "sign_token",
25
26
  "verify_webhook",
26
27
  "sign_webhook",
@@ -30,7 +31,7 @@ __all__ = [
30
31
  "assistant_tools",
31
32
  "verify_assistant_tool_call",
32
33
  ]
33
- __version__ = "0.7.0"
34
+ __version__ = "0.9.0"
34
35
 
35
36
  SIGNATURE_HEADER = "X-SfuKit-Signature"
36
37
  _ID = re.compile(r"^[A-Za-z0-9._:@-]{1,128}$")
@@ -67,6 +68,76 @@ def _json(value: Any) -> str:
67
68
  return json.dumps(value, separators=(",", ":"), ensure_ascii=False)
68
69
 
69
70
 
71
+ def _http_error(what: str, e: urllib.error.HTTPError) -> "SfuKitError":
72
+ text = e.read().decode("utf-8", "replace")
73
+ try:
74
+ parsed: Any = json.loads(text)
75
+ except ValueError:
76
+ parsed = text
77
+ msg = parsed.get("error", text) if isinstance(parsed, dict) else text
78
+ return SfuKitError(e.code, f"sfukit {what}: {e.code} {msg}", parsed)
79
+
80
+
81
+ def _body(options: Dict[str, Any], names: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
82
+ """Keyword options as a request body: names mapped to the API's camelCase, None left out."""
83
+ return {(names or {}).get(k, k): v for k, v in options.items() if v is not None}
84
+
85
+
86
+ # snake_case options of the AI Tasks, Speech and Videos helpers, as the API spells them.
87
+ _NAMES = {
88
+ "max_tokens": "maxTokens",
89
+ "expires_in": "expiresIn",
90
+ "max_duration_seconds": "maxDurationSeconds",
91
+ "upload_length": "uploadLength",
92
+ "expires_in_seconds": "expiresInSeconds",
93
+ }
94
+
95
+
96
+ class AiStream:
97
+ """One streamed AI Tasks answer (from `SfuKit.ai_stream`).
98
+
99
+ Iterate it for the text as it is written; `usage` holds the call's usage (model, tokens,
100
+ cost, credits) once the stream has ended. Use it in a `with` block, or call `close()`, if
101
+ you stop reading early.
102
+ """
103
+
104
+ def __init__(self, response: Any):
105
+ self._res = response
106
+ self.usage: Optional[Dict[str, Any]] = None
107
+
108
+ def __iter__(self):
109
+ event = data = None
110
+ try:
111
+ for raw in self._res:
112
+ line = raw.decode("utf-8").rstrip("\r\n")
113
+ if line == "":
114
+ if event is not None and data is not None:
115
+ d = json.loads(data)
116
+ if event == "text" and d.get("text"):
117
+ yield d["text"]
118
+ elif event == "error":
119
+ raise SfuKitError(502, f"sfukit POST /ai/complete: {d.get('error') or 'stream failed'}", d)
120
+ elif event == "done":
121
+ self.usage = d.get("usage")
122
+ return
123
+ event = data = None
124
+ elif line.startswith("event: "):
125
+ event = line[7:]
126
+ elif line.startswith("data: ") and data is None:
127
+ data = line[6:]
128
+ finally:
129
+ self.close()
130
+
131
+ def close(self) -> None:
132
+ self._res.close()
133
+
134
+ def __enter__(self) -> "AiStream":
135
+ return self
136
+
137
+ def __exit__(self, *exc: Any) -> None:
138
+ self.close()
139
+
140
+
70
141
  class SfuKit:
71
142
  """Admin client for one sfukit deployment.
72
143
 
@@ -488,7 +559,8 @@ class SfuKit:
488
559
  options: name, role, conversation_id, tools (names), paths, tier, retention_days,
489
560
  monthly_messages (this person's messages per month), metadata (dict of strings, passed back with every tool call),
490
561
  context (what your app knows about this person that the assistant should always have, at most 3,000 characters),
491
- report_usage (add tier, units, cost and tokens to the done event; for a backend that relays answers), ttl_seconds (default 3600, max 43200).
562
+ report_usage (add tier, units, cost and tokens to the done event; for a backend that relays answers),
563
+ knowledge (a knowledge base collection to answer from, for an app that keeps each customer's knowledge apart), ttl_seconds (default 3600, max 43200).
492
564
  """
493
565
  body: Dict[str, Any] = {"userId": user_id}
494
566
  names = {"conversation_id": "conversationId", "retention_days": "retentionDays", "monthly_messages": "monthlyMessages", "report_usage": "reportUsage", "ttl_seconds": "ttlSeconds"}
@@ -501,14 +573,284 @@ class SfuKit:
501
573
  """Forget one person's conversation (its memory and transcript)."""
502
574
  self.request("DELETE", f"/assistant/conversations/{_id(user_id)}/{_id(conversation_id)}")
503
575
 
576
+ # ---------- AI Tasks (/ai/*; called AI Text in code) ----------
577
+
578
+ #: Seconds AI Tasks calls may take (they write whole answers); longer than `timeout`.
579
+ AI_TIMEOUT = 300.0
580
+
581
+ def ai_complete(self, prompt: Optional[str] = None, **options: Any) -> Dict[str, Any]:
582
+ """One Claude call with your own prompt: `prompt`, or `system` and `messages`.
583
+
584
+ options: system, messages ([{"role": "user" | "assistant", "content": …}]), json (True for any
585
+ JSON object, or a JSON Schema dict for an answer that keeps to it), tier ("standard", "smart",
586
+ "best"), max_tokens (default 4000, at most 32000), user (your id for the person this is for:
587
+ per-person monthly allowance, audit), label (your own label, shown in usage and audit).
588
+ Returns {"task", "tier", "text", "json"?, "error"?, "stopReason", "usage": {…, "credits"}}.
589
+ """
590
+ body = {"prompt": prompt, **options}
591
+ return self.request("POST", "/ai/complete", {**_body(body, _NAMES), "stream": False}, timeout=max(self.timeout, self.AI_TIMEOUT))
592
+
593
+ def ai_task(self, task: str, input: Dict[str, Any], **options: Any) -> Dict[str, Any]:
594
+ """A ready-made task: "write", "mark", "questions", "summary", "moderate" or "extract"
595
+ (see the AI Tasks docs for each input). options: tier, max_tokens, user, label."""
596
+ return self.request("POST", "/ai/complete", {**_body(options, _NAMES), "task": task, "input": input}, timeout=max(self.timeout, self.AI_TIMEOUT))
597
+
598
+ def ai_stream(self, prompt: Optional[str] = None, **options: Any) -> AiStream:
599
+ """Your own prompt, streamed: iterate the result for the text as it is written, then read
600
+ its `usage`. Takes the options of ai_complete except json. Raises SfuKitError at once when
601
+ the kit refuses the call (for example 429 at the daily limit)."""
602
+ body = _body({"prompt": prompt, **options}, _NAMES)
603
+ req = urllib.request.Request(
604
+ self.url + "/ai/complete",
605
+ data=_json({**body, "stream": True}).encode("utf-8"),
606
+ headers={**self._headers(), "Content-Type": "application/json"},
607
+ method="POST",
608
+ )
609
+ try:
610
+ return AiStream(urllib.request.urlopen(req, timeout=max(self.timeout, self.AI_TIMEOUT)))
611
+ except urllib.error.HTTPError as e:
612
+ raise _http_error("POST /ai/complete", e) from None
613
+
614
+ def get_ai_settings(self) -> Dict[str, Any]:
615
+ """{"settings": {…}, "dailyCapUsd": n}."""
616
+ return self.request("GET", "/ai/settings")
617
+
618
+ def set_ai_settings(self, settings: Dict[str, Any]) -> Dict[str, Any]:
619
+ """Replace AI Tasks' settings (the API's own keys): dailyBudgetUsd, userMonthlyUsd, tiers,
620
+ defaultTier, audit."""
621
+ return self.request("PUT", "/ai/settings", settings)
622
+
623
+ def get_ai_usage(self, days: int = 7) -> Dict[str, Any]:
624
+ """Spending (today against the cap, per day) and calls by task and model over `days` (1-90)."""
625
+ return self.request("GET", f"/ai/usage?days={int(days)}")
626
+
627
+ def get_ai_audit(self, day: Optional[str] = None, user: Optional[str] = None) -> Dict[str, Any]:
628
+ """One UTC day's calls (never their text), optionally one person's: {"day", "events", "truncated"}."""
629
+ q = {k: v for k, v in (("day", day), ("user", user)) if v}
630
+ return self.request("GET", "/ai/audit" + (f"?{urllib.parse.urlencode(q)}" if q else ""))
631
+
632
+ # ---------- Speech (/speech/tts, /speech/stt) ----------
633
+
634
+ def text_to_speech(self, text: str, **options: Any) -> bytes:
635
+ """Speak `text` (up to 5,000 characters): the audio file's bytes (mp3 unless format="wav").
636
+ Repeats of the same text come from the cache, free.
637
+
638
+ options: language (default "en"; Yoruba "yo", Hausa "ha" and Igbo "ig" use Spitch or ElevenLabs),
639
+ voice, provider ("cartesia", "elevenlabs", "spitch", "openai", "deepgram"), format ("mp3" or "wav"),
640
+ speed (0.5 to 2), model, cache (False: always made fresh, always billed).
641
+ """
642
+ return self.request("POST", "/speech/tts", {**_body({"text": text, **options}, _NAMES), "response": "audio"}, raw=bytes)
643
+
644
+ def text_to_speech_url(self, text: str, **options: Any) -> Dict[str, Any]:
645
+ """Speak `text` and get a signed link that plays without your key until it expires.
646
+ Takes the options of text_to_speech except cache, and expires_in (60 seconds to 7 days, default 3600).
647
+ Returns {"url", "expiresAt", "cached", "characters", "provider", "voice", "format"}."""
648
+ return self.request("POST", "/speech/tts", {**_body({"text": text, **options}, _NAMES), "response": "url"})
649
+
650
+ def speech_to_text(
651
+ self,
652
+ audio: Union[bytes, bytearray, memoryview],
653
+ content_type: str = "application/octet-stream",
654
+ language: Optional[str] = None,
655
+ provider: Optional[str] = None,
656
+ model: Optional[str] = None,
657
+ timeout: float = 120.0,
658
+ ) -> Dict[str, Any]:
659
+ """Transcribe a recording (up to 25 MB): {"text", "language"?, "seconds", "provider", "words"?}.
660
+
661
+ content_type: e.g. "audio/webm", "audio/wav", "audio/mpeg". language: unset = detected (Deepgram,
662
+ ElevenLabs). provider: "deepgram", "elevenlabs" or "spitch". model: a Deepgram model (default nova-3).
663
+ """
664
+ if not isinstance(audio, (bytes, bytearray, memoryview)):
665
+ raise SfuKitError(400, "audio must be bytes")
666
+ q = {k: v for k, v in (("language", language), ("provider", provider), ("model", model)) if v}
667
+ path = "/speech/stt" + (f"?{urllib.parse.urlencode(q)}" if q else "")
668
+ return self.request("POST", path, _encoded=(bytes(audio), content_type), timeout=timeout)
669
+
670
+ def get_speech_usage(self) -> Dict[str, Any]:
671
+ """Spending per day (US dollars) and today's cap: {"today": {…}, "days": […]}."""
672
+ return self.request("GET", "/speech/usage")
673
+
674
+ def set_speech_daily_budget(self, daily_budget_usd: Optional[float]) -> Dict[str, Any]:
675
+ """The project's own daily speech cap in US dollars (None = the server's default)."""
676
+ return self.request("PUT", "/speech/config", {"dailyBudgetUsd": daily_budget_usd})
677
+
678
+ # ---------- Translation (/languages, /translate/*) and AI interpreters ----------
679
+
680
+ def get_languages(self) -> List[Dict[str, Any]]:
681
+ """The languages every AI service takes: [{"code", "name", "native", "quality", "text",
682
+ "speechToText", "textToSpeech", "rtl"?}]. Public; good for a language picker."""
683
+ return self.request("GET", "/languages")["languages"]
684
+
685
+ def translate_text(
686
+ self,
687
+ text: str,
688
+ to: Union[str, List[str]],
689
+ from_: Optional[str] = None,
690
+ **options: Any,
691
+ ) -> Dict[str, Any]:
692
+ """Translate up to 20,000 characters into one language or up to 20 ("fr" or ["fr", "de"]).
693
+
694
+ from_: the source language (unset = detected). options: tier ("standard", "smart", "best"),
695
+ context (what the text is, for tone), formality ("formal" or "informal"), glossary
696
+ ({"term": "translation"}), user and label (for the AI Tasks audit and per-person allowance).
697
+ Returns {"from", "to", "translations": {code: text}, "text"? (one target), "tier", "usage"}.
698
+ Billed as AI Tasks credits, within the project's AI Tasks daily cap.
699
+ """
700
+ return self.request("POST", "/translate/text", _body({"text": text, "to": to, "from": from_, **options}))
701
+
702
+ def translate_speech(
703
+ self,
704
+ audio: Union[bytes, bytearray, memoryview],
705
+ to: Union[str, List[str]],
706
+ content_type: str = "application/octet-stream",
707
+ from_: Optional[str] = None,
708
+ speak: bool = False,
709
+ timeout: float = 180.0,
710
+ **options: Any,
711
+ ) -> Dict[str, Any]:
712
+ """Hear a recording (up to 25 MB), translate it, and with speak=True voice it (up to 5 languages).
713
+
714
+ options: voice, format ("mp3" or "wav"), tier, context, formality, user, label.
715
+ Returns {"from", "transcript", "seconds", "to", "translations", "text"?, "audio"? ({code: {"url",
716
+ "expiresAt"}}), "usage"}. Errors carry "step": "speech to text", "translate" or "text to speech".
717
+ """
718
+ if not isinstance(audio, (bytes, bytearray, memoryview)):
719
+ raise SfuKitError(400, "audio must be bytes")
720
+ q: Dict[str, Any] = {"to": ",".join(to) if isinstance(to, (list, tuple)) else to}
721
+ if from_:
722
+ q["from"] = from_
723
+ if speak:
724
+ q["speak"] = "true"
725
+ q.update({k: v for k, v in options.items() if v is not None})
726
+ return self.request("POST", f"/translate/speech?{urllib.parse.urlencode(q)}", _encoded=(bytes(audio), content_type), timeout=timeout)
727
+
728
+ def start_interpreter(self, room_id: str, language: str, from_: Optional[str] = None, **options: Any) -> Dict[str, Any]:
729
+ """Add an AI interpreter to a room: it speaks what people say in `language` ("fr", "de", …).
730
+ Only people who chose that language (room.setInterpretation in the client, or the kits'
731
+ My language menu) hear it. Up to 3 per room, one per language.
732
+
733
+ options: name, voice_name, tts ("cartesia" or "elevenlabs"), metadata. Returns {"roomId",
734
+ "agentId", "participant"}. Billed as AI Agent minutes plus Speech characters, within the
735
+ project's Speech daily cap.
736
+ """
737
+ body = _body({"language": language, "from": from_, **options}, {"voice_name": "voiceName"})
738
+ return self.request("POST", f"/rooms/{_id(room_id)}/interpreters", body)
739
+
740
+ def list_interpreters(self, room_id: str) -> List[Dict[str, Any]]:
741
+ """The room's AI interpreters: [{"agentId", "language", "listeners"}]."""
742
+ return self.request("GET", f"/rooms/{_id(room_id)}/interpreters")["interpreters"]
743
+
744
+ def stop_interpreter(self, room_id: str, agent_id: str) -> None:
745
+ """Remove an AI interpreter from a room."""
746
+ self.request("DELETE", f"/rooms/{_id(room_id)}/interpreters/{_id(agent_id)}")
747
+
748
+ # ---------- Videos (video on demand on R2) ----------
749
+
750
+ #: Seconds a video upload may take (a whole file, or one part of it); longer than `timeout`.
751
+ UPLOAD_TIMEOUT = 600.0
752
+
753
+ def create_video_upload(
754
+ self,
755
+ max_duration_seconds: int,
756
+ name: Optional[str] = None,
757
+ meta: Optional[Dict[str, str]] = None,
758
+ upload_length: Optional[int] = None,
759
+ ) -> Dict[str, Any]:
760
+ """An upload link for one video: give `uploadUrl` to the browser (it PUTs the file straight to it,
761
+ or its parts when `protocol` is "parts"), or send a file from your server with upload_video_file.
762
+
763
+ max_duration_seconds: the longest the video may be (longer ones are refused when converted).
764
+ meta: up to 10 string pairs of your own. upload_length: the file's size in bytes; required over 95 MB (up to 5 GB).
765
+ Returns {"videoId", "uploadUrl", "protocol": "put" | "parts", "partSize"?, "parts"?, "expiresAt"}.
766
+ """
767
+ return self.request(
768
+ "POST",
769
+ "/videos/uploads",
770
+ _body({"max_duration_seconds": max_duration_seconds, "name": name, "meta": meta, "upload_length": upload_length}, _NAMES),
771
+ )
772
+
773
+ def upload_video_file(self, upload: Dict[str, Any], file: Any) -> Dict[str, Any]:
774
+ """Send a file from your server to an upload link (both protocols): one PUT, or each part in turn
775
+ and then the finishing POST. `file` is bytes, or a binary file object (read in parts for big files).
776
+ Returns the video."""
777
+ url = upload["uploadUrl"]
778
+ timeout = max(self.timeout, self.UPLOAD_TIMEOUT)
779
+ if upload.get("protocol") == "put":
780
+ return self._upload(url, "PUT", file if isinstance(file, (bytes, bytearray, memoryview)) else file.read(), None, timeout)
781
+ size = upload.get("partSize") or 50 * 1024 * 1024
782
+ sep = "&" if "?" in url else "?"
783
+ parts = []
784
+ n = 1
785
+ for chunk in _slices(file, size):
786
+ parts.append(self._upload(f"{url}{sep}part={n}", "PUT", chunk, None, timeout))
787
+ n += 1
788
+ return self._upload(f"{url}{sep}complete", "POST", _json({"parts": parts}).encode("utf-8"), "application/json", timeout)
789
+
790
+ def copy_video(self, url: str, **options: Any) -> Dict[str, Any]:
791
+ """Bring in a video from a public https link (moving an existing library over).
792
+ options: name, meta, max_duration_seconds."""
793
+ return self.request("POST", "/videos/copy", {"url": url, **_body(options, _NAMES)})
794
+
795
+ def list_videos(self, after: Optional[str] = None, limit: Optional[int] = None) -> Dict[str, Any]:
796
+ """Your videos, newest first: {"videos": […], "next": …}. Pass `next` from the last page as `after`."""
797
+ q = {k: v for k, v in (("after", after), ("limit", limit)) if v is not None and v != ""}
798
+ return self.request("GET", "/videos" + (f"?{urllib.parse.urlencode(q)}" if q else ""))
799
+
800
+ def get_video(self, video_id: str) -> Dict[str, Any]:
801
+ return self.request("GET", f"/videos/{_id(video_id)}")
802
+
803
+ def update_video(self, video_id: str, **update: Any) -> Dict[str, Any]:
804
+ """Rename (name=), or replace your meta (meta=)."""
805
+ return self.request("PATCH", f"/videos/{_id(video_id)}", update)
806
+
807
+ def delete_video(self, video_id: str) -> None:
808
+ """Delete the video and its files for good."""
809
+ self.request("DELETE", f"/videos/{_id(video_id)}")
810
+
811
+ def video_playback(self, video_id: str, expires_in_seconds: Optional[int] = None) -> Dict[str, Any]:
812
+ """Signed links for one viewer: {"hls", "iframe", "thumbnail", "expiresAt"}. Make one per viewing; they expire."""
813
+ return self.request("POST", f"/videos/{_id(video_id)}/playback", _body({"expires_in_seconds": expires_in_seconds}, _NAMES))
814
+
815
+ def get_video_usage(self) -> Dict[str, Any]:
816
+ """Bytes kept, this month's meters and your caps."""
817
+ return self.request("GET", "/videos/usage")
818
+
504
819
  def health(self) -> Dict[str, Any]:
505
820
  return self.request("GET", "/health")
506
821
 
507
822
  # ---------- plumbing ----------
508
823
 
509
- def request(self, method: str, path: str, body: Any = None, raw: Any = False, _encoded: Optional[tuple] = None) -> Any:
510
- """Call any admin endpoint (for routes this SDK doesn't wrap yet). raw=True: text, raw=bytes: bytes."""
511
- headers = {"Authorization": f"Bearer {self._admin_key}", "User-Agent": f"sfukit-python/{__version__}"}
824
+ def _headers(self) -> Dict[str, str]:
825
+ return {"Authorization": f"Bearer {self._admin_key}", "User-Agent": f"sfukit-python/{__version__}"}
826
+
827
+ def _upload(self, url: str, method: str, data: Any, content_type: Optional[str], timeout: float) -> Any:
828
+ """Send bytes to an upload link the kit gave. The link carries its own token, so no key is sent."""
829
+ if urllib.parse.urlparse(url).scheme not in ("http", "https"):
830
+ raise SfuKitError(400, f'invalid upload link "{url}"')
831
+ headers = {"User-Agent": f"sfukit-python/{__version__}"}
832
+ if content_type:
833
+ headers["Content-Type"] = content_type
834
+ req = urllib.request.Request(url, data=bytes(data), headers=headers, method=method)
835
+ try:
836
+ with urllib.request.urlopen(req, timeout=timeout) as res:
837
+ text = res.read().decode("utf-8")
838
+ except urllib.error.HTTPError as e:
839
+ raise _http_error("video upload", e) from None
840
+ return json.loads(text) if text else None
841
+
842
+ def request(
843
+ self,
844
+ method: str,
845
+ path: str,
846
+ body: Any = None,
847
+ raw: Any = False,
848
+ _encoded: Optional[tuple] = None,
849
+ timeout: Optional[float] = None,
850
+ ) -> Any:
851
+ """Call any admin endpoint (for routes this SDK doesn't wrap yet). raw=True: text, raw=bytes: bytes.
852
+ timeout: seconds for this call (default: the client's)."""
853
+ headers = self._headers()
512
854
  data = None
513
855
  if _encoded is not None:
514
856
  data, headers["Content-Type"] = _encoded
@@ -517,24 +859,32 @@ class SfuKit:
517
859
  headers["Content-Type"] = "application/json"
518
860
  req = urllib.request.Request(self.url + path, data=data, headers=headers, method=method)
519
861
  try:
520
- with urllib.request.urlopen(req, timeout=self.timeout) as res:
862
+ with urllib.request.urlopen(req, timeout=self.timeout if timeout is None else timeout) as res:
521
863
  data_out = res.read()
522
864
  if raw is bytes:
523
865
  return data_out
524
866
  text = data_out.decode("utf-8")
525
867
  except urllib.error.HTTPError as e:
526
- text = e.read().decode("utf-8", "replace")
527
- try:
528
- parsed: Any = json.loads(text)
529
- except ValueError:
530
- parsed = text
531
- msg = parsed.get("error", text) if isinstance(parsed, dict) else text
532
- raise SfuKitError(e.code, f"sfukit {method} {path}: {e.code} {msg}", parsed) from None
868
+ raise _http_error(f"{method} {path}", e) from None
533
869
  if raw:
534
870
  return text
535
871
  return json.loads(text) if text else None
536
872
 
537
873
 
874
+ def _slices(file: Any, size: int):
875
+ """The file's parts of `size` bytes: slices of bytes, or reads from a file object."""
876
+ if isinstance(file, (bytes, bytearray, memoryview)):
877
+ view = memoryview(file)
878
+ for at in range(0, len(view), size):
879
+ yield view[at : at + size]
880
+ return
881
+ while True:
882
+ chunk = file.read(size)
883
+ if not chunk:
884
+ return
885
+ yield chunk
886
+
887
+
538
888
  def _b64url(data: bytes) -> str:
539
889
  return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
540
890
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: appsocom
3
- Version: 0.7.0
3
+ Version: 0.9.0
4
4
  Summary: Python server SDK for Appsocom Live video calls: join tokens, rooms, moderation and webhook verification
5
5
  Author: Appsotech Limited
6
6
  License-Expression: MIT
@@ -86,7 +86,33 @@ def assistant_tools_route():
86
86
 
87
87
  `handle()` refuses bad or stale signatures with 401, answers `{"result": ...}` (`"done"` when a tool returns `None`) or `{"error": ...}`, and hides any exception other than `AssistantToolError` as "The tool failed." (pass `on_error=` to see it). Also: `get_assistant_config`, `delete_assistant_conversation(user_id, conversation_id)`, `verify_assistant_tool_call`.
88
88
 
89
- All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `set_assistant_config`, `get_assistant_config`, `create_assistant_token`, `delete_assistant_conversation`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`, `assistant_tools`, `verify_assistant_tool_call`.
89
+ ## AI Tasks, Speech and Videos
90
+
91
+ ```python
92
+ # AI Tasks: one Claude call from your server (a ready-made task, or your own prompt)
93
+ marked = kit.ai_task("mark", {"question": q, "answer": a, "rubric": rubric, "maxScore": 10}, user=student_id)
94
+ marked["json"]["score"], marked["usage"]["credits"]
95
+ draft = kit.ai_complete("Write a two-line welcome for new parents.", tier="standard")
96
+ data = kit.ai_complete("List the dates in this letter: ...", json={"type": "object", "properties": {"dates": {"type": "array"}}})
97
+ with kit.ai_stream("Tell a short story.") as story:
98
+ for piece in story:
99
+ print(piece, end="")
100
+ story.usage # model, tokens, cost, credits
101
+
102
+ # Speech
103
+ audio = kit.text_to_speech("Well done!", language="en") # mp3 bytes
104
+ link = kit.text_to_speech_url("Ẹ káàárọ̀", language="yo", expires_in=3600) # link["url"] plays without your key
105
+ heard = kit.speech_to_text(recording_bytes, content_type="audio/webm", language="ha") # heard["text"]
106
+
107
+ # Videos: an upload link for a browser, or send a file from your server
108
+ upload = kit.create_video_upload(3600, name="Lesson 1", upload_length=size)
109
+ kit.upload_video_file(upload, open("lesson.mp4", "rb"))
110
+ links = kit.video_playback(upload["videoId"]) # links["hls"], links["iframe"], links["thumbnail"]
111
+ ```
112
+
113
+ `ai_complete` and `ai_task` return the API's answer as a dict (`text`, `json`, `usage`); a call the kit refuses (daily limit, no credit) raises `SfuKitError` with the status, and `ai_stream` raises it at once. Settings and reports: `get_ai_settings`, `set_ai_settings`, `get_ai_usage(days)`, `get_ai_audit(day, user)`, `get_speech_usage`, `set_speech_daily_budget`, `get_video_usage`. Videos: `copy_video`, `list_videos`, `get_video`, `update_video`, `delete_video`. See [AI Tasks](https://docs.appsocom.dev/ai-tasks/), [Speech](https://docs.appsocom.dev/speech/) and [Videos](https://docs.appsocom.dev/videos/).
114
+
115
+ All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `set_assistant_config`, `get_assistant_config`, `create_assistant_token`, `delete_assistant_conversation`, `ai_complete`, `ai_task`, `ai_stream`, `get_ai_settings`, `set_ai_settings`, `get_ai_usage`, `get_ai_audit`, `text_to_speech`, `text_to_speech_url`, `speech_to_text`, `get_speech_usage`, `set_speech_daily_budget`, `create_video_upload`, `upload_video_file`, `copy_video`, `list_videos`, `get_video`, `update_video`, `delete_video`, `video_playback`, `get_video_usage`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`, `assistant_tools`, `verify_assistant_tool_call`.
90
116
 
91
117
  Self-hosting your own deployment instead? Point `url` at it and pass its admin key; the optional `jwt_secret` signs tokens locally without an HTTP call.
92
118
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "appsocom"
7
- version = "0.7.0"
7
+ version = "0.9.0"
8
8
  description = "Python server SDK for Appsocom Live video calls: join tokens, rooms, moderation and webhook verification"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -298,3 +298,255 @@ class DataSaverTokenTest(unittest.TestCase):
298
298
  self.assertNotIn("ds", claims(sign_token(SECRET, "r1", "u1", data_saver="off")["token"]))
299
299
  with self.assertRaises(ValueError):
300
300
  sign_token(SECRET, "r1", "u1", data_saver="ultra")
301
+
302
+
303
+ class ServicesHandler(BaseHTTPRequestHandler):
304
+ """A fake kit for AI Tasks, Speech and Videos: remembers every request it gets."""
305
+
306
+ seen = []
307
+
308
+ def log_message(self, *a):
309
+ pass
310
+
311
+ def _reply(self, code, payload, ctype="application/json"):
312
+ data = payload if isinstance(payload, bytes) else json.dumps(payload).encode()
313
+ self.send_response(code)
314
+ self.send_header("Content-Type", ctype)
315
+ self.send_header("Content-Length", str(len(data)))
316
+ self.end_headers()
317
+ self.wfile.write(data)
318
+
319
+ def _go(self):
320
+ n = int(self.headers.get("Content-Length") or 0)
321
+ raw = self.rfile.read(n) if n else b""
322
+ ServicesHandler.seen.append((self.command, self.path, {k.lower(): v for k, v in self.headers.items()}, raw))
323
+ path, _, query = self.path.partition("?")
324
+ body = json.loads(raw) if raw and self.headers.get("Content-Type") == "application/json" else {}
325
+ base = f"http://127.0.0.1:{self.server.server_port}"
326
+ if path == "/ai/complete":
327
+ if body.get("prompt") == "limit":
328
+ return self._reply(429, {"error": "AI Tasks has reached this project's daily limit"})
329
+ if body.get("stream"):
330
+ self.send_response(200)
331
+ self.send_header("Content-Type", "text/event-stream")
332
+ self.end_headers()
333
+ if body.get("prompt") == "boom":
334
+ self.wfile.write(b'event: text\ndata: {"text":"Hel"}\n\nevent: error\ndata: {"error":"the model stopped"}\n\n')
335
+ else:
336
+ self.wfile.write(b'event: text\ndata: {"text":"Hel"}\n\nevent: text\ndata: {"text":"lo \xc3\xa9"}\n\nevent: done\ndata: {"usage":{"credits":0.2}}\n\n')
337
+ return
338
+ return self._reply(200, {"task": body.get("task", "custom"), "text": "ok", "json": {"score": 3}, "usage": {"credits": 0.1}})
339
+ if path in ("/ai/settings", "/ai/usage", "/ai/audit", "/speech/usage"):
340
+ return self._reply(200, {})
341
+ if path == "/speech/tts":
342
+ if body.get("response") == "url":
343
+ return self._reply(200, {"url": f"{base}/speech/audio/t/x.mp3?exp=1&sig=a", "cached": True, "characters": 0})
344
+ return self._reply(200, b"\x01\x02", "audio/mpeg")
345
+ if path == "/speech/stt":
346
+ if raw == b"quota":
347
+ return self._reply(429, {"error": "the project's daily speech budget is used up"})
348
+ return self._reply(200, {"text": "hello", "seconds": 3, "provider": "deepgram"})
349
+ if path == "/languages":
350
+ return self._reply(200, {"languages": [{"code": "fr", "name": "French"}]})
351
+ if path == "/translate/text":
352
+ return self._reply(200, {"from": "en", "to": ["fr"], "translations": {"fr": "Bonjour"}, "text": "Bonjour"})
353
+ if path == "/translate/speech":
354
+ return self._reply(200, {"from": "en", "transcript": "hello", "translations": {"fr": "bonjour"}})
355
+ if path.endswith("/interpreters") and self.command == "GET":
356
+ return self._reply(200, {"interpreters": [{"agentId": "a1", "language": "fr", "listeners": 2}], "max": 3})
357
+ if "/interpreters" in path:
358
+ return self._reply(200, {"roomId": "r1", "agentId": "a1"} if self.command == "POST" else {"stopped": True})
359
+ if path == "/speech/config":
360
+ return self._reply(200, {"dailyBudgetUsd": body.get("dailyBudgetUsd"), "effectiveDailyCapUsd": 5})
361
+ if path == "/videos/uploads":
362
+ parts = body.get("name") == "big"
363
+ out = {"videoId": "v", "uploadUrl": f"{base}/videos/upload/p/v?t=x", "protocol": "parts" if parts else "put", "expiresAt": ""}
364
+ return self._reply(200, {**out, "partSize": 4, "parts": 3} if parts else out)
365
+ if path == "/videos/copy":
366
+ return self._reply(200, {"videoId": "v", "status": "processing"})
367
+ if path == "/videos/upload/p/v":
368
+ if "part=" in query:
369
+ n = int(query.split("part=")[1])
370
+ return self._reply(200, {"partNumber": n, "etag": f"e{n}"})
371
+ return self._reply(200, {"videoId": "v", "status": "processing"})
372
+ if path == "/videos" or path.startswith("/videos/"): # list, one video, update, delete, playback, usage
373
+ return self._reply(200, {"videoId": "v", "videos": [], "next": None})
374
+ self._reply(404, {"error": "no such route"})
375
+
376
+ do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = _go
377
+
378
+
379
+ class ServicesTests(unittest.TestCase):
380
+ @classmethod
381
+ def setUpClass(cls):
382
+ cls.server = HTTPServer(("127.0.0.1", 0), ServicesHandler)
383
+ threading.Thread(target=cls.server.serve_forever, daemon=True).start()
384
+ cls.kit = SfuKit(f"http://127.0.0.1:{cls.server.server_port}", "k")
385
+
386
+ @classmethod
387
+ def tearDownClass(cls):
388
+ cls.server.shutdown()
389
+
390
+ def last(self):
391
+ method, path, headers, raw = ServicesHandler.seen[-1]
392
+ return method, path, headers, (json.loads(raw) if raw and headers.get("content-type") == "application/json" else None)
393
+
394
+ def test_ai_tasks_post_to_ai_complete(self):
395
+ r = self.kit.ai_task("mark", {"question": "q", "answer": "a"}, user="s1", tier="smart", max_tokens=500, label=None)
396
+ self.assertEqual(r["json"], {"score": 3})
397
+ method, path, headers, body = self.last()
398
+ self.assertEqual((method, path, headers["authorization"]), ("POST", "/ai/complete", "Bearer k"))
399
+ self.assertEqual(body, {"user": "s1", "tier": "smart", "maxTokens": 500, "task": "mark", "input": {"question": "q", "answer": "a"}})
400
+ self.kit.ai_complete("hi", system="Be brief", json=True)
401
+ self.assertEqual(self.last()[3], {"prompt": "hi", "system": "Be brief", "json": True, "stream": False})
402
+ self.kit.ai_complete(system="Mark it", messages=[{"role": "user", "content": "x"}], json={"type": "object"})
403
+ self.assertEqual(self.last()[3], {"system": "Mark it", "messages": [{"role": "user", "content": "x"}], "json": {"type": "object"}, "stream": False})
404
+
405
+ def test_ai_tasks_errors_carry_the_status(self):
406
+ with self.assertRaises(SfuKitError) as cm:
407
+ self.kit.ai_complete("limit")
408
+ self.assertEqual(cm.exception.status, 429)
409
+ self.assertIn("daily limit", str(cm.exception))
410
+ with self.assertRaises(SfuKitError) as cm:
411
+ self.kit.ai_stream("limit") # refused at once, not on the first read
412
+ self.assertEqual(cm.exception.status, 429)
413
+
414
+ def test_ai_stream_yields_text_then_usage(self):
415
+ stream = self.kit.ai_stream("x", tier="standard")
416
+ self.assertIsNone(stream.usage)
417
+ self.assertEqual("".join(stream), "Hello é")
418
+ self.assertEqual(stream.usage, {"credits": 0.2})
419
+ self.assertEqual(self.last()[3], {"prompt": "x", "tier": "standard", "stream": True})
420
+ with self.assertRaises(SfuKitError) as cm:
421
+ list(self.kit.ai_stream("boom"))
422
+ self.assertEqual((cm.exception.status, str(cm.exception)), (502, "sfukit POST /ai/complete: the model stopped"))
423
+ with self.kit.ai_stream("x") as s: # stopping early closes the connection
424
+ self.assertEqual(next(iter(s)), "Hel")
425
+
426
+ def test_ai_settings_usage_and_audit_paths(self):
427
+ self.kit.set_ai_settings({"dailyBudgetUsd": 2})
428
+ self.assertEqual(self.last()[:2] + (self.last()[3],), ("PUT", "/ai/settings", {"dailyBudgetUsd": 2}))
429
+ self.kit.get_ai_settings()
430
+ self.assertEqual(self.last()[:2], ("GET", "/ai/settings"))
431
+ self.kit.get_ai_usage(30)
432
+ self.assertEqual(self.last()[:2], ("GET", "/ai/usage?days=30"))
433
+ self.kit.get_ai_usage()
434
+ self.assertEqual(self.last()[1], "/ai/usage?days=7")
435
+ self.kit.get_ai_audit("2026-11-20", "u1")
436
+ self.assertEqual(self.last()[1], "/ai/audit?day=2026-11-20&user=u1")
437
+ self.kit.get_ai_audit()
438
+ self.assertEqual(self.last()[1], "/ai/audit")
439
+
440
+ def test_speech(self):
441
+ self.assertEqual(self.kit.text_to_speech("Hi", language="yo", cache=None), b"\x01\x02")
442
+ self.assertEqual(self.last()[:2] + (self.last()[3],), ("POST", "/speech/tts", {"text": "Hi", "language": "yo", "response": "audio"}))
443
+ link = self.kit.text_to_speech_url("Hi", expires_in=600, format="wav")
444
+ self.assertIn("/speech/audio/", link["url"])
445
+ self.assertEqual(self.last()[3], {"text": "Hi", "expiresIn": 600, "format": "wav", "response": "url"})
446
+ out = self.kit.speech_to_text(b"\x00\x01\x02", content_type="audio/webm", language="en")
447
+ self.assertEqual((out["text"], out["seconds"]), ("hello", 3))
448
+ method, path, headers, _ = self.last()
449
+ self.assertEqual((method, path, headers["content-type"], headers["authorization"]), ("POST", "/speech/stt?language=en", "audio/webm", "Bearer k"))
450
+ self.assertEqual(ServicesHandler.seen[-1][3], b"\x00\x01\x02")
451
+ self.kit.speech_to_text(bytearray(b"a"))
452
+ self.assertEqual((self.last()[1], self.last()[2]["content-type"]), ("/speech/stt", "application/octet-stream"))
453
+ with self.assertRaises(SfuKitError) as cm:
454
+ self.kit.speech_to_text(b"quota")
455
+ self.assertEqual(cm.exception.status, 429)
456
+ with self.assertRaises(SfuKitError):
457
+ self.kit.speech_to_text("not bytes") # type: ignore[arg-type]
458
+ self.kit.get_speech_usage()
459
+ self.assertEqual(self.last()[:2], ("GET", "/speech/usage"))
460
+ self.assertEqual(self.kit.set_speech_daily_budget(None)["dailyBudgetUsd"], None)
461
+ self.assertEqual(self.last()[:2] + (self.last()[3],), ("PUT", "/speech/config", {"dailyBudgetUsd": None}))
462
+ self.assertEqual(self.kit.set_speech_daily_budget(2)["dailyBudgetUsd"], 2)
463
+
464
+ def test_translation_and_interpreters(self):
465
+ self.assertEqual(self.kit.get_languages()[0]["code"], "fr")
466
+ self.assertEqual(self.last()[:2], ("GET", "/languages"))
467
+ out = self.kit.translate_text("Hello", ["fr", "de"], from_="en", tier="smart", glossary={"Appsocom": "Appsocom"})
468
+ self.assertEqual(out["text"], "Bonjour")
469
+ self.assertEqual(self.last()[:2] + (self.last()[3],), ("POST", "/translate/text", {"text": "Hello", "to": ["fr", "de"], "from": "en", "tier": "smart", "glossary": {"Appsocom": "Appsocom"}}))
470
+ self.kit.translate_text("Hi", "fr")
471
+ self.assertEqual(self.last()[3], {"text": "Hi", "to": "fr"})
472
+ heard = self.kit.translate_speech(b"\x00\x01", ["fr", "de"], content_type="audio/webm", speak=True, voice="v1")
473
+ self.assertEqual(heard["transcript"], "hello")
474
+ method, path, headers, _ = self.last()
475
+ self.assertEqual((method, path, headers["content-type"]), ("POST", "/translate/speech?to=fr%2Cde&speak=true&voice=v1", "audio/webm"))
476
+ self.assertEqual(ServicesHandler.seen[-1][3], b"\x00\x01")
477
+ with self.assertRaises(SfuKitError):
478
+ self.kit.translate_speech("not bytes", "fr") # type: ignore[arg-type]
479
+ self.assertEqual(self.kit.start_interpreter("room-1", "fr", voice_name="v2")["agentId"], "a1")
480
+ self.assertEqual(self.last()[:2] + (self.last()[3],), ("POST", "/rooms/room-1/interpreters", {"language": "fr", "voiceName": "v2"}))
481
+ self.assertEqual(self.kit.list_interpreters("r1")[0]["listeners"], 2)
482
+ self.assertEqual(self.last()[:2], ("GET", "/rooms/r1/interpreters"))
483
+ self.assertIsNone(self.kit.stop_interpreter("r1", "a1"))
484
+ self.assertEqual(self.last()[:2], ("DELETE", "/rooms/r1/interpreters/a1"))
485
+
486
+ def test_the_video_methods_call_the_right_routes(self):
487
+ kit, v = self.kit, "a" * 32
488
+ calls = []
489
+
490
+ def seen(fn, *a, **kw):
491
+ fn(*a, **kw)
492
+ method, path, _, body = self.last()
493
+ calls.append((method, path, body))
494
+
495
+ seen(kit.create_video_upload, 600, name="Lesson 1", upload_length=5000)
496
+ seen(kit.copy_video, "https://files.example/a.mp4", name="Old")
497
+ seen(kit.list_videos, after="abc", limit=10)
498
+ seen(kit.list_videos)
499
+ seen(kit.get_video, v)
500
+ seen(kit.update_video, v, name="New")
501
+ seen(kit.video_playback, v, expires_in_seconds=900)
502
+ seen(kit.video_playback, v)
503
+ seen(kit.get_video_usage)
504
+ seen(kit.delete_video, v)
505
+ self.assertEqual(
506
+ calls,
507
+ [
508
+ ("POST", "/videos/uploads", {"maxDurationSeconds": 600, "name": "Lesson 1", "uploadLength": 5000}),
509
+ ("POST", "/videos/copy", {"url": "https://files.example/a.mp4", "name": "Old"}),
510
+ ("GET", "/videos?after=abc&limit=10", None),
511
+ ("GET", "/videos", None),
512
+ ("GET", f"/videos/{v}", None),
513
+ ("PATCH", f"/videos/{v}", {"name": "New"}),
514
+ ("POST", f"/videos/{v}/playback", {"expiresInSeconds": 900}),
515
+ ("POST", f"/videos/{v}/playback", {}),
516
+ ("GET", "/videos/usage", None),
517
+ ("DELETE", f"/videos/{v}", None),
518
+ ],
519
+ )
520
+ for bad in ("..", "a/b", "x" * 200):
521
+ with self.assertRaises(SfuKitError):
522
+ kit.get_video(bad)
523
+
524
+ def test_upload_video_file_sends_one_put_or_parts_then_complete(self):
525
+ import io
526
+
527
+ kit = self.kit
528
+ up = kit.create_video_upload(600)
529
+ n = len(ServicesHandler.seen)
530
+ self.assertEqual(kit.upload_video_file(up, b"0123456789")["status"], "processing")
531
+ method, path, headers, raw = ServicesHandler.seen[-1]
532
+ self.assertEqual((len(ServicesHandler.seen) - n, method, path, raw), (1, "PUT", "/videos/upload/p/v?t=x", b"0123456789"))
533
+ self.assertNotIn("authorization", headers) # the link has its own token; the key stays home
534
+ self.assertEqual(kit.upload_video_file(up, io.BytesIO(b"abc"))["status"], "processing")
535
+
536
+ for source in (b"0123456789", io.BytesIO(b"0123456789")):
537
+ big = kit.create_video_upload(600, name="big")
538
+ n = len(ServicesHandler.seen)
539
+ kit.upload_video_file(big, source)
540
+ sent = ServicesHandler.seen[n:]
541
+ self.assertEqual(
542
+ [(m, p, len(r)) for m, p, _, r in sent],
543
+ [("PUT", "/videos/upload/p/v?t=x&part=1", 4), ("PUT", "/videos/upload/p/v?t=x&part=2", 4), ("PUT", "/videos/upload/p/v?t=x&part=3", 2), ("POST", "/videos/upload/p/v?t=x&complete", len(sent[-1][3]))],
544
+ )
545
+ self.assertEqual(json.loads(sent[-1][3]), {"parts": [{"partNumber": 1, "etag": "e1"}, {"partNumber": 2, "etag": "e2"}, {"partNumber": 3, "etag": "e3"}]})
546
+ self.assertEqual(sent[-1][2]["content-type"], "application/json")
547
+ self.assertTrue(all("authorization" not in h for _, _, h, _ in sent))
548
+
549
+ def test_upload_links_must_be_http(self):
550
+ with self.assertRaises(SfuKitError) as cm:
551
+ self.kit.upload_video_file({"uploadUrl": "file:///etc/passwd", "protocol": "put"}, b"x")
552
+ self.assertEqual(cm.exception.status, 400)
File without changes
File without changes