File size: 5,678 Bytes
991ca47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
"""
Test script for Quran Transcription API
Run this script to test the API endpoints
"""

import requests
import json
from pathlib import Path


BASE_URL = "http://localhost:8888"
SAMPLE_AUDIO = "sample_audio.mp3"  # Replace with your test audio file


def test_health_check():
    """Test health check endpoint"""
    print("\n" + "=" * 50)
    print("Testing Health Check Endpoint")
    print("=" * 50)
    
    # Test root endpoint
    response = requests.get(f"{BASE_URL}/")
    print(f"\nGET / => Status: {response.status_code}")
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))
    
    # Test health endpoint
    response = requests.get(f"{BASE_URL}/health")
    print(f"\nGET /health => Status: {response.status_code}")
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))


def test_transcription():
    """Test single file transcription"""
    print("\n" + "=" * 50)
    print("Testing Transcription Endpoint")
    print("=" * 50)
    
    if not Path(SAMPLE_AUDIO).exists():
        print(f"⚠️  Sample audio file '{SAMPLE_AUDIO}' not found.")
        print("   Please provide a test audio file to test transcription.")
        return
    
    with open(SAMPLE_AUDIO, "rb") as f:
        files = {"file": f}
        response = requests.post(f"{BASE_URL}/transcribe", files=files)
    
    print(f"\nPOST /transcribe => Status: {response.status_code}")
    
    if response.status_code == 200:
        result = response.json()
        print("\nTranscription Result:")
        print(f"  Text: {result.get('transcription', 'N/A')}")
        print(f"  Language: {result.get('language', 'N/A')}")
        print(f"  Confidence: {result.get('language_probability', 0):.2%}")
        print(f"  Processing Time: {result.get('processing_time', 0):.2f}s")
        
        segments = result.get('segments', [])
        if segments:
            print(f"\n  Segments ({len(segments)} total):")
            for i, seg in enumerate(segments[:3], 1):  # Show first 3
                print(f"    [{seg['start']:.2f}s - {seg['end']:.2f}s] {seg['text']}")
            if len(segments) > 3:
                print(f"    ... and {len(segments) - 3} more segments")
    else:
        print(f"Error: {response.json()}")


def test_batch_transcription():
    """Test batch file transcription"""
    print("\n" + "=" * 50)
    print("Testing Batch Transcription Endpoint")
    print("=" * 50)
    
    if not Path(SAMPLE_AUDIO).exists():
        print(f"⚠️  Sample audio file '{SAMPLE_AUDIO}' not found.")
        print("   Please provide test audio files to test batch transcription.")
        return
    
    with open(SAMPLE_AUDIO, "rb") as f:
        files = [
            ("files", (SAMPLE_AUDIO, f, "audio/mpeg"))
        ]
        response = requests.post(f"{BASE_URL}/transcribe-batch", files=files)
    
    print(f"\nPOST /transcribe-batch => Status: {response.status_code}")
    
    if response.status_code == 200:
        result = response.json()
        print(f"\nResults: {result['successful']}/{result['total_files']} successful")
        
        for item in result['results']:
            if item.get('success'):
                print(f"\n  ✓ {item['filename']}")
                print(f"    Processing time: {item['processing_time']:.2f}s")
                print(f"    Text: {item['transcription'][:100]}...")
            else:
                print(f"\n  ✗ {item['filename']}")
                print(f"    Error: {item.get('error', 'Unknown error')}")
    else:
        print(f"Error: {response.json()}")


def test_documentation():
    """Check if API documentation is available"""
    print("\n" + "=" * 50)
    print("Testing Documentation Endpoints")
    print("=" * 50)
    
    # Test Swagger UI
    response = requests.get(f"{BASE_URL}/docs")
    print(f"\nSwagger UI (GET /docs) => Status: {response.status_code}")
    if response.status_code == 200:
        print("  ✓ Swagger documentation available at /docs")
    
    # Test ReDoc
    response = requests.get(f"{BASE_URL}/redoc")
    print(f"\nReDoc (GET /redoc) => Status: {response.status_code}")
    if response.status_code == 200:
        print("  ✓ ReDoc documentation available at /redoc")
    
    # Test OpenAPI schema
    response = requests.get(f"{BASE_URL}/openapi.json")
    print(f"\nOpenAPI Schema (GET /openapi.json) => Status: {response.status_code}")
    if response.status_code == 200:
        schema = response.json()
        print(f"  ✓ OpenAPI schema available")
        print(f"    Paths: {len(schema.get('paths', {}))}")
        print(f"    Version: {schema.get('info', {}).get('version', 'N/A')}")


def main():
    """Run all tests"""
    print("\n" + "=" * 50)
    print("🧪 Quran Transcription API Test Suite")
    print("=" * 50)
    print(f"\nTesting endpoint: {BASE_URL}")
    
    try:
        # Test connectivity
        response = requests.get(f"{BASE_URL}/", timeout=5)
        if response.status_code != 200:
            print("✗ API is not responding correctly")
            return
        
        print("✓ API is reachable and responsive")
        
        # Run tests
        test_health_check()
        test_documentation()
        test_transcription()
        test_batch_transcription()
        
        print("\n" + "=" * 50)
        print("✅ Tests completed!")
        print("=" * 50)
        
    except requests.exceptions.ConnectionError:
        print(f"\n✗ Failed to connect to {BASE_URL}")
        print("  Make sure the API server is running:")
        print("  uvicorn main:app --reload")
    except Exception as e:
        print(f"\n✗ Test error: {e}")


if __name__ == "__main__":
    main()