Download api_helper.py from abanm/Frontend: direct link, hf CLI and curl.
- Browser
- Download file 1.55 kB
-
https://huggingface.co/spaces/abanm/Frontend/resolve/main/api_helper.py
- Command line
-
hf download hf://spaces/abanm/Frontend/api_helper.py
-
curl -L -o api_helper.py https://huggingface.co/spaces/abanm/Frontend/resolve/main/api_helper.py
1.55 kB
| import requests | |
| import json | |
| # Constants | |
| SPACE_URL = "https://abanm-dubs.hf.space/api/generate" | |
| API_KEY = "s3cr3t_k3y" # Replace with your actual API key | |
| def call_api(message): | |
| """ | |
| Calls the backend API with the user's input using streaming. | |
| Args: | |
| message (str): User's message. | |
| Returns: | |
| str: Streamed response from the backend API or an error message. | |
| """ | |
| headers = { | |
| "Authorization": f"Bearer {API_KEY}", | |
| "Content-Type": "application/json", | |
| } | |
| payload = {"prompt": message} # Match the API's expected input key | |
| try: | |
| # Send request with streaming enabled | |
| response = requests.post(SPACE_URL, json=payload, headers=headers, stream=True) | |
| response.raise_for_status() | |
| # Aggregate streamed response | |
| bot_response = "" | |
| for chunk in response.iter_lines(decode_unicode=True): | |
| if chunk.strip(): # Ensure the chunk is not empty | |
| try: | |
| # Parse JSON chunk | |
| data = json.loads(chunk) | |
| if "response" in data: | |
| bot_response += data["response"] | |
| except json.JSONDecodeError: | |
| bot_response += "\nError decoding response chunk." | |
| return bot_response.strip() if bot_response else "Error: No response from API." | |
| except requests.exceptions.Timeout: | |
| return "Error: The API call timed out." | |
| except requests.exceptions.RequestException as e: | |
| return f"Error: {str(e)}" |