Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
timho102003 committed Sep 7, 2023
0 parents commit 81a45d5
Show file tree
Hide file tree
Showing 10 changed files with 1,448 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
**/.DS_Store
**/__pycache__
.streamlit/secrets.toml
assets/newsgpt_firebase_serviceAccount.json
6 changes: 6 additions & 0 deletions .streamlit/config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[theme]
primaryColor = "#949494"
backgroundColor = "#FFFFFF"
secondaryBackgroundColor = "#f1efef"
textColor = "#000000"
font = "sans serif"
89 changes: 89 additions & 0 deletions Home.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import json
import time

import streamlit as st
from firebase_admin import firestore
from google.oauth2 import service_account
from streamlit_extras.buy_me_a_coffee import button as coffee_button
from streamlit_extras.switch_page_button import switch_page

from template.chat_page import chat_template
from template.feed_page import feed_template
from template.login_page import login_template, signup_template
from template.summary_page import summary_template
from utils import load_activities, second_to_text, signout

st.set_page_config(page_title="", page_icon="👋", layout="wide")

with st.sidebar:
coffee_button(username="timho102003", floating=False, width=221)
is_signout = st.button("Sign Out")
if is_signout:
if not st.session_state.get("is_auth_user", False):
st.warning("Please login first to sign out")
else:
signout()
st.success("Successfully sign out, Please sign in as different user")
time.sleep(1)
switch_page("home")
st.divider()
if st.session_state.get("is_auth_user", False):
user_meta = st.session_state["user_ref"].get()
user_meta = user_meta.to_dict()
tot_readtime = 0
tot_savetime = 0
readtime_last = 0
savetime_last = 0
col1, col2 = st.columns(2)
if "save_time" in user_meta:
savetime_last = user_meta["save_time"][-1]
tot_savetime = sum(user_meta["save_time"])
col1.metric(
"Total Save Time",
second_to_text(tot_savetime, True),
second_to_text(savetime_last, True),
help="Read time in total",
)
if "readtime" in user_meta:
readtime_last = user_meta["readtime"][-1]
tot_readtime = sum(user_meta["readtime"])
col2.metric(
"Total Read Time",
second_to_text(tot_readtime, True),
second_to_text(readtime_last, True),
help="NewsGPT saves you time in total",
)
if "activities" in user_meta:
gb_time_df, gb_cat_df = load_activities(user_meta["activities"])
st.divider()
st.area_chart(
gb_time_df,
x="yyyy-mm-dd",
y="read cnt",
)
st.divider()
st.bar_chart(
gb_cat_df,
x="category",
y="read cnt",
)

key_dict = json.loads(st.secrets["textkey"])
creds = service_account.Credentials.from_service_account_info(key_dict)
st.session_state["firestore_db"] = firestore.Client(credentials=creds)
# st.session_state["firestore_db"] = firestore.Client.from_service_account_json("assets/newsgpt_firebase_serviceAccount.json")

if st.session_state.get("error", None):
st.toast(f'Something went wrong: {st.session_state["error"]}')
st.session_state["error"] = None

if st.session_state.get("page_name", "login") == "login":
login_template()
elif st.session_state.get("page_name", "login") == "signup":
signup_template()
elif st.session_state.get("page_name", "login") == "feed":
feed_template()
elif st.session_state.get("page_name", "login") == "summary":
summary_template()
elif st.session_state.get("page_name", "login") == "chat_mode":
chat_template()
9 changes: 9 additions & 0 deletions config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
NEWS_CATEGORIES = [
"World",
"Nation",
"Technology",
"Science",
"Entertainment",
"Business",
]
FEED_ARTICLE_NUMS = 20
12 changes: 12 additions & 0 deletions convert_toml.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import toml

output_file = ".streamlit/secrets.toml"

with open("./assets/newsgpt_firebase_serviceAccount.json") as json_file:
json_text = json_file.read()

config = {"textkey": json_text}
toml_config = toml.dumps(config)

with open(output_file, "w") as target:
target.write(toml_config)
220 changes: 220 additions & 0 deletions template/chat_page.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
import readtime
import streamlit as st
from streamlit_extras.row import row
from streamlit_extras.switch_page_button import switch_page

from utils import (
generate_anno_text,
second_to_text,
update_activities,
update_negatives,
update_positives,
)


def predefine_prompt(prompt):
st.session_state.initial_prompt.append(prompt)


def chat_template():
title = st.session_state["active_chat_result"]["title"]
image = st.session_state["active_chat_result"]["image"]
author = st.session_state["active_chat_result"]["author"]
publish = st.session_state["active_chat_result"]["publish"]
reference = st.session_state["active_chat_result"]["reference"]
id = st.session_state["active_chat_result"]["id"]
category = st.session_state["active_chat_result"]["category"]
ori_tot_readtime = st.session_state["active_chat_result"]["ori_tot_readtime"]
ner_loc = st.session_state["active_chat_result"]["ner_loc"]
ner_org = st.session_state["active_chat_result"]["ner_org"]
ner_per = st.session_state["active_chat_result"]["ner_per"]

col1, col2, col3 = st.columns([0.2, 0.6, 0.2])
with col2:
go_back_to_feed = st.button(
"Back To Feed",
on_click=update_activities,
kwargs={
"title": title,
"id": id,
"category": category,
"summary_rt": st.session_state.reading_time,
"ori_rt": ori_tot_readtime,
"ner_loc": ner_loc,
"ner_org": ner_org,
"ner_per": ner_per,
"chat_mode": True,
},
)
if go_back_to_feed:
st.session_state["page_name"] = "feed"
switch_page("home")

with st.container():
st.markdown(
"""
<style>
.title {
text-align: center;
font-size: 200%;
font-weight: bold;
color: white;
margin-bottom: 10px;
padding: 10px;
border-radius: 10px;
}
.author-publish, .read-time {
text-align: center;
font-size: 80%;
color: grey;
margin: 5px 0;
}
.summary-heading, .similarity-heading, .difference-heading {
text-align: justify;
font-size: 150%;
font-weight: bold;
color: white;
margin-top: 20px;
padding: 10px;
border-radius: 10px;
max-width: 90%;
}
.centered-image img {
display: block;
margin-left: auto;
margin-right: auto;
border-radius: 10px; /* Rounded corners */
max-width: 100%; /* Responsive */
}
.content {
text-align: justify;
margin: 0 auto;
max-width: 90%; /* Adjust to match the image width */
}
</style>
""",
unsafe_allow_html=True,
)

st.markdown("<div class='rounded-container'>", unsafe_allow_html=True)
st.markdown(f"<div class='title'>{title}</div>", unsafe_allow_html=True)
st.markdown(
f"<div class='centered-image'><img src='{image}' alt='Image'></div>",
unsafe_allow_html=True,
) # Centered and rounded image
st.markdown(
f"<p class='author-publish'>category: {category}</p>",
unsafe_allow_html=True,
)
st.markdown(
f"<p class='author-publish'>author: {author}</p>",
unsafe_allow_html=True,
)
st.markdown(
f"<p class='author-publish'>published: {publish}</p>",
unsafe_allow_html=True,
)
st.markdown(
f"<p class='author-publish'>reference article number: {len(reference)}</p>",
unsafe_allow_html=True,
)
st.markdown(
f"<p class='read-time'>NewsGPT help you save: {second_to_text(ori_tot_readtime - st.session_state.reading_time)}</p>",
unsafe_allow_html=True,
)
st.markdown("<br>", unsafe_allow_html=True)
with st.expander("Tags"):
if ner_org:
generate_anno_text(ner_org, label="ORG")
if ner_per:
generate_anno_text(ner_per, label="PER")
if ner_loc:
generate_anno_text(ner_loc, label="LOC")

with st.expander("Reference Article Links"):
for r_i, ref in enumerate(reference):
st.markdown(f'{r_i}. [{ref["title"]}]({ref["url"]})')

thumbtext, thumbbt1, thumbbt2, _ = st.columns([0.4, 0.1, 0.1, 0.4])
is_like = thumbbt1.button(
"👍",
on_click=update_positives,
kwargs={
"title": title,
"id": id,
"category": category,
"ner_loc": ner_loc,
"ner_org": ner_org,
"ner_per": ner_per,
},
help="I like the news content, please recommend more",
)

not_like = thumbbt2.button(
"👎",
on_click=update_negatives,
kwargs={
"title": title,
"id": id,
"category": category,
"ner_loc": ner_loc,
"ner_org": ner_org,
"ner_per": ner_per,
},
help="I don't like the news content, please don't feed to me",
)
if is_like:
st.toast(f"Thanks for liking the summary and article: {title}", icon="👍")

if not_like:
st.toast(f"We will make the recommendation better for you. Trust us!", icon="👎")

prompt = st.chat_input("Ask me any question about the news")
if st.session_state.initial_prompt:
prompt = st.session_state.initial_prompt.pop(0)
if prompt:
st.session_state.messages.append({"role": "user", "content": prompt})

for message in st.session_state.messages: # Display the prior chat messages
with st.chat_message(message["role"]):
st.write(message["content"])

# If last message is not from assistant, generate a new response
if st.session_state.messages[-1]["role"] != "assistant":
with st.chat_message(
"assistant",
):
with st.spinner("Thinking..."):
# response = st.session_state["chat_engine"].chat(prompt)
response = st.session_state["chat_engine"].query(prompt)
st.write(response.response)
message = {"role": "assistant", "content": response.response}
st.session_state.reading_time += readtime.of_text(
response.response
).seconds
st.session_state.messages.append(
message
) # Add response to message history

print(st.session_state.reading_time)
predefine_prompt_row = row(
[0.05, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.05],
vertical_align="center",
gap="medium",
)
for _ in range(3):
predefine_prompt_row.write("")
predefine_prompt_row.button(
"Similar Viewpoints",
on_click=predefine_prompt,
kwargs={
"prompt": "Compare between the articles and provide the similar viewpoints in bullet points"
},
)
predefine_prompt_row.button(
"Discrepency Viewpoints",
on_click=predefine_prompt,
kwargs={
"prompt": "Compare between the articles and provide the discrepency viewpoints in bullet points"
},
)
Loading

0 comments on commit 81a45d5

Please sign in to comment.