singhdevendra58 commited on
Commit
318d005
·
verified ·
1 Parent(s): 0cfdd6a

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +129 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,131 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ from langchain.document_loaders import PyPDFLoader, Docx2txtLoader, TextLoader
3
+ from langchain.text_splitter import CharacterTextSplitter
4
+ from langchain.embeddings.openai import OpenAIEmbeddings
5
+ from langchain.vectorstores import FAISS
6
+ from langchain.chains import ConversationalRetrievalChain
7
+ from langchain.llms import OpenAI
8
+ import os
9
+ import tempfile
10
+ from doc_qa import embeddings,llm
11
+ from doc_qa_1 import embeddings,doc_qa
12
 
13
+ def start_message(doc_name):
14
+ st.success("✅ ドキュメントのアップロードが完了しました!")
15
+ st.markdown(f"### 📄 アップロードされました: `{doc_name}`")
16
+ st.markdown("これで文書に関する質問ができます。 💬")
17
+ st.markdown("例えば、次のような質問ができます。:")
18
+ st.markdown("- この文書は何について書かれていますか?")
19
+ st.markdown("- 重要なポイントを要約してください。")
20
+ st.markdown("- 著者は誰ですか?")
21
+ st.markdown("はじめるには、下に質問を入力してください。!")
22
+
23
+ # Function to load individual file
24
+ def load_file(file, suffix):
25
+ with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:
26
+ temp_file.write(file.read())
27
+ temp_file_path = temp_file.name
28
+
29
+ if suffix == ".pdf":
30
+ loader = PyPDFLoader(temp_file_path)
31
+ elif suffix == ".docx":
32
+ loader = Docx2txtLoader(temp_file_path)
33
+ elif suffix == ".txt":
34
+ loader = TextLoader(temp_file_path)
35
+ else:
36
+ return []
37
+
38
+ return loader.load()
39
+ st.set_page_config(
40
+ page_title="QA Assistant",
41
+ page_icon="https://yourdomain.com/logo.png",
42
+ layout="centered"
43
+ )
44
+ # Title
45
+ st.title("📄 ドキュメント質問応答支援ツール")
46
+
47
+ # Step 1: Upload document
48
+ if "file_uploaded" not in st.session_state:
49
+ st.session_state.file_uploaded = False
50
+ st.markdown("""
51
+ 👋 こちらへようこそ!私は文書の内容を理解するためのインテリジェントアシスタントです。
52
+
53
+ あなたは以下のことができます:
54
+
55
+ PDF、DOCX、TXTファイルをアップロード
56
+
57
+ 文書の内容について質問
58
+
59
+ 要約、重要ポイント、または具体的な詳細の取得
60
+
61
+ 🛠️ 質問の例:
62
+ この文書は何について書かれていますか?
63
+
64
+ 主要なポイントを要約してください。
65
+
66
+ 著者は誰ですか?
67
+
68
+ 重要な日付や締め切りは何ですか?
69
+
70
+ 結論や推奨事項は何ですか?
71
+
72
+ 📂 まず、1つ以上の文書をアップロードしてください。
73
+ 💬 その後、下に質問を入力しましょう!
74
+ """)
75
+ if "messages" not in st.session_state:
76
+ st.session_state.messages = []
77
+
78
+
79
+ flag = 0
80
+ # Upload multiple files
81
+ with st.sidebar:
82
+ uploaded_files = st.file_uploader("PDF、DOCX、またはTXTファイルをアップロードしてください。", type=["pdf", "docx", "txt"], accept_multiple_files=True)
83
+ # Load and process documents
84
+ file_names=[]
85
+ if uploaded_files:
86
+ all_docs = []
87
+ for file in uploaded_files:
88
+ suffix = os.path.splitext(file.name)[1]
89
+ docs = load_file(file, suffix)
90
+ all_docs.extend(docs)
91
+ file_names.append(file.name)
92
+
93
+ # Split and embed documents
94
+ text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
95
+ split_docs = text_splitter.split_documents(all_docs)
96
+ #embeddings = OpenAIEmbeddings()
97
+ vectorstore = FAISS.from_documents(split_docs, embeddings)
98
+
99
+ # Setup ConversationalRetrievalChain
100
+ qa_chain = ConversationalRetrievalChain.from_llm(
101
+ llm=llm,
102
+ retriever=vectorstore.as_retriever(),
103
+ return_source_documents=False
104
+ )
105
+ start_message('\n'.join(file_names))
106
+ flag = 1
107
+
108
+ # Initialize session state
109
+ if "chat_history" not in st.session_state:
110
+ st.session_state.chat_history = []
111
+
112
+ for msg in st.session_state.messages:
113
+ st.chat_message(msg["role"]).write(msg["content"])
114
+
115
+ if flag==1:
116
+ if user_query := st.chat_input():
117
+ st.session_state.messages.append({"role": "user", "content": user_query})
118
+ with st.chat_message("user"):
119
+ st.markdown(f"**Q:** {user_query}")
120
+ result=doc_qa(user_query,vectorstore)
121
+ st.session_state.messages.append({"role": "assistant", "content": result["answer"]})
122
+ with st.chat_message("assistant"):
123
+ st.markdown(f"**A:** {result["answer"]}")
124
+ st.session_state.chat_history.append((user_query, result["answer"]))
125
+
126
+ # # Display conversation history
127
+ # if st.session_state.chat_history:
128
+ # st.markdown("### 🗨️ Chat History")
129
+ # for i, (q, a) in enumerate(st.session_state.chat_history, 1):
130
+ # st.markdown(f"**Q{i}:** {q}")
131
+ # st.markdown(f"**A{i}:** {a}")