mirror of
https://github.com/lucasrcsantana/story-generator.git
synced 2025-12-18 14:27:51 +00:00
86 lines
2.2 KiB
TypeScript
86 lines
2.2 KiB
TypeScript
import { supabase } from '../lib/supabase';
|
|
|
|
interface ProcessAudioResponse {
|
|
transcription?: string;
|
|
error?: string;
|
|
}
|
|
|
|
export async function processAudio(audioFile: File, storyId: string): Promise<ProcessAudioResponse> {
|
|
try {
|
|
// 1. Gerar nome único para o arquivo
|
|
const fileName = `${crypto.randomUUID()}-${audioFile.name}`;
|
|
|
|
// 2. Primeiro criar o registro no banco
|
|
const { data: recordData, error: recordError } = await supabase
|
|
.from('story_recordings')
|
|
.insert({
|
|
story_id: storyId,
|
|
status: 'pending_analysis',
|
|
created_at: new Date().toISOString()
|
|
})
|
|
.select()
|
|
.single();
|
|
|
|
if (recordError) throw recordError;
|
|
|
|
// 3. Upload do arquivo para o bucket do Supabase
|
|
const { data: uploadData, error: uploadError } = await supabase.storage
|
|
.from('audio-uploads')
|
|
.upload(`recordings/${recordData.id}/${fileName}`, audioFile, {
|
|
cacheControl: '3600',
|
|
contentType: audioFile.type,
|
|
upsert: false
|
|
});
|
|
|
|
if (uploadError) {
|
|
// Se falhar o upload, deletar o registro
|
|
await supabase
|
|
.from('story_recordings')
|
|
.delete()
|
|
.eq('id', recordData.id);
|
|
|
|
throw uploadError;
|
|
}
|
|
|
|
// 4. Pegar URL pública do arquivo
|
|
const { data: { publicUrl } } = supabase.storage
|
|
.from('audio-uploads')
|
|
.getPublicUrl(`recordings/${recordData.id}/${fileName}`);
|
|
|
|
// 5. Atualizar registro com URL do áudio
|
|
const { error: updateError } = await supabase
|
|
.from('story_recordings')
|
|
.update({
|
|
audio_url: publicUrl
|
|
})
|
|
.eq('id', recordData.id);
|
|
|
|
if (updateError) throw updateError;
|
|
|
|
// 6. Chamar a Edge Function para processar o áudio
|
|
const { data, error } = await supabase.functions.invoke<ProcessAudioResponse>(
|
|
'process-audio',
|
|
{
|
|
body: {
|
|
record: {
|
|
id: recordData.id,
|
|
story_id: storyId,
|
|
audio_url: publicUrl
|
|
}
|
|
}
|
|
}
|
|
);
|
|
|
|
if (error) throw error;
|
|
|
|
return {
|
|
transcription: data?.transcription
|
|
};
|
|
|
|
} catch (error) {
|
|
console.error('Erro ao processar áudio:', error);
|
|
return {
|
|
error: 'Falha ao processar o áudio. Tente novamente.'
|
|
};
|
|
}
|
|
}
|