Upload app.py
Browse files
app.py
CHANGED
|
@@ -1,103 +1,198 @@
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Untitled68.ipynb
|
| 3 |
+
|
| 4 |
+
Automatically generated by Colab.
|
| 5 |
+
|
| 6 |
+
Original file is located at
|
| 7 |
+
https://colab.research.google.com/drive/1h4tpXH6r9B2VZLVwksIkuuVpcrXTUnuJ
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import bitsandbytes as bnb
|
| 12 |
+
import transformers
|
| 13 |
+
import re
|
| 14 |
+
import pandas as pd
|
| 15 |
+
import os
|
| 16 |
+
import streamlit as st
|
| 17 |
+
|
| 18 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 19 |
+
from langchain.llms import HuggingFacePipeline
|
| 20 |
+
from langchain.prompts import PromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate, ChatPromptTemplate
|
| 21 |
+
from langchain_core.output_parsers import StrOutputParser
|
| 22 |
+
from langchain_community.document_loaders import YoutubeLoader, DataFrameLoader
|
| 23 |
+
from langchain_community.vectorstores.utils import filter_complex_metadata
|
| 24 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 25 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 26 |
+
from langchain_community.vectorstores import FAISS
|
| 27 |
+
from langchain.schema.runnable import RunnablePassthrough
|
| 28 |
+
from langchain_core.messages import AIMessage, HumanMessage
|
| 29 |
+
from dotenv import load_dotenv
|
| 30 |
+
|
| 31 |
+
# Get the API token from environment variable
|
| 32 |
+
api_token = os.getenv("API_TOKEN")
|
| 33 |
+
|
| 34 |
+
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "max_split_size_mb:15000"
|
| 35 |
+
|
| 36 |
+
model_id = "google/gemma-2-9b-it"
|
| 37 |
+
quantization_config = BitsAndBytesConfig(load_in_4bit=True)
|
| 38 |
+
|
| 39 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 40 |
+
model_id,
|
| 41 |
+
return_tensors="pt",
|
| 42 |
+
padding=True,
|
| 43 |
+
truncation=True,
|
| 44 |
+
trust_remote_code=True,
|
| 45 |
+
)
|
| 46 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 47 |
+
tokenizer.padding_side = "right"
|
| 48 |
+
|
| 49 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 50 |
+
model_id,
|
| 51 |
+
quantization_config=quantization_config,
|
| 52 |
+
device_map="auto",
|
| 53 |
+
low_cpu_mem_usage=True,
|
| 54 |
+
pad_token_id=0,
|
| 55 |
+
)
|
| 56 |
+
model.config.use_cache = False
|
| 57 |
+
|
| 58 |
+
# Create a text generation pipeline with specific settings
|
| 59 |
+
pipe = transformers.pipeline(
|
| 60 |
+
task="text-generation",
|
| 61 |
+
model=model,
|
| 62 |
+
tokenizer=tokenizer,
|
| 63 |
+
torch_dtype=torch.float16,
|
| 64 |
+
device_map="auto",
|
| 65 |
+
# do_sample=True,
|
| 66 |
+
# top_k=10,
|
| 67 |
+
temperature=0.0,
|
| 68 |
+
top_p=0.9,
|
| 69 |
+
num_return_sequences=1,
|
| 70 |
+
eos_token_id=tokenizer.eos_token_id,
|
| 71 |
+
max_length=4096,
|
| 72 |
+
truncation=True,
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
chat_model = HuggingFacePipeline(pipeline=pipe)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
template = """
|
| 79 |
+
You are a genius trader with extensive knowledge of the financial and stock markets, capable of providing deep and insightful analysis of financial stocks with remarkable accuracy.
|
| 80 |
+
|
| 81 |
+
**ALWAYS**
|
| 82 |
+
Summarize and provide the main insights.
|
| 83 |
+
Be as detailed as possible, but don't make up any information that’s not from the context.
|
| 84 |
+
If you don't know an answer, say you don't know.
|
| 85 |
+
Let's think step by step.
|
| 86 |
+
|
| 87 |
+
Please ensure responses are informative, accurate, and tailored to the user's queries and preferences.
|
| 88 |
+
Use natural language to engage users and provide readable content throughout your response.
|
| 89 |
+
|
| 90 |
+
{context}
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
review_system_prompt = SystemMessagePromptTemplate(
|
| 94 |
+
prompt=PromptTemplate(
|
| 95 |
+
input_variables=["context"],
|
| 96 |
+
template=template,
|
| 97 |
+
)
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
review_human_prompt = HumanMessagePromptTemplate(
|
| 101 |
+
prompt=PromptTemplate(
|
| 102 |
+
input_variables=["question"],
|
| 103 |
+
template="{question}",
|
| 104 |
+
)
|
| 105 |
+
)
|
| 106 |
+
messages = [review_system_prompt, review_human_prompt]
|
| 107 |
+
|
| 108 |
+
review_prompt_template = ChatPromptTemplate(
|
| 109 |
+
input_variables=["context", "question"],
|
| 110 |
+
messages=messages,
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def find_youtube_links(text):
|
| 115 |
+
# Define the regular expression pattern for YouTube URLs
|
| 116 |
+
youtube_regex = (r'(https?://(?:www\.)?(?:youtube\.com/watch\?v=|youtu\.be/)[^ \n]+)')
|
| 117 |
+
# Use re.findall() to find all matches in the text
|
| 118 |
+
matches = re.findall(youtube_regex, text)
|
| 119 |
+
return str(' '.join(matches))
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# Function to get a response from the model
|
| 123 |
+
def get_response(user_query):
|
| 124 |
+
review_chain = (
|
| 125 |
+
{"context": reviews_retriever, "question": RunnablePassthrough()}
|
| 126 |
+
| review_prompt_template
|
| 127 |
+
| chat_model
|
| 128 |
+
| StrOutputParser()
|
| 129 |
+
)
|
| 130 |
+
response = review_chain.invoke(user_query)
|
| 131 |
+
return response
|
| 132 |
+
|
| 133 |
+
# App config
|
| 134 |
+
st.set_page_config(page_title="GOAHEAD.VN", page_icon="🌍")
|
| 135 |
+
st.title("Summary and provide insights from youtube news.")
|
| 136 |
+
|
| 137 |
+
# Initialize session state
|
| 138 |
+
if "chat_history" not in st.session_state:
|
| 139 |
+
st.session_state.chat_history = [
|
| 140 |
+
AIMessage(content="Hello, how can I help you?"),
|
| 141 |
+
]
|
| 142 |
+
|
| 143 |
+
# Display chat history
|
| 144 |
+
for message in st.session_state.chat_history:
|
| 145 |
+
if isinstance(message, AIMessage):
|
| 146 |
+
with st.chat_message("AI"):
|
| 147 |
+
st.write(message.content)
|
| 148 |
+
elif isinstance(message, HumanMessage):
|
| 149 |
+
with st.chat_message("Human"):
|
| 150 |
+
st.write(message.content)
|
| 151 |
+
|
| 152 |
+
# User input
|
| 153 |
+
user_query = st.chat_input("Type your message here...")
|
| 154 |
+
|
| 155 |
+
if user_query is not None and find_youtube_links(user_query) != "":
|
| 156 |
+
st.session_state.chat_history.append(HumanMessage(content=user_query))
|
| 157 |
+
|
| 158 |
+
with st.chat_message("Human"):
|
| 159 |
+
st.markdown(user_query)
|
| 160 |
+
|
| 161 |
+
loader = YoutubeLoader.from_youtube_url(
|
| 162 |
+
find_youtube_links(url),
|
| 163 |
+
add_video_info=False,
|
| 164 |
+
language=["en", "vi"],
|
| 165 |
+
translation="en",
|
| 166 |
+
)
|
| 167 |
+
docs = loader.load()
|
| 168 |
+
# Convert the loaded documents to a list of dictionaries
|
| 169 |
+
data_list = [
|
| 170 |
+
{
|
| 171 |
+
"source": doc.metadata['source'],
|
| 172 |
+
"page_content": doc.page_content
|
| 173 |
+
}
|
| 174 |
+
for doc in docs
|
| 175 |
+
]
|
| 176 |
+
df = pd.DataFrame(data_list)
|
| 177 |
+
loader = DataFrameLoader(df, page_content_column='page_content')
|
| 178 |
+
content = loader.load()
|
| 179 |
+
content = filter_complex_metadata(content)
|
| 180 |
+
|
| 181 |
+
# Split the document into chunks with a specified chunk size
|
| 182 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1500, chunk_overlap=150)
|
| 183 |
+
all_splits = text_splitter.split_documents(content)
|
| 184 |
+
|
| 185 |
+
# Initialize the embedding model
|
| 186 |
+
embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L12-v2")
|
| 187 |
+
|
| 188 |
+
# Store the document into a vector store with a specific embedding model
|
| 189 |
+
vectorstore = FAISS.from_documents(all_splits, embedding_model)
|
| 190 |
+
|
| 191 |
+
reviews_retriever = vectorstore.as_retriever()
|
| 192 |
+
|
| 193 |
+
response = get_response("Help me summary and provide main insights.")
|
| 194 |
+
|
| 195 |
+
with st.chat_message("AI"):
|
| 196 |
+
st.write(response)
|
| 197 |
+
|
| 198 |
+
st.session_state.chat_history.append(AIMessage(content=response))
|