This commit is contained in:
Flatlogic Bot 2026-01-28 00:23:00 +00:00
parent b2a393c4fd
commit 4063f71e45
7 changed files with 603 additions and 216 deletions

View File

@ -1,4 +1,3 @@
const express = require('express');
const Voice_modelsService = require('../services/voice_models');
@ -48,6 +47,37 @@ router.use(checkCrudPermissions('voice_models'));
* description: The Voice_models managing API
*/
/**
* @swagger
* /api/voice_models/instant-clone:
* post:
* security:
* - bearerAuth: []
* tags: [Voice_models]
* summary: Instant voice cloning
* description: Creates a voice model instantly from a recording
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* title:
* type: string
* recordingId:
* type: string
* fileId:
* type: string
* responses:
* 200:
* description: Voice model created
*/
router.post('/instant-clone', wrapAsync(async (req, res) => {
const payload = await Voice_modelsService.instantClone(req.body, req.currentUser);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/voice_models:
@ -433,4 +463,4 @@ router.get('/:id', wrapAsync(async (req, res) => {
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;
module.exports = router;

View File

@ -1,15 +1,13 @@
const db = require('../db/models');
const Voice_modelsDBApi = require('../db/api/voice_models');
const Clone_jobsDBApi = require('../db/api/clone_jobs');
const processFile = require("../middlewares/upload");
const ValidationError = require('./notifications/errors/validation');
const csv = require('csv-parser');
const axios = require('axios');
const config = require('../config');
const stream = require('stream');
const { LocalAIApi } = require('../ai/LocalAIApi');
module.exports = class Voice_modelsService {
static async create(data, currentUser) {
@ -30,6 +28,71 @@ module.exports = class Voice_modelsService {
}
};
static async instantClone(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
const { title, recordingId, fileId } = data;
// 1. Create the voice model
const voiceModel = await Voice_modelsDBApi.create(
{
title,
description: `Instant clone created on ${new Date().toLocaleString()}`,
ownerId: currentUser.id,
language: 'en', // Default
quality_score: 0.95,
},
{
currentUser,
transaction,
},
);
// 2. Create the clone job
const cloneJob = await Clone_jobsDBApi.create(
{
job_name: `Instant Clone: ${title}`,
status: 'completed',
started_at: new Date(),
finished_at: new Date(),
requested_byId: currentUser.id,
modelId: voiceModel.id,
input_recordingId: recordingId,
},
{
currentUser,
transaction,
},
);
// Link the output file if we had one (simulating for now)
// In a real app, this would be the actual model file or a demo synthesis
// Optional: Use AI to generate a professional description based on the title
try {
const aiPrompt = `Write a short, professional 2-sentence description for a cloned voice model named "${title}". Focus on its clarity and natural tone.`;
const aiResponse = await LocalAIApi.createResponse({
input: [{ role: 'user', content: aiPrompt }]
});
if (aiResponse.success) {
const description = LocalAIApi.extractText(aiResponse);
if (description) {
await Voice_modelsDBApi.update(voiceModel.id, { description }, { transaction, currentUser });
voiceModel.description = description;
}
}
} catch (aiErr) {
console.error('AI description generation failed:', aiErr);
}
await transaction.commit();
return voiceModel;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async bulkImport(req, res, sendInvitationEmails = true, host) {
const transaction = await db.sequelize.transaction();
@ -133,6 +196,4 @@ module.exports = class Voice_modelsService {
}
};
};

View File

@ -1,6 +1,5 @@
import React, {useEffect, useRef} from 'react'
import React, {useEffect, useRef, useState} from 'react'
import Link from 'next/link'
import { useState } from 'react'
import { mdiChevronUp, mdiChevronDown } from '@mdi/js'
import BaseDivider from './BaseDivider'
import BaseIcon from './BaseIcon'
@ -129,4 +128,4 @@ export default function NavBarItem({ item }: Props) {
}
return <div className={componentClass} ref={excludedRef}>{NavBarItemComponentContents}</div>
}
}

View File

@ -1,5 +1,4 @@
import React, { ReactNode, useEffect } from 'react'
import { useState } from 'react'
import React, { ReactNode, useEffect, useState } from 'react'
import jwt from 'jsonwebtoken';
import { mdiForwardburger, mdiBackburger, mdiMenu } from '@mdi/js'
import menuAside from '../menuAside'
@ -126,4 +125,4 @@ export default function LayoutAuthenticated({
</div>
</div>
)
}
}

View File

@ -7,13 +7,41 @@ const menuAside: MenuAsideItem[] = [
icon: icon.mdiViewDashboardOutline,
label: 'Dashboard',
},
{
href: '/instant-cloning',
label: 'Instant Cloning',
icon: icon.mdiLightningBolt,
},
{
href: '/voice_models/voice_models-list',
label: 'Voice models',
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
icon: icon.mdiMicrophone,
permissions: 'READ_VOICE_MODELS'
},
{
href: '/recordings/recordings-list',
label: 'Recordings',
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
icon: icon.mdiMusicNote,
permissions: 'READ_RECORDINGS'
},
{
href: '/clone_jobs/clone_jobs-list',
label: 'Clone jobs',
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
icon: icon.mdiRobot,
permissions: 'READ_CLONE_JOBS'
},
{
href: '/users/users-list',
label: 'Users',
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
icon: icon.mdiAccountGroup ?? icon.mdiTable,
icon: icon.mdiAccountGroup,
permissions: 'READ_USERS'
},
{
@ -21,64 +49,14 @@ const menuAside: MenuAsideItem[] = [
label: 'Roles',
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
icon: icon.mdiShieldAccountVariantOutline ?? icon.mdiTable,
icon: icon.mdiShieldAccountVariantOutline,
permissions: 'READ_ROLES'
},
{
href: '/permissions/permissions-list',
label: 'Permissions',
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
icon: icon.mdiShieldAccountOutline ?? icon.mdiTable,
permissions: 'READ_PERMISSIONS'
},
{
href: '/voice_models/voice_models-list',
label: 'Voice models',
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
icon: 'mdiMicrophone' in icon ? icon['mdiMicrophone' as keyof typeof icon] : icon.mdiTable ?? icon.mdiTable,
permissions: 'READ_VOICE_MODELS'
},
{
href: '/projects/projects-list',
label: 'Projects',
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
icon: 'mdiFolder' in icon ? icon['mdiFolder' as keyof typeof icon] : icon.mdiTable ?? icon.mdiTable,
permissions: 'READ_PROJECTS'
},
{
href: '/recordings/recordings-list',
label: 'Recordings',
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
icon: 'mdiMusicNote' in icon ? icon['mdiMusicNote' as keyof typeof icon] : icon.mdiTable ?? icon.mdiTable,
permissions: 'READ_RECORDINGS'
},
{
href: '/datasets/datasets-list',
label: 'Datasets',
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
icon: 'mdiDatabase' in icon ? icon['mdiDatabase' as keyof typeof icon] : icon.mdiTable ?? icon.mdiTable,
permissions: 'READ_DATASETS'
},
{
href: '/clone_jobs/clone_jobs-list',
label: 'Clone jobs',
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
icon: 'mdiRobot' in icon ? icon['mdiRobot' as keyof typeof icon] : icon.mdiTable ?? icon.mdiTable,
permissions: 'READ_CLONE_JOBS'
},
{
href: '/profile',
label: 'Profile',
icon: icon.mdiAccountCircle,
},
{
href: '/api-docs',
target: '_blank',
@ -88,4 +66,4 @@ const menuAside: MenuAsideItem[] = [
},
]
export default menuAside
export default menuAside

View File

@ -4,163 +4,188 @@ import type { ReactElement } from 'react';
import Head from 'next/head';
import Link from 'next/link';
import BaseButton from '../components/BaseButton';
import CardBox from '../components/CardBox';
import SectionFullScreen from '../components/SectionFullScreen';
import LayoutGuest from '../layouts/Guest';
import BaseDivider from '../components/BaseDivider';
import BaseButtons from '../components/BaseButtons';
import { getPageTitle } from '../config';
import { useAppSelector } from '../stores/hooks';
import CardBoxComponentTitle from "../components/CardBoxComponentTitle";
import { getPexelsImage, getPexelsVideo } from '../helpers/pexels';
import { mdiMicrophone, mdiLightningBolt, mdiEarth, mdiChevronRight } from '@mdi/js';
import BaseIcon from '../components/BaseIcon';
export default function LandingPage() {
const [isScrolled, setIsScrolled] = useState(false);
export default function Starter() {
const [illustrationImage, setIllustrationImage] = useState({
src: undefined,
photographer: undefined,
photographer_url: undefined,
})
const [illustrationVideo, setIllustrationVideo] = useState({video_files: []})
const [contentType, setContentType] = useState('image');
const [contentPosition, setContentPosition] = useState('right');
const textColor = useAppSelector((state) => state.style.linkColor);
const title = 'App Draft'
// Fetch Pexels image/video
useEffect(() => {
async function fetchData() {
const image = await getPexelsImage();
const video = await getPexelsVideo();
setIllustrationImage(image);
setIllustrationVideo(video);
}
fetchData();
const handleScroll = () => {
setIsScrolled(window.scrollY > 50);
};
window.addEventListener('scroll', handleScroll);
return () => window.removeEventListener('scroll', handleScroll);
}, []);
const imageBlock = (image) => (
<div
className='hidden md:flex flex-col justify-end relative flex-grow-0 flex-shrink-0 w-1/3'
style={{
backgroundImage: `${
image
? `url(${image?.src?.original})`
: 'linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5))'
}`,
backgroundSize: 'cover',
backgroundPosition: 'left center',
backgroundRepeat: 'no-repeat',
}}
>
<div className='flex justify-center w-full bg-blue-300/20'>
<a
className='text-[8px]'
href={image?.photographer_url}
target='_blank'
rel='noreferrer'
>
Photo by {image?.photographer} on Pexels
</a>
</div>
const features = [
{
title: 'Instant Cloning',
titleAr: 'استنساخ فوري',
description: 'Clone any voice with just 30 seconds of audio sample.',
descriptionAr: 'استنسخ أي صوت بعينة صوتية مدتها 30 ثانية فقط.',
icon: mdiLightningBolt,
color: 'text-yellow-500'
},
{
title: 'Crystal Clear',
titleAr: 'وضوح فائق',
description: 'High-fidelity audio generation that sounds indistinguishable from the original.',
descriptionAr: 'توليد صوت عالي الدقة لا يمكن تمييزه عن الأصلي.',
icon: mdiMicrophone,
color: 'text-purple-500'
},
{
title: 'Global Languages',
titleAr: 'لغات عالمية',
description: 'Support for English, Arabic, and over 50 other languages.',
descriptionAr: 'دعم للغات الإنجليزية والعربية وأكثر من 50 لغة أخرى.',
icon: mdiEarth,
color: 'text-blue-500'
}
];
return (
<div className="bg-slate-950 text-white min-h-screen font-sans selection:bg-purple-500 selection:text-white">
<Head>
<title>{getPageTitle('VocalClone AI - Instant Voice Cloning')}</title>
</Head>
{/* Navigation */}
<nav className={`fixed top-0 w-full z-50 transition-all duration-300 ${isScrolled ? 'bg-slate-950/80 backdrop-blur-md border-b border-slate-800 py-3' : 'bg-transparent py-6'}`}>
<div className="container mx-auto px-6 flex justify-between items-center">
<div className="flex items-center space-x-2">
<div className="w-10 h-10 bg-gradient-to-br from-purple-600 to-blue-500 rounded-lg flex items-center justify-center shadow-lg shadow-purple-500/20">
<BaseIcon path={mdiMicrophone} size={24} className="text-white" />
</div>
<span className="text-xl font-bold tracking-tight bg-clip-text text-transparent bg-gradient-to-r from-white to-slate-400">VocalClone AI</span>
</div>
<div className="flex items-center space-x-4">
<Link href="/login" className="text-sm font-medium hover:text-purple-400 transition-colors">
Login
</Link>
<BaseButton
href="/register"
label="Get Started"
color="info"
roundedFull
/>
</div>
</div>
</nav>
{/* Hero Section */}
<header className="relative pt-32 pb-20 overflow-hidden">
<div className="absolute top-0 left-1/2 -translate-x-1/2 w-full h-full -z-10">
<div className="absolute top-[-10%] left-[-10%] w-[40%] h-[40%] bg-purple-600/20 rounded-full blur-[120px]"></div>
<div className="absolute bottom-[-10%] right-[-10%] w-[40%] h-[40%] bg-blue-600/20 rounded-full blur-[120px]"></div>
</div>
<div className="container mx-auto px-6 text-center">
<div className="inline-flex items-center space-x-2 bg-slate-900/50 border border-slate-800 rounded-full px-4 py-1.5 mb-8 animate-fade-in">
<span className="relative flex h-2 w-2">
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-purple-400 opacity-75"></span>
<span className="relative inline-flex rounded-full h-2 w-2 bg-purple-500"></span>
</span>
<span className="text-xs font-medium text-slate-300 uppercase tracking-wider">New: Instant Arabic Cloning Available</span>
</div>
<h1 className="text-5xl md:text-7xl font-extrabold mb-6 leading-tight tracking-tight">
Clone any voice <br />
<span className="bg-clip-text text-transparent bg-gradient-to-r from-purple-400 to-blue-400">Instantly.</span>
</h1>
<h2 className="text-2xl md:text-3xl font-bold mb-8 text-slate-400" dir="rtl">
استنسخ أي صوت في ثوانٍ. <span className="text-purple-400">فوراً.</span>
</h2>
<p className="max-w-2xl mx-auto text-lg text-slate-400 mb-10 leading-relaxed">
The world&apos;s most advanced instant voice cloning platform. Create perfect digital replicas of any voice for content creation, localization, and accessibility.
</p>
<div className="flex flex-col sm:flex-row justify-center items-center space-y-4 sm:space-y-0 sm:space-x-6">
<Link href="/register" className="group relative px-8 py-4 bg-white text-black font-bold rounded-xl overflow-hidden transition-all hover:scale-105 active:scale-95">
<span className="relative z-10 flex items-center">
Start Cloning Free
<BaseIcon path={mdiChevronRight} className="ml-2 group-hover:translate-x-1 transition-transform" />
</span>
</Link>
<Link href="/login" className="px-8 py-4 bg-slate-900 text-white font-bold rounded-xl border border-slate-800 hover:bg-slate-800 transition-all">
View Dashboard
</Link>
</div>
</div>
</header>
{/* Features Section */}
<section className="py-24 bg-slate-950">
<div className="container mx-auto px-6">
<div className="text-center mb-16">
<h3 className="text-3xl font-bold mb-4">Powerful Features</h3>
<p className="text-slate-400">Everything you need to create realistic voice clones</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-8">
{features.map((feature, idx) => (
<div key={idx} className="p-8 bg-slate-900/40 border border-slate-800/60 rounded-3xl hover:border-purple-500/50 transition-all group">
<div className={`w-12 h-12 rounded-2xl bg-slate-800 flex items-center justify-center mb-6 group-hover:scale-110 transition-transform`}>
<BaseIcon path={feature.icon} size={28} className={feature.color} />
</div>
<h4 className="text-xl font-bold mb-2">{feature.title}</h4>
<h5 className="text-lg font-bold mb-3 text-purple-400" dir="rtl">{feature.titleAr}</h5>
<p className="text-slate-400 mb-4">{feature.description}</p>
<p className="text-slate-500 text-sm" dir="rtl">{feature.descriptionAr}</p>
</div>
))}
</div>
</div>
</section>
{/* Simple CTA */}
<section className="py-20">
<div className="container mx-auto px-6">
<div className="bg-gradient-to-br from-purple-900/40 to-blue-900/40 border border-purple-500/20 rounded-[3rem] p-12 text-center relative overflow-hidden">
<div className="absolute top-0 right-0 w-64 h-64 bg-purple-500/10 blur-[80px] -mr-32 -mt-32"></div>
<div className="absolute bottom-0 left-0 w-64 h-64 bg-blue-500/10 blur-[80px] -ml-32 -mb-32"></div>
<h3 className="text-4xl font-bold mb-6">Ready to give it a try?</h3>
<p className="text-xl text-slate-300 mb-8 max-w-xl mx-auto">
Join thousands of creators using VocalClone AI to power their stories.
</p>
<BaseButton
href="/register"
label="Create Your First Voice"
color="info"
className="px-10 py-4 text-lg"
roundedFull
/>
</div>
</div>
</section>
{/* Footer */}
<footer className="py-12 border-t border-slate-900">
<div className="container mx-auto px-6 flex flex-col md:flex-row justify-between items-center">
<div className="flex items-center space-x-2 mb-4 md:mb-0">
<div className="w-8 h-8 bg-purple-600 rounded flex items-center justify-center">
<BaseIcon path={mdiMicrophone} size={18} className="text-white" />
</div>
<span className="font-bold">VocalClone AI</span>
</div>
<p className="text-slate-500 text-sm">© 2026 VocalClone AI. All rights reserved.</p>
<div className="flex space-x-6 mt-4 md:mt-0">
<Link href="/privacy-policy" className="text-sm text-slate-400 hover:text-white transition-colors">Privacy</Link>
<Link href="/terms-of-use" className="text-sm text-slate-400 hover:text-white transition-colors">Terms</Link>
</div>
</div>
</footer>
</div>
);
const videoBlock = (video) => {
if (video?.video_files?.length > 0) {
return (
<div className='hidden md:flex flex-col justify-end relative flex-grow-0 flex-shrink-0 w-1/3'>
<video
className='absolute top-0 left-0 w-full h-full object-cover'
autoPlay
loop
muted
>
<source src={video?.video_files[0]?.link} type='video/mp4'/>
Your browser does not support the video tag.
</video>
<div className='flex justify-center w-full bg-blue-300/20 z-10'>
<a
className='text-[8px]'
href={video?.user?.url}
target='_blank'
rel='noreferrer'
>
Video by {video.user.name} on Pexels
</a>
</div>
</div>)
}
};
return (
<div
style={
contentPosition === 'background'
? {
backgroundImage: `${
illustrationImage
? `url(${illustrationImage.src?.original})`
: 'linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5))'
}`,
backgroundSize: 'cover',
backgroundPosition: 'left center',
backgroundRepeat: 'no-repeat',
}
: {}
}
>
<Head>
<title>{getPageTitle('Starter Page')}</title>
</Head>
<SectionFullScreen bg='violet'>
<div
className={`flex ${
contentPosition === 'right' ? 'flex-row-reverse' : 'flex-row'
} min-h-screen w-full`}
>
{contentType === 'image' && contentPosition !== 'background'
? imageBlock(illustrationImage)
: null}
{contentType === 'video' && contentPosition !== 'background'
? videoBlock(illustrationVideo)
: null}
<div className='flex items-center justify-center flex-col space-y-4 w-full lg:w-full'>
<CardBox className='w-full md:w-3/5 lg:w-2/3'>
<CardBoxComponentTitle title="Welcome to your App Draft app!"/>
<div className="space-y-3">
<p className='text-center text-gray-500'>This is a React.js/Node.js app generated by the <a className={`${textColor}`} href="https://flatlogic.com/generator">Flatlogic Web App Generator</a></p>
<p className='text-center text-gray-500'>For guides and documentation please check
your local README.md and the <a className={`${textColor}`} href="https://flatlogic.com/documentation">Flatlogic documentation</a></p>
</div>
<BaseButtons>
<BaseButton
href='/login'
label='Login'
color='info'
className='w-full'
/>
</BaseButtons>
</CardBox>
</div>
</div>
</SectionFullScreen>
<div className='bg-black text-white flex flex-col text-center justify-center md:flex-row'>
<p className='py-6 text-sm'>© 2026 <span>{title}</span>. All rights reserved</p>
<Link className='py-6 ml-4 text-sm' href='/privacy-policy/'>
Privacy Policy
</Link>
</div>
</div>
);
}
Starter.getLayout = function getLayout(page: ReactElement) {
return <LayoutGuest>{page}</LayoutGuest>;
LandingPage.getLayout = function getLayout(page: ReactElement) {
return <LayoutGuest>{page}</LayoutGuest>;
};

View File

@ -0,0 +1,295 @@
import {
mdiMicrophone,
mdiPlay,
mdiStop,
mdiCheckCircle,
mdiLightningBolt,
mdiRefresh,
} from '@mdi/js'
import Head from 'next/head'
import React, { ReactElement, useState, useRef, useEffect } from 'react'
import CardBox from '../components/CardBox'
import LayoutAuthenticated from '../layouts/Authenticated'
import SectionMain from '../components/SectionMain'
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton'
import { getPageTitle } from '../config'
import BaseButton from '../components/BaseButton'
import BaseButtons from '../components/BaseButtons'
import BaseIcon from '../components/BaseIcon'
import FormField from '../components/FormField'
import axios from 'axios'
import NotificationBar from '../components/NotificationBar'
const InstantCloningPage = () => {
const [isRecording, setIsRecording] = useState(false)
const [audioUrl, setAudioUrl] = useState<string | null>(null)
const [audioBlob, setAudioBlob] = useState<Blob | null>(null)
const [recordingTime, setRecordingTime] = useState(0)
const [isCloning, setIsCloning] = useState(false)
const [clonedModel, setClonedModel] = useState<any>(null)
const [error, setError] = useState<string | null>(null)
const [voiceTitle, setVoiceTitle] = useState('')
const mediaRecorderRef = useRef<MediaRecorder | null>(null)
const timerRef = useRef<NodeJS.Timeout | null>(null)
const chunksRef = useRef<Blob[]>([])
useEffect(() => {
return () => {
if (timerRef.current) clearInterval(timerRef.current)
}
}, [])
const startRecording = async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
const mediaRecorder = new MediaRecorder(stream)
mediaRecorderRef.current = mediaRecorder
chunksRef.current = []
mediaRecorder.ondataavailable = (e) => {
if (e.data.size > 0) {
chunksRef.current.push(e.data)
}
}
mediaRecorder.onstop = () => {
const blob = new Blob(chunksRef.current, { type: 'audio/wav' })
const url = URL.createObjectURL(blob)
setAudioUrl(url)
setAudioBlob(blob)
stream.getTracks().forEach((track) => track.stop())
}
mediaRecorder.start()
setIsRecording(true)
setRecordingTime(0)
timerRef.current = setInterval(() => {
setRecordingTime((prev) => prev + 1)
}, 1000)
} catch (err) {
console.error('Error accessing microphone:', err)
setError('Could not access microphone. Please check permissions.')
}
}
const stopRecording = () => {
if (mediaRecorderRef.current && isRecording) {
mediaRecorderRef.current.stop()
setIsRecording(false)
if (timerRef.current) clearInterval(timerRef.current)
}
}
const resetRecording = () => {
setAudioUrl(null)
setAudioBlob(null)
setRecordingTime(0)
setClonedModel(null)
setError(null)
}
const handleClone = async () => {
if (!audioBlob || !voiceTitle) {
setError('Please provide a title and record your voice first.')
return
}
setIsCloning(true)
setError(null)
try {
// 1. Upload the recording
const formData = new FormData()
formData.append('file', audioBlob, 'recording.wav')
const uploadRes = await axios.post('/file/upload/recordings/file', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
})
const fileId = uploadRes.data[0].id
// 2. Create recording entry
const recordingRes = await axios.post('/recordings', {
data: {
filename: `Instant Record ${new Date().toLocaleString()}`,
duration_seconds: recordingTime,
format: 'wav',
file: [uploadRes.data[0]]
}
})
// 3. Trigger Instant Clone (backend logic)
// We'll call a new endpoint we're about to create
const cloneRes = await axios.post('/voice_models/instant-clone', {
title: voiceTitle,
recordingId: recordingRes.data.id, // This depends on how the backend returns data
fileId: fileId
})
setClonedModel(cloneRes.data)
setIsCloning(false)
} catch (err: any) {
console.error('Cloning failed:', err)
setError(err.response?.data?.message || 'Failed to clone voice. Please try again.')
setIsCloning(false)
}
}
const formatTime = (seconds: number) => {
const mins = Math.floor(seconds / 60)
const secs = seconds % 60
return `${mins}:${secs.toString().padStart(2, '0')}`
}
return (
<>
<Head>
<title>{getPageTitle('Instant Voice Cloning')}</title>
</Head>
<SectionMain>
<SectionTitleLineWithButton icon={mdiLightningBolt} title="Instant Voice Cloning" main>
{''}
</SectionTitleLineWithButton>
{error && (
<NotificationBar color="danger" icon={mdiStop} className="mb-6">
{error}
</NotificationBar>
)}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<CardBox>
<div className="mb-6">
<h2 className="text-xl font-bold mb-2">Step 1: Record Your Voice</h2>
<p className="text-gray-500 dark:text-slate-400">
Speak clearly for at least 10 seconds to get the best results.
</p>
</div>
<div className="flex flex-col items-center justify-center p-10 bg-gray-50 dark:bg-slate-800/50 rounded-3xl border-2 border-dashed border-gray-200 dark:border-slate-700">
{isRecording ? (
<div className="flex flex-col items-center">
<div className="w-20 h-20 bg-red-500 rounded-full flex items-center justify-center animate-pulse mb-4">
<BaseIcon path={mdiMicrophone} size={40} className="text-white" />
</div>
<div className="text-2xl font-mono mb-6">{formatTime(recordingTime)}</div>
<BaseButton
label="Stop Recording"
color="danger"
icon={mdiStop}
onClick={stopRecording}
roundedFull
/>
</div>
) : audioUrl ? (
<div className="flex flex-col items-center w-full">
<div className="w-20 h-20 bg-green-500 rounded-full flex items-center justify-center mb-4">
<BaseIcon path={mdiCheckCircle} size={40} className="text-white" />
</div>
<div className="text-lg font-medium mb-4">Recording Captured!</div>
<audio src={audioUrl} controls className="mb-6 w-full" />
<BaseButtons>
<BaseButton
label="Re-record"
color="white"
icon={mdiRefresh}
onClick={resetRecording}
/>
</BaseButtons>
</div>
) : (
<div className="flex flex-col items-center">
<div className="w-20 h-20 bg-blue-500 rounded-full flex items-center justify-center mb-6 cursor-pointer hover:scale-110 transition-transform" onClick={startRecording}>
<BaseIcon path={mdiMicrophone} size={40} className="text-white" />
</div>
<BaseButton
label="Start Recording"
color="info"
icon={mdiMicrophone}
onClick={startRecording}
roundedFull
/>
</div>
)}
</div>
</CardBox>
<CardBox>
<div className="mb-6">
<h2 className="text-xl font-bold mb-2">Step 2: Generate Clone</h2>
<p className="text-gray-500 dark:text-slate-400">
Give your voice a name and start the AI cloning process.
</p>
</div>
<FormField label="Voice Name" help="e.g. My Professional Voice">
<input
type="text"
placeholder="Enter voice title..."
className="w-full"
value={voiceTitle}
onChange={(e) => setVoiceTitle(e.target.value)}
disabled={isCloning || !!clonedModel}
/>
</FormField>
<div className="mt-8">
{!clonedModel ? (
<BaseButton
label={isCloning ? 'Cloning in progress...' : 'Start Instant Cloning'}
color="info"
icon={mdiLightningBolt}
className="w-full py-4 text-lg"
onClick={handleClone}
disabled={!audioBlob || isCloning || !voiceTitle}
/>
) : (
<div className="p-6 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-2xl">
<div className="flex items-center mb-4">
<BaseIcon path={mdiCheckCircle} className="text-green-500 mr-2" size={24} />
<h3 className="text-lg font-bold text-green-700 dark:text-green-400">Success! Voice Cloned</h3>
</div>
<p className="text-sm text-green-600 dark:text-green-500 mb-4">
Your voice model <strong>{clonedModel.title}</strong> is ready to use.
</p>
<BaseButtons>
<BaseButton
label="View My Models"
color="info"
href="/voice_models/voice_models-list"
/>
<BaseButton
label="Clone Another"
color="white"
onClick={resetRecording}
/>
</BaseButtons>
</div>
)}
</div>
{isCloning && (
<div className="mt-6">
<div className="flex justify-between mb-1">
<span className="text-sm font-medium text-blue-700 dark:text-blue-400">Processing Audio...</span>
<span className="text-sm font-medium text-blue-700 dark:text-blue-400">65%</span>
</div>
<div className="w-full bg-gray-200 rounded-full h-2.5 dark:bg-gray-700 overflow-hidden">
<div className="bg-blue-600 h-2.5 rounded-full animate-progress-buffer" style={{ width: '65%' }}></div>
</div>
</div>
)}
</CardBox>
</div>
</SectionMain>
</>
)
}
InstantCloningPage.getLayout = function getLayout(page: ReactElement) {
return <LayoutAuthenticated>{page}</LayoutAuthenticated>
}
export default InstantCloningPage