File size: 3,476 Bytes
fbe0e88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import streamlit as st
import requests
import json
import os
from dotenv import load_dotenv
from langchain_community.document_loaders import WebBaseLoader

# Load environment variables from .env file
load_dotenv()

# Function to load the article/blog post from a URL
def load_text(url):
    """Load the article/blog post from a URL"""
    try:
        loader = WebBaseLoader(url)
        loader.requests_kwargs = {
            'verify': False,
            'headers': {'User-Agent': os.getenv('USER_AGENT', 'SummarizerBot/1.0 (https://your-site.com)')}
        }
        docs = loader.load()
        return docs[0].page_content if docs else None  # Extract text content
    except Exception as e:
        st.error(f"Error loading URL: {e}")
        return None

# Function to summarize text using Gemma 3 27B via OpenRouter API
def summarize_text(url):
    """Summarize the content from the given URL using Gemma 3 27B via OpenRouter API"""
    text = load_text(url)
    if not text:
        return None

    # Define the prompt for summarization
    summary_prompt = f"""

You are an expert summarizer. Your task is to create a concise summary of the following text. The summary should be no more than 7-8 sentences long.



TEXT: {text}



SUMMARY:

"""

    try:
        # Make API request to OpenRouter for summarization
        response = requests.post(
            url="https://openrouter.ai/api/v1/chat/completions",
            headers={
                "Authorization": f"Bearer {os.getenv('OPENROUTER_API_KEY')}",
                "Content-Type": "application/json",
                "HTTP-Referer": os.getenv('SITE_URL', '<YOUR_SITE_URL>'),  # Optional, defaults to placeholder
                "X-Title": os.getenv('SITE_NAME', '<YOUR_SITE_NAME>'),  # Optional, defaults to placeholder
            },
            data=json.dumps({
                "model": "google/gemma-3-27b-it:free",
                "messages": [
                    {
                        "role": "user",
                        "content": [
                            {
                                "type": "text",
                                "text": summary_prompt
                            }
                        ]
                    }
                ]
            })
        )

        # Check if the request was successful
        if response.status_code == 200:
            result = response.json()
            summary = result['choices'][0]['message']['content']
            return summary.strip()
        else:
            st.error(f"API Error: {response.status_code} - {response.text}")
            return None

    except Exception as e:
        st.error(f"Error summarizing content: {e}")
        return None

# Streamlit app interface
st.title("Summarizer AI")
st.markdown("Enter a URL to summarize the content concisely")

with st.form(key='summarizer_form'):
    url = st.text_area(
        label="Enter the URL of the article or blog post:",
        max_chars=250,
        placeholder="https://example.com/article"
    )
    submit_button = st.form_submit_button(label="Summarize")

if submit_button and url:
    with st.spinner("Summarizing..."):
        summary = summarize_text(url)
        if summary:
            st.subheader("Summary")
            st.write(summary)
        else:
            st.error("Unable to generate summary. Please check the URL or try again.")