pinge commited on
Commit
f7c1801
·
verified ·
1 Parent(s): ab7a845

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +94 -34
src/streamlit_app.py CHANGED
@@ -1,40 +1,100 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
 
13
- In the meantime, below is an example of what you can do with just a few lines of code:
 
 
14
  """
15
 
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import requests
3
+ import json
4
+ import os
5
+ from dotenv import load_dotenv
6
+ from langchain_community.document_loaders import WebBaseLoader
7
 
8
+ # Load environment variables from .env file
9
+ load_dotenv()
10
+
11
+ # Function to load the article/blog post from a URL
12
+ def load_text(url):
13
+ """Load the article/blog post from a URL"""
14
+ try:
15
+ loader = WebBaseLoader(url)
16
+ loader.requests_kwargs = {
17
+ 'verify': False,
18
+ 'headers': {'User-Agent': os.getenv('USER_AGENT', 'SummarizerBot/1.0 (https://your-site.com)')}
19
+ }
20
+ docs = loader.load()
21
+ return docs[0].page_content if docs else None # Extract text content
22
+ except Exception as e:
23
+ st.error(f"Error loading URL: {e}")
24
+ return None
25
+
26
+ # Function to summarize text using Gemma 3 27B via OpenRouter API
27
+ def summarize_text(url):
28
+ """Summarize the content from the given URL using Gemma 3 27B via OpenRouter API"""
29
+ text = load_text(url)
30
+ if not text:
31
+ return None
32
 
33
+ # Define the prompt for summarization
34
+ summary_prompt = f"""
35
+ 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.
36
 
37
+ TEXT: {text}
38
+
39
+ SUMMARY:
40
  """
41
 
42
+ try:
43
+ # Make API request to OpenRouter for summarization
44
+ response = requests.post(
45
+ url="https://openrouter.ai/api/v1/chat/completions",
46
+ headers={
47
+ "Authorization": f"Bearer {os.getenv('OPENROUTER_API_KEY')}",
48
+ "Content-Type": "application/json",
49
+ "HTTP-Referer": os.getenv('SITE_URL', '<YOUR_SITE_URL>'), # Optional, defaults to placeholder
50
+ "X-Title": os.getenv('SITE_NAME', '<YOUR_SITE_NAME>'), # Optional, defaults to placeholder
51
+ },
52
+ data=json.dumps({
53
+ "model": "google/gemma-3-27b-it:free",
54
+ "messages": [
55
+ {
56
+ "role": "user",
57
+ "content": [
58
+ {
59
+ "type": "text",
60
+ "text": summary_prompt
61
+ }
62
+ ]
63
+ }
64
+ ]
65
+ })
66
+ )
67
+
68
+ # Check if the request was successful
69
+ if response.status_code == 200:
70
+ result = response.json()
71
+ summary = result['choices'][0]['message']['content']
72
+ return summary.strip()
73
+ else:
74
+ st.error(f"API Error: {response.status_code} - {response.text}")
75
+ return None
76
+
77
+ except Exception as e:
78
+ st.error(f"Error summarizing content: {e}")
79
+ return None
80
+
81
+ # Streamlit app interface
82
+ st.title("Summarizer AI")
83
+ st.markdown("Enter a URL to summarize the content concisely")
84
+
85
+ with st.form(key='summarizer_form'):
86
+ url = st.text_area(
87
+ label="Enter the URL of the article or blog post:",
88
+ max_chars=250,
89
+ placeholder="https://example.com/article"
90
+ )
91
+ submit_button = st.form_submit_button(label="Summarize")
92
+
93
+ if submit_button and url:
94
+ with st.spinner("Summarizing..."):
95
+ summary = summarize_text(url)
96
+ if summary:
97
+ st.subheader("Summary")
98
+ st.write(summary)
99
+ else:
100
+ st.error("Unable to generate summary. Please check the URL or try again.")