Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save reboottime/621145668de6e97624340fc87e146a8c to your computer and use it in GitHub Desktop.
Save reboottime/621145668de6e97624340fc87e146a8c to your computer and use it in GitHub Desktop.
polling example
import HttpClient from 'whyfetch';
const API_KEY = process.env.NEXT_PUBLIC_ASSEMBLY_API_KEY;
const ASSEMBLY_BASE_URL = 'https://api.assemblyai.com/v2';
class Assembly {
private client: HttpClient;
constructor() {
this.client = new HttpClient(ASSEMBLY_BASE_URL, {
headers: {
authorization: API_KEY,
},
} as RequestInit);
}
transcribeAudio = async (audioUrl: string) => {
try {
const { id: transcribeId } = await this.client.post<Transcript>({
apiPath: 'transcript',
data: {
/**
* Here we can't have both the summarization and the chapters feature at the same time
*/
summarization: true,
summary_model: 'informative',
summary_type: 'bullets',
audio_url: audioUrl,
// auto_chapters: true,
iab_categories: true,
},
});
return await this.pollTranscript(transcribeId);
} catch (e) {
return Promise.reject(e);
}
};
getTranscripts = () => {
return this.client.get<TranscriptedItem[]>({
apiPath: '',
query: {
limit: 200,
states: 'completed',
},
});
};
getTranscript = (transcriptId: string) => {
return this.client.get<Transcript>({
apiPath: 'transcript/' + transcriptId,
});
};
private pollTranscript = async (transcriptId: string) => {
return new Promise<Transcript>(async (resolve, reject) => {
while (true) {
const transcript = await this.client.get<Transcript>({
apiPath: 'transcript/' + transcriptId,
});
if (transcript.status === 'completed') {
resolve(transcript);
break;
} else if (transcript.status === 'error') {
reject(transcript);
break;
} else {
await new Promise((resolve) =>
setTimeout(resolve, Math.random() * 2000)
);
}
}
});
};
}
const client = new Assembly();
export default client;
export type Transcript = {
status: 'completed' | 'queued' | 'processing' | 'error';
id: string;
language_model: 'assemblyai_default';
acoustic_model: 'assemblyai_default';
language_code: 'en_us';
audio_url: string;
text: string;
words: string[];
utterances: string;
confidence: number;
audio_duration: number;
punctuate: boolean;
chapters: Chapter[];
summary: string;
};
export type TranscriptedItem = {
id: string;
response_url: string;
status: Transcript['status'];
created: string;
completed: string;
audio_url: string;
};
export type Chapter = {
start: number;
end: number;
headline: string;
gist: string;
summary: string;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment