""" Client Examples for Quran Transcription API This file contains example code for different programming languages to interact with the Quran Transcription API. """ # ============================================================================ # PYTHON EXAMPLES # ============================================================================ # Example 1: Simple Transcription with Requests def python_simple_transcription(): import requests with open("audio.mp3", "rb") as f: files = {"file": f} response = requests.post( "http://localhost:8888/transcribe", files=files ) result = response.json() print(f"Transcription: {result['transcription']}") print(f"Confidence: {result['language_probability']:.2%}") print(f"Processing time: {result['processing_time']:.2f}s") for segment in result['segments']: print(f"[{segment['start']:.2f}s - {segment['end']:.2f}s] {segment['text']}") # Example 2: Batch Transcription def python_batch_transcription(): import requests from pathlib import Path audio_files = Path(".").glob("*.mp3") with requests.post( "http://localhost:8888/transcribe-batch", files=[("files", open(f, "rb")) for f in audio_files] ) as response: result = response.json() for item in result['results']: if item['success']: print(f"✓ {item['filename']}: {item['transcription'][:100]}...") else: print(f"✗ {item['filename']}: {item['error']}") # Example 3: Async Client with AsyncIO async def python_async_transcription(): import aiohttp import asyncio async with aiohttp.ClientSession() as session: with open("audio.mp3", "rb") as f: data = aiohttp.FormData() data.add_field('file', f, filename='audio.mp3') async with session.post( "http://localhost:8888/transcribe", data=data ) as response: result = await response.json() return result # Example 4: Using httpx with async async def python_httpx_transcription(): import httpx async with httpx.AsyncClient() as client: with open("audio.mp3", "rb") as f: response = await client.post( "http://localhost:8888/transcribe", files={"file": f} ) return response.json() # ============================================================================ # JAVASCRIPT/NODE.JS EXAMPLES # ============================================================================ javascript_simple = """ // Example 1: Simple Transcription with Fetch async function transcribeAudio(audioFile) { const formData = new FormData(); formData.append('file', audioFile); const response = await fetch('http://localhost:8888/transcribe', { method: 'POST', body: formData }); const result = await response.json(); console.log('Transcription:', result.transcription); console.log('Language Probability:', result.language_probability); console.log('Processing Time:', result.processing_time, 'seconds'); // Display segments result.segments.forEach(segment => { console.log(`[${segment.start.toFixed(2)}s - ${segment.end.toFixed(2)}s] ${segment.text}`); }); return result; } // Usage document.getElementById('uploadBtn').addEventListener('click', async (e) => { const file = document.getElementById('audioFile').files[0]; const result = await transcribeAudio(file); }); """ javascript_axios = """ // Example 2: Using Axios const axios = require('axios'); const FormData = require('form-data'); const fs = require('fs'); async function transcribeWithAxios(audioFilePath) { const form = new FormData(); form.append('file', fs.createReadStream(audioFilePath)); try { const response = await axios.post( 'http://localhost:8888/transcribe', form, { headers: form.getHeaders() } ); console.log('Result:', response.data); return response.data; } catch (error) { console.error('Error:', error.response?.data || error.message); } } // Usage transcribeWithAxios('./audio.mp3'); """ javascript_batch = """ // Example 3: Batch Upload async function batchTranscribe(audioFiles) { const formData = new FormData(); audioFiles.forEach(file => { formData.append('files', file); }); const response = await fetch('http://localhost:8888/transcribe-batch', { method: 'POST', body: formData }); const results = await response.json(); console.log(`Successful: ${results.successful}/${results.total_files}`); results.results.forEach(item => { if (item.success) { console.log(`✓ ${item.filename}: ${item.transcription}`); } else { console.log(`✗ ${item.filename}: ${item.error}`); } }); return results; } """ # ============================================================================ # CURL EXAMPLES # ============================================================================ curl_examples = """ # Single File Transcription curl -X POST \\ -F "file=@audio.mp3" \\ http://localhost:8888/transcribe | jq . # Batch Transcription curl -X POST \\ -F "files=@audio1.mp3" \\ -F "files=@audio2.wav" \\ http://localhost:8888/transcribe-batch | jq . # Health Check curl http://localhost:8888/health | jq . # With API Key (if implemented) curl -H "Authorization: Bearer YOUR_API_KEY" \\ -F "file=@audio.mp3" \\ http://localhost:8888/transcribe | jq . # Save response to file curl -X POST \\ -F "file=@audio.mp3" \\ http://localhost:8888/transcribe \\ -o result.json # Pretty print response curl -X POST \\ -F "file=@audio.mp3" \\ http://localhost:8888/transcribe \\ -s | python -m json.tool """ # ============================================================================ # REACT EXAMPLE # ============================================================================ react_example = """ import React, { useState } from 'react'; import axios from 'axios'; function QuranTranscriber() { const [file, setFile] = useState(null); const [transcription, setTranscription] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const handleFileChange = (e) => { setFile(e.target.files[0]); }; const handleSubmit = async (e) => { e.preventDefault(); if (!file) { setError('Please select a file'); return; } const formData = new FormData(); formData.append('file', file); setLoading(true); setError(null); try { const response = await axios.post( 'http://localhost:8888/transcribe', formData, { headers: { 'Content-Type': 'multipart/form-data' }, onUploadProgress: (progressEvent) => { const percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total ); console.log(`Upload progress: ${percentCompleted}%`); } } ); setTranscription(response.data); } catch (err) { setError(err.response?.data?.detail || 'Transcription failed'); } finally { setLoading(false); } }; return (

Quran Transcriber

{error &&
{error}
} {transcription && (

Transcription

{transcription.transcription}

Details

Segments

)}
); } export default QuranTranscriber; """ # ============================================================================ # PYTHON STREAMING EXAMPLE # ============================================================================ python_streaming = """ import requests from pathlib import Path def transcribe_with_streaming(audio_file_path, chunk_size=1024*1024): ''' Transcribe audio file with progress streaming ''' file_size = Path(audio_file_path).stat().st_size with open(audio_file_path, 'rb') as f: # Create a progress callback def progress_callback(monitor): bytes_read = monitor.bytes_read progress = (bytes_read / file_size) * 100 print(f'Upload progress: {progress:.1f}%') # Use requests-toolbelt for progress from requests_toolbelt import MultipartEncoder, MultipartEncoderMonitor fields = { 'file': (Path(audio_file_path).name, f, 'audio/mpeg') } m = MultipartEncoder(fields=fields) monitor = MultipartEncoderMonitor( m, callback=progress_callback ) response = requests.post( 'http://localhost:8888/transcribe', data=monitor, headers={'Content-Type': monitor.content_type} ) return response.json() """ # ============================================================================ # POSTMAN COLLECTION # ============================================================================ postman_collection = """{ "info": { "name": "Quran Transcription API", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" }, "item": [ { "name": "Health Check", "request": { "method": "GET", "url": "http://localhost:8888/health" } }, { "name": "Transcribe Single File", "request": { "method": "POST", "url": "http://localhost:8888/transcribe", "body": { "mode": "formdata", "formdata": [ { "key": "file", "type": "file", "src": "/path/to/audio.mp3" } ] } } }, { "name": "Transcribe Batch", "request": { "method": "POST", "url": "http://localhost:8888/transcribe-batch", "body": { "mode": "formdata", "formdata": [ { "key": "files", "type": "file", "src": ["/path/to/audio1.mp3", "/path/to/audio2.wav"] } ] } } } ] } """ if __name__ == "__main__": print("=" * 60) print("QURAN TRANSCRIPTION API - CLIENT EXAMPLES") print("=" * 60) print("\nSee code comments for various implementation examples.") print("\nQuick Examples:") print("\n1. Python with Requests:") print(" python_simple_transcription()") print("\n2. Curl:") print(" curl -F 'file=@audio.mp3' http://localhost:8888/transcribe") print("\n3. JavaScript Fetch:") print(" transcribeAudio(audioFile)")