File size: 2,613 Bytes
476b9b5
 
 
 
 
 
6037530
476b9b5
4f93309
 
 
476b9b5
 
 
5fc6e34
 
476b9b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f93309
 
476b9b5
4f93309
476b9b5
 
 
4f93309
476b9b5
 
 
4f93309
476b9b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f93309
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import os
import gradio as gr
import requests
from newspaper import Article
import time
from langdetect import detect
import nltk

# Download the 'punkt' tokenizer
nltk.download('punkt')

# Load environment variables from .env file
API_KEY = os.getenv('API_KEY')

print(f"API_KEY: {'Loaded' if API_KEY else 'Not Loaded'}")

# Ensure the API key is loaded
if not API_KEY:
    raise ValueError("API_KEY is missing. Please set it in the secret variables in the Hugging Face Spaces settings.")

# Define the Hugging Face API URL
API_URL = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"

# Set up headers for the API request
headers = {"Authorization": f"Bearer {API_KEY}"}

# Function to query the Hugging Face API
def query(payload):
    for _ in range(5):  # Try 5 times
        response = requests.post(API_URL, headers=headers, json=payload)
        result = response.json()
        if 'error' in result and 'currently loading' in result['error']:
            time.sleep(5)  # Wait for 5 seconds before retrying
        else:
            return result
    return {"error": "Model is still loading. Please try again later."}

# Function to summarize text
def summarize(text, minL=20, maxL=300):
    output = query({
        "inputs": text,
        "parameters": {
            "min_length": minL,
            "max_length": maxL
        }
    })
    if "error" in output:
        return f"Error: {output['error']}"
    if not isinstance(output, list) or not output:
        return "Error: Unexpected response format."
    if "summary_text" not in output[0]:
        return "Error: 'summary_text' key not found in the response."
    return output[0]['summary_text']

def Choices(choice, input_text, minL, maxL):
    if choice == "URL":
        try:
            article = Article(input_text, language="en")
            article.download()
            article.parse()
            article.nlp()
            text = article.text
        except Exception as e:
            return f"Error: Unable to fetch article. {str(e)}"
    else:
        text = input_text
    return summarize(text, minL, maxL)

# Create Gradio interface
demo = gr.Interface(
    fn=Choices,
    inputs=[
        gr.Radio(choices=["URL", "Paragraph"], label="Input Type", value="URL"),
        gr.Textbox(lines=10, placeholder="Enter text here..."),
        gr.Number(value=20, label="Minimum Length"),
        gr.Number(value=300, label="Maximum Length"),
    ],
    outputs="textbox",
    title="Text Summarizer",
    description="Enter text to summarize using Hugging Face BART model."
)

# Launch the interface
demo.launch()