saima730 commited on
Commit
975a834
Β·
verified Β·
1 Parent(s): 46e7793

Create text_summary.py

Browse files
Files changed (1) hide show
  1. text_summary.py +53 -0
text_summary.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ !pip install streamlit langchain
2
+ import streamlit as st
3
+ import openai
4
+ from langchain.docstore.document import Document
5
+ from langchain.text_splitter import CharacterTextSplitter
6
+ from langchain.chains.summarize import load_summarize_chain
7
+
8
+ def generate_response(txt, openai_api_key):
9
+ try:
10
+ # Set up OpenAI API key
11
+ openai.api_key = openai_api_key
12
+
13
+ # Split text
14
+ text_splitter = CharacterTextSplitter()
15
+ texts = text_splitter.split_text(txt)
16
+
17
+ # Create multiple documents
18
+ docs = [Document(page_content=t) for t in texts]
19
+
20
+ # Text summarization using langchain's summarization chain
21
+ chain = load_summarize_chain(llm="openai", chain_type='map_reduce')
22
+ return chain.run(docs)
23
+ except Exception as e:
24
+ st.error(f"An error occurred during summarization: {str(e)}")
25
+ return None
26
+
27
+ # Page title
28
+ st.set_page_config(page_title='πŸ¦œπŸ”— Text Summarization App')
29
+ st.title('πŸ¦œπŸ”— Text Summarization App')
30
+
31
+ # Text input
32
+ txt_input = st.text_area('Enter your text', '', height=200)
33
+
34
+ # Form to accept user's text input for summarization
35
+ response = None
36
+ with st.form('summarize_form', clear_on_submit=True):
37
+ openai_api_key = st.text_input('OpenAI API Key', type='password', disabled=not txt_input)
38
+ submitted = st.form_submit_button('Submit')
39
+ if submitted and openai_api_key.startswith('sk-'):
40
+ with st.spinner('Calculating...'):
41
+ response = generate_response(txt_input, openai_api_key)
42
+
43
+ if response:
44
+ st.info(response)
45
+
46
+ # Instructions for getting an OpenAI API key
47
+ st.subheader("Get an OpenAI API key")
48
+ st.write("You can get your own OpenAI API key by following the instructions:")
49
+ st.write("""
50
+ 1. Go to [OpenAI API Keys](https://platform.openai.com/account/api-keys).
51
+ 2. Click on the `+ Create new secret key` button.
52
+ 3. Next, enter an identifier name (optional) and click on the `Create secret key` button.
53
+ """)