Spaces:
Runtime error
Runtime error
| # Welcome to Cloud Functions for Firebase for Python! | |
| # To get started, simply uncomment the below code or create your own. | |
| # Deploy with `firebase deploy` | |
| from firebase_functions import https_fn | |
| from firebase_admin import initialize_app | |
| import io # Ensure this import is added to handle BytesIO | |
| import tempfile | |
| import os | |
| from backend.ai_processing.gpt import ai_language_detector | |
| from backend.ai_processing.transcription import transcribe_audio_file_with_language | |
| initialize_app() | |
| def detect_language(req: https_fn.Request) -> https_fn.Response: | |
| """ | |
| Cloud Function to detect language from an uploaded audio file. | |
| - Accepts POST requests with an audio file. | |
| - Validates the file format (assumes WAV for this example). | |
| - Reads the audio file content. | |
| - Transcribes the audio content and detects the language. | |
| - Returns the detected language as JSON. | |
| """ | |
| if req.method != 'POST': | |
| return https_fn.Response("Method Not Allowed", status=405) | |
| # Check if there is a file in the request | |
| if 'file' not in req.files: | |
| return https_fn.Response("No file part in the request", status=400) | |
| file = req.files['file'] | |
| # Enforce a specific file format here, e.g., WAV | |
| if not file or not file.filename or not file.filename.endswith(('.mp3', '.mp4', '.mpeg', '.mpga', '.m4a', '.wav', '.webm')): | |
| return https_fn.Response("File format not supported.", status=400) | |
| try: | |
| # Save the file to a temporary file | |
| with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.filename)[1]) as tmp_file: | |
| file_content = file.read() # Read file content | |
| tmp_file.write(file_content) # Write content to temporary file | |
| tmp_file_path = tmp_file.name # Get the path of the temporary file | |
| # Process the audio file and detect language | |
| transcription = transcribe_audio_file_with_language(tmp_file_path) | |
| # Clean up the temporary file | |
| os.remove(tmp_file_path) | |
| # Detect the language from the transcription | |
| predicted_language = ai_language_detector(transcription) | |
| if predicted_language is None: | |
| raise ValueError("Language could not be detected.") | |
| # Return the detected language as JSON | |
| return https_fn.Response(f"{predicted_language}", status=200, mimetype='application/json') | |
| except ValueError as e: | |
| # Handle specific errors, e.g., language not detected | |
| return https_fn.Response(f"Error: {str(e)}", status=400) | |
| except Exception as e: | |
| # Handle errors (e.g., transcription failure, unsupported audio format) | |
| return https_fn.Response(f"Error processing the audio file: {str(e)}", status=500) | |