Spaces:
Sleeping
Sleeping
Akshay Kumar BM commited on
Commit ·
3602229
1
Parent(s): 1e68cb4
Add files via upload
Browse files- app.py +5 -50
- requirements.txt +1 -0
app.py
CHANGED
|
@@ -9,49 +9,31 @@ from langchain.schema import Document
|
|
| 9 |
import os
|
| 10 |
import tempfile
|
| 11 |
from dotenv import load_dotenv
|
| 12 |
-
|
| 13 |
load_dotenv()
|
| 14 |
|
| 15 |
-
os.environ['LANGCHAIN_API_KEY']=os.getenv("LANGCHAIN_API_KEY")
|
| 16 |
-
os.environ['LANGCHAIN_TRACING_V2']="true"
|
| 17 |
-
os.environ['LANGCHAIN_PROJECT']="LangChain: Process Content from Multiple Sources"
|
| 18 |
os.environ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com"
|
| 19 |
|
| 20 |
st.set_page_config(page_title="LangChain: Process Content from Multiple Sources", page_icon="🦜")
|
| 21 |
st.title("🦜 LangChain: Process Content from Multiple Sources")
|
| 22 |
|
| 23 |
-
# Initialize session state for PDF page ranges
|
| 24 |
if 'pdf_page_ranges' not in st.session_state:
|
| 25 |
st.session_state.pdf_page_ranges = {}
|
| 26 |
|
| 27 |
-
# Function to count tokens
|
| 28 |
-
def count_tokens(text, model="gpt-3.5-turbo"):
|
| 29 |
-
encoding = tiktoken.encoding_for_model(model)
|
| 30 |
-
return len(encoding.encode(text))
|
| 31 |
-
|
| 32 |
-
# Function to estimate cost
|
| 33 |
-
def estimate_cost(total_tokens, model):
|
| 34 |
-
pricing = {
|
| 35 |
-
"llama3-8b-8192": 0.05,
|
| 36 |
-
"gemma2-9b-it": 0.05,
|
| 37 |
-
"mixtral-8x7b-32768": 0.10
|
| 38 |
-
}
|
| 39 |
-
return (total_tokens / 1000) * pricing[model]
|
| 40 |
-
|
| 41 |
-
# Function to calculate optimal chunk size
|
| 42 |
def calculate_chunk_size(text_length, model_context_length):
|
| 43 |
target_chunk_size = model_context_length // 3
|
| 44 |
return max(1000, min(target_chunk_size, model_context_length // 2))
|
| 45 |
|
| 46 |
-
# Sidebar for API key input and PDF page selection
|
| 47 |
with st.sidebar:
|
| 48 |
st.header("Configuration")
|
| 49 |
groq_api_key = st.text_input("Groq API Key", type="password")
|
| 50 |
-
model = st.selectbox("Select Model", ["llama3-8b-8192","gemma2-9b-it", "mixtral-8x7b-32768"])
|
| 51 |
|
| 52 |
st.header("PDF Settings")
|
| 53 |
|
| 54 |
-
# Main content
|
| 55 |
st.subheader('Select Sources to Process')
|
| 56 |
use_urls = st.checkbox("URLs (YouTube or websites)")
|
| 57 |
use_files = st.checkbox("File Upload (PDF or text files)")
|
|
@@ -67,7 +49,6 @@ if use_files:
|
|
| 67 |
if uploaded_files:
|
| 68 |
sources['files'] = uploaded_files
|
| 69 |
|
| 70 |
-
# PDF page range selection
|
| 71 |
for uploaded_file in uploaded_files:
|
| 72 |
if uploaded_file.type == "application/pdf":
|
| 73 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
|
|
@@ -78,10 +59,8 @@ if use_files:
|
|
| 78 |
pdf_pages = loader.load()
|
| 79 |
total_pages = len(pdf_pages)
|
| 80 |
|
| 81 |
-
# Use the file name as a unique key for session state
|
| 82 |
file_key = f"pdf_range_{uploaded_file.name}"
|
| 83 |
|
| 84 |
-
# Initialize the range in session state if it doesn't exist
|
| 85 |
if file_key not in st.session_state.pdf_page_ranges:
|
| 86 |
st.session_state.pdf_page_ranges[file_key] = (1, total_pages)
|
| 87 |
|
|
@@ -100,13 +79,11 @@ if use_files:
|
|
| 100 |
st.write("This PDF has only one page.")
|
| 101 |
st.session_state.pdf_page_ranges[file_key] = (1, 1)
|
| 102 |
|
| 103 |
-
# Clean up the temporary file
|
| 104 |
os.unlink(temp_file_path)
|
| 105 |
|
| 106 |
if use_text:
|
| 107 |
sources['text'] = st.text_area("Enter text content", placeholder="Paste your text here...")
|
| 108 |
|
| 109 |
-
# Predefined actions
|
| 110 |
predefined_actions = [
|
| 111 |
"Summarize", "Analyze", "Review", "Critique", "Explain",
|
| 112 |
"Paraphrase", "Simplify", "Elaborate", "Extract key points",
|
|
@@ -115,7 +92,6 @@ predefined_actions = [
|
|
| 115 |
"Fact-check", "Create study notes", "Generate questions"
|
| 116 |
]
|
| 117 |
|
| 118 |
-
# Action selection
|
| 119 |
action_type = st.radio("Choose action type", ["Predefined", "Custom"])
|
| 120 |
|
| 121 |
if action_type == "Predefined":
|
|
@@ -123,7 +99,6 @@ if action_type == "Predefined":
|
|
| 123 |
else:
|
| 124 |
action = st.text_input("Enter Custom Action", placeholder="e.g., Summarize in bullet points")
|
| 125 |
|
| 126 |
-
# Templates
|
| 127 |
prompt_template = """
|
| 128 |
Provide a {action} of the following content:
|
| 129 |
|
|
@@ -145,7 +120,6 @@ Refined {action}:
|
|
| 145 |
prompt = PromptTemplate(input_variables=['text', 'action'], template=prompt_template)
|
| 146 |
refine_prompt = PromptTemplate(input_variables=['text', 'action', 'existing_answer'], template=refine_template)
|
| 147 |
|
| 148 |
-
# Process button
|
| 149 |
if st.button("Process Content"):
|
| 150 |
if not groq_api_key.strip():
|
| 151 |
st.error("Please provide your Groq API key in the sidebar.")
|
|
@@ -158,7 +132,6 @@ if st.button("Process Content"):
|
|
| 158 |
llm = ChatGroq(model=model, groq_api_key=groq_api_key)
|
| 159 |
|
| 160 |
all_docs = []
|
| 161 |
-
total_tokens = 0
|
| 162 |
|
| 163 |
with st.spinner(f"Processing... ({action.lower()})"):
|
| 164 |
if 'urls' in sources and sources['urls']:
|
|
@@ -245,16 +218,6 @@ if st.button("Process Content"):
|
|
| 245 |
else:
|
| 246 |
split_docs.extend(text_splitter.split_documents([doc]))
|
| 247 |
|
| 248 |
-
for doc in split_docs:
|
| 249 |
-
total_tokens += count_tokens(doc.page_content)
|
| 250 |
-
|
| 251 |
-
total_tokens += count_tokens(prompt_template) * len(split_docs)
|
| 252 |
-
total_tokens += count_tokens(refine_template) * (len(split_docs) - 1)
|
| 253 |
-
|
| 254 |
-
estimated_cost = estimate_cost(total_tokens, model)
|
| 255 |
-
|
| 256 |
-
st.info(f"Estimated cost for processing: ${estimated_cost:.4f}")
|
| 257 |
-
|
| 258 |
chain = load_summarize_chain(
|
| 259 |
llm=llm,
|
| 260 |
chain_type="refine",
|
|
@@ -264,18 +227,10 @@ if st.button("Process Content"):
|
|
| 264 |
|
| 265 |
output = chain.run(input_documents=split_docs, action=action.lower())
|
| 266 |
|
| 267 |
-
output_tokens = count_tokens(output)
|
| 268 |
-
total_tokens += output_tokens
|
| 269 |
-
|
| 270 |
-
final_cost = estimate_cost(total_tokens, model)
|
| 271 |
-
|
| 272 |
st.success("Processing complete!")
|
| 273 |
st.subheader(f"{action} Result")
|
| 274 |
st.write(output)
|
| 275 |
|
| 276 |
-
st.info(f"Total tokens processed: {total_tokens}")
|
| 277 |
-
st.info(f"Final cost for processing: ${final_cost:.4f}")
|
| 278 |
-
|
| 279 |
except Exception as e:
|
| 280 |
st.error(f"An error occurred: {str(e)}")
|
| 281 |
|
|
|
|
| 9 |
import os
|
| 10 |
import tempfile
|
| 11 |
from dotenv import load_dotenv
|
| 12 |
+
|
| 13 |
load_dotenv()
|
| 14 |
|
| 15 |
+
os.environ['LANGCHAIN_API_KEY'] = os.getenv("LANGCHAIN_API_KEY")
|
| 16 |
+
os.environ['LANGCHAIN_TRACING_V2'] = "true"
|
| 17 |
+
os.environ['LANGCHAIN_PROJECT'] = "LangChain: Process Content from Multiple Sources"
|
| 18 |
os.environ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com"
|
| 19 |
|
| 20 |
st.set_page_config(page_title="LangChain: Process Content from Multiple Sources", page_icon="🦜")
|
| 21 |
st.title("🦜 LangChain: Process Content from Multiple Sources")
|
| 22 |
|
|
|
|
| 23 |
if 'pdf_page_ranges' not in st.session_state:
|
| 24 |
st.session_state.pdf_page_ranges = {}
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
def calculate_chunk_size(text_length, model_context_length):
|
| 27 |
target_chunk_size = model_context_length // 3
|
| 28 |
return max(1000, min(target_chunk_size, model_context_length // 2))
|
| 29 |
|
|
|
|
| 30 |
with st.sidebar:
|
| 31 |
st.header("Configuration")
|
| 32 |
groq_api_key = st.text_input("Groq API Key", type="password")
|
| 33 |
+
model = st.selectbox("Select Model", ["llama3-8b-8192", "gemma2-9b-it", "mixtral-8x7b-32768"])
|
| 34 |
|
| 35 |
st.header("PDF Settings")
|
| 36 |
|
|
|
|
| 37 |
st.subheader('Select Sources to Process')
|
| 38 |
use_urls = st.checkbox("URLs (YouTube or websites)")
|
| 39 |
use_files = st.checkbox("File Upload (PDF or text files)")
|
|
|
|
| 49 |
if uploaded_files:
|
| 50 |
sources['files'] = uploaded_files
|
| 51 |
|
|
|
|
| 52 |
for uploaded_file in uploaded_files:
|
| 53 |
if uploaded_file.type == "application/pdf":
|
| 54 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
|
|
|
|
| 59 |
pdf_pages = loader.load()
|
| 60 |
total_pages = len(pdf_pages)
|
| 61 |
|
|
|
|
| 62 |
file_key = f"pdf_range_{uploaded_file.name}"
|
| 63 |
|
|
|
|
| 64 |
if file_key not in st.session_state.pdf_page_ranges:
|
| 65 |
st.session_state.pdf_page_ranges[file_key] = (1, total_pages)
|
| 66 |
|
|
|
|
| 79 |
st.write("This PDF has only one page.")
|
| 80 |
st.session_state.pdf_page_ranges[file_key] = (1, 1)
|
| 81 |
|
|
|
|
| 82 |
os.unlink(temp_file_path)
|
| 83 |
|
| 84 |
if use_text:
|
| 85 |
sources['text'] = st.text_area("Enter text content", placeholder="Paste your text here...")
|
| 86 |
|
|
|
|
| 87 |
predefined_actions = [
|
| 88 |
"Summarize", "Analyze", "Review", "Critique", "Explain",
|
| 89 |
"Paraphrase", "Simplify", "Elaborate", "Extract key points",
|
|
|
|
| 92 |
"Fact-check", "Create study notes", "Generate questions"
|
| 93 |
]
|
| 94 |
|
|
|
|
| 95 |
action_type = st.radio("Choose action type", ["Predefined", "Custom"])
|
| 96 |
|
| 97 |
if action_type == "Predefined":
|
|
|
|
| 99 |
else:
|
| 100 |
action = st.text_input("Enter Custom Action", placeholder="e.g., Summarize in bullet points")
|
| 101 |
|
|
|
|
| 102 |
prompt_template = """
|
| 103 |
Provide a {action} of the following content:
|
| 104 |
|
|
|
|
| 120 |
prompt = PromptTemplate(input_variables=['text', 'action'], template=prompt_template)
|
| 121 |
refine_prompt = PromptTemplate(input_variables=['text', 'action', 'existing_answer'], template=refine_template)
|
| 122 |
|
|
|
|
| 123 |
if st.button("Process Content"):
|
| 124 |
if not groq_api_key.strip():
|
| 125 |
st.error("Please provide your Groq API key in the sidebar.")
|
|
|
|
| 132 |
llm = ChatGroq(model=model, groq_api_key=groq_api_key)
|
| 133 |
|
| 134 |
all_docs = []
|
|
|
|
| 135 |
|
| 136 |
with st.spinner(f"Processing... ({action.lower()})"):
|
| 137 |
if 'urls' in sources and sources['urls']:
|
|
|
|
| 218 |
else:
|
| 219 |
split_docs.extend(text_splitter.split_documents([doc]))
|
| 220 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
chain = load_summarize_chain(
|
| 222 |
llm=llm,
|
| 223 |
chain_type="refine",
|
|
|
|
| 227 |
|
| 228 |
output = chain.run(input_documents=split_docs, action=action.lower())
|
| 229 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
st.success("Processing complete!")
|
| 231 |
st.subheader(f"{action} Result")
|
| 232 |
st.write(output)
|
| 233 |
|
|
|
|
|
|
|
|
|
|
| 234 |
except Exception as e:
|
| 235 |
st.error(f"An error occurred: {str(e)}")
|
| 236 |
|
requirements.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Hello World!
|