File size: 2,528 Bytes
2fb4096
 
 
 
 
 
5966d25
cda1e78
2fb4096
 
 
 
 
cda1e78
 
5966d25
 
 
cda1e78
5966d25
2fb4096
 
5966d25
 
2fb4096
 
5966d25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fb4096
5966d25
 
 
 
 
2fb4096
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()