rahul7star's picture
Update app.py
5966d25 verified
raw
history blame
2.53 kB
import gradio as gr
import requests
import os
# Load API URL and token from environment variables
API_URL = os.getenv("HF_API_URL", "https://api-inference.huggingface.co/models/your-model")
API_TOKEN = os.getenv("HF_API_TOKEN", "your-default-token") # Replace with your actual token for fallback
# Function to call the Hugging Face Inference API
def call_huggingface_api(input_text):
headers = {"Authorization": f"Bearer {API_TOKEN}"}
payload = {"inputs": input_text}
try:
print(f"Request sent to: {API_URL}")
print(f"Payload: {payload}")
response = requests.post(API_URL, headers=headers, json=payload)
print(f"Response Status Code: {response.status_code}")
if response.status_code == 200:
data = response.json()
print(f"Response Data: {data}")
# Assuming 'answer' and 'confidence' are the correct keys in the response JSON
return f"Question: {input_text}\nAnswer: {data.get('answer', 'No answer found.')}\nConfidence: {data.get('confidence', 'N/A')}"
else:
# Handle non-200 status codes and provide a detailed error message
error_message = f"Error: {response.status_code} - {response.text}"
print(f"Error Response: {error_message}")
return error_message
except requests.exceptions.RequestException as e:
# Catch network-related errors
error_message = f"Network error during API call: {e}"
print(error_message)
return error_message
except ValueError as e:
# Handle invalid JSON response
error_message = f"Error parsing response JSON: {e}"
print(error_message)
return error_message
except KeyError as e:
# Handle unexpected response structure or missing keys
error_message = f"KeyError: Missing expected key in response JSON: {e}"
print(error_message)
return error_message
except Exception as e:
# Handle any other unexpected errors
error_message = f"Unexpected error during API call: {e}"
print(error_message)
return error_message
# Gradio Interface
gr.Interface(
fn=call_huggingface_api,
inputs="text",
outputs="text",
examples=[
["Who is rahul7star?"],
["What does Rahul7star do?"],
["Tell me about Rahul7star"]
],
title="Ask Rahul7star AI",
description="Ask questions about rahul7star and get answers powered by Hugging Face Inference API."
).launch()