forked from neuromindlabs/TalkBriefAI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp1.py
192 lines (158 loc) · 6.68 KB
/
app1.py
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import validators, streamlit as st
from langchain.prompts import PromptTemplate
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain.chains.summarize import load_summarize_chain
from langchain_community.document_loaders import YoutubeLoader, UnstructuredURLLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.llms import openai
import tiktoken
from langchain.chains import LLMChain
import urllib3
import nltk
nltk.download("punkt") # Download the punkt tokenizer
# Try to download punkt_tab as well, though it may not be necessary
nltk.download("punkt_tab")
nltk.download("averaged_perceptron_tagger")
# Suppress SSL warnings (temporary solution)
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
st.set_page_config(page_title="Talk-Brief AI", page_icon="👴")
st.title("👴 Talk-Brief AI: Interact with YT or Website")
st.subheader("Get an Overview of URL")
with st.sidebar:
google_api_key = st.text_input("Google API Key", value="", type="password")
if st.button("Get your Google API Key"):
st.write("Go to Google AI Studio...")
st.markdown(
"[Click here to go to Google AI Studio](https://ai.google.dev/aistudio)"
)
llm = ChatGoogleGenerativeAI(
model="gemini-1.5-flash",
verbose=True,
temperature=0.5,
google_api_key=google_api_key,
)
def calculate_tokens(text):
encoding = tiktoken.encoding_for_model("gpt-3.5-turbo")
token_count = len(encoding.encode(text))
return token_count
def stuff_chain(docs):
prompt_template = """
Provide a summary of the following content in 300 words:
Content:{text}
"""
prompt = PromptTemplate(template=prompt_template, input_variables=["text"])
chain = load_summarize_chain(llm, chain_type="stuff", prompt=prompt)
output_summary = chain.run(docs)
return output_summary
def map_reduce(docs):
final_documents = RecursiveCharacterTextSplitter(
chunk_size=2000, chunk_overlap=100
).split_documents(docs)
chunks_prompt = """
Please summarize the below speech:
Speech:`{text}'
Summary:
"""
map_prompt_template = PromptTemplate(
input_variables=["text"], template=chunks_prompt
)
final_prompt = """
Provide the final summary of the entire speech with these important points.
Add a Motivation Title, Start the precise summary with an introduction, and provide the summary in numbered
points for the speech.
Speech:{text}
"""
final_prompt_template = PromptTemplate(
input_variables=["text"], template=final_prompt
)
summary_chain = load_summarize_chain(
llm=llm,
chain_type="map_reduce",
map_prompt=map_prompt_template,
combine_prompt=final_prompt_template,
verbose=True,
)
output_summary = summary_chain.run(final_documents)
return output_summary
def refine(docs):
final_documents = RecursiveCharacterTextSplitter(
chunk_size=2000, chunk_overlap=100
).split_documents(docs)
chain = load_summarize_chain(llm=llm, chain_type="refine", verbose=True)
output_summary = chain.run(final_documents)
final_prompt = f"""
Provide the final summary of the entire speech with these important points.
Add a Title, start the precise summary with an introduction and provide the summary in numbered
points for the speech.
Speech: {output_summary}
"""
prompt_template = PromptTemplate(input_variables=["summary"], template=final_prompt)
chain = LLMChain(llm=llm, prompt=prompt_template)
final_output = chain.run({"summary": output_summary})
return final_output
generic_url = st.text_input("URL", label_visibility="collapsed")
if generic_url:
if not validators.url(generic_url):
st.error("Please enter a valid URL. It can be a YT video URL or website URL")
else:
try:
with st.spinner("Analyzing the content..."):
if "youtube.com" in generic_url:
loader = YoutubeLoader.from_youtube_url(
generic_url, add_video_info=True
)
else:
loader = UnstructuredURLLoader(
urls=[generic_url],
ssl_verify=False,
headers={
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 13_5_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
},
)
docs = loader.load()
token_count = calculate_tokens(str(docs))
st.info(f"Total Tokens: {token_count}")
if token_count < 1000:
suggested_type = "Stuffchain"
elif 1000 <= token_count < 3000:
suggested_type = "Map-reduce"
else:
suggested_type = "Refine"
st.info(f"Suggested Summarization Type: {suggested_type}")
summarization_type = st.selectbox(
"Select Summarization Type",
["Stuffchain", "Map-reduce", "Refine"],
index=["Stuffchain", "Map-reduce", "Refine"].index(suggested_type),
)
except Exception as e:
st.exception(f"Exception: {e}")
if st.button("Get an overview of the Content from YT or Website"):
if not google_api_key.strip() or not generic_url.strip():
st.error("Please provide the information to get started")
elif not validators.url(generic_url):
st.error("Please enter a valid URL. It can be a YT video URL or website URL")
else:
try:
with st.spinner("Summarizing..."):
if "youtube.com" in generic_url:
loader = YoutubeLoader.from_youtube_url(
generic_url, add_video_info=True
)
else:
loader = UnstructuredURLLoader(
urls=[generic_url],
ssl_verify=False,
headers={
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 13_5_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
},
)
docs = loader.load()
if summarization_type == "Stuffchain":
output_summary = stuff_chain(docs)
elif summarization_type == "Map-reduce":
output_summary = map_reduce(docs)
else:
output_summary = refine(docs)
st.success(output_summary)
except Exception as e:
st.exception(f"Exception: {e}")