faizanmumtaz's picture
Update main.py
7c3e734
from langchain.prompts import ChatPromptTemplate
from langchain.chat_models import ChatOpenAI,ChatGooglePalm,ChatCohere
from langchain.schema.output_parser import StrOutputParser
from langchain.schema.runnable import RunnablePassthrough
import pandas as pd
import os
import streamlit as st
from io import BytesIO
def _main(df):
if "reviews" not in df.columns:
st.warning("CSV file must have a column named 'reviews'")
else:
df = df["reviews"][0:20]
model = ChatCohere(cohere_api_key="",temperature=0.1)
template = """What is the sentiment of following product review,
which is delimited in triple backticks?
Do not generate extra text just determined the sentiment of the product review. e.g positive,negative,neutral
Review text: > ```{review}```"""
prompt = ChatPromptTemplate.from_messages([
("system", "You are a review sentiment analyzer.Do not generate extra text just determined the sentiment of the product review. e.g positive,negative,neutral"),
("user", template.format(review = "I'm a coffee enthusiast, and the FreshBrew grinder has taken my coffee game to the next level. It's easy to use, and the adjustable grind settings allow me to customize my coffee to perfection. A must-have for any coffee lover.")),
("ai", "positive"),
("user", template.format(review = "I'm disappointed with the product. It didn't live up to the advertised features, and the quality is subpar. I wouldn't recommend it to others.")),
("ai", "negative"),
("user",template)
])
chain = prompt | model | StrOutputParser()
get_sentiment = RunnablePassthrough.assign(
reviews = lambda x : list(x["reviews"])
) | (lambda x:[{"review":r} for r in x["reviews"]]) | chain.map()
sentiments = get_sentiment.invoke({"reviews":df})
data = {'review': list(df), 'sentiment': sentiments}
df = pd.DataFrame(data)
st.write(df)
excel_file = BytesIO()
df.to_excel(excel_file, index=False, engine='xlsxwriter')
excel_file.seek(0)
st.download_button(
label='Download Excel File',
data=excel_file,
key='download_excel_button',
file_name='reviews_sentiments.xlsx',
mime='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
)