|
|
import requests |
|
|
import json |
|
|
|
|
|
|
|
|
SPACE_URL = "https://abanm-dubs.hf.space/api/generate" |
|
|
API_KEY = "s3cr3t_k3y" |
|
|
|
|
|
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} |
|
|
|
|
|
try: |
|
|
|
|
|
response = requests.post(SPACE_URL, json=payload, headers=headers, stream=True) |
|
|
response.raise_for_status() |
|
|
|
|
|
|
|
|
bot_response = "" |
|
|
for chunk in response.iter_lines(decode_unicode=True): |
|
|
if chunk.strip(): |
|
|
try: |
|
|
|
|
|
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)}" |