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85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
"""
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 (
    <div className="container">
      <h1>Quran Transcriber</h1>
      
      <form onSubmit={handleSubmit}>
        <input 
          type="file" 
          onChange={handleFileChange}
          accept="audio/*"
        />
        <button type="submit" disabled={loading}>
          {loading ? 'Transcribing...' : 'Transcribe'}
        </button>
      </form>

      {error && <div className="error">{error}</div>}

      {transcription && (
        <div className="results">
          <h2>Transcription</h2>
          <p>{transcription.transcription}</p>
          
          <h3>Details</h3>
          <ul>
            <li>Language: {transcription.language}</li>
            <li>Confidence: {(transcription.language_probability * 100).toFixed(2)}%</li>
            <li>Processing Time: {transcription.processing_time.toFixed(2)}s</li>
          </ul>

          <h3>Segments</h3>
          <ul>
            {transcription.segments.map((seg, idx) => (
              <li key={idx}>
                [{seg.start.toFixed(2)}s - {seg.end.toFixed(2)}s] {seg.text}
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}

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)")