ngcanh commited on
Commit
a2141da
·
verified ·
1 Parent(s): 29169b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +171 -112
app.py CHANGED
@@ -1,117 +1,176 @@
1
- from langchain_community.vectorstores import FAISS
2
- from langchain_community.embeddings import HuggingFaceEmbeddings
3
- from langchain.prompts import PromptTemplate
4
- import os
5
- from langchain.memory import ConversationBufferWindowMemory
6
- from langchain.chains import ConversationalRetrievalChain
7
- import time
8
  import streamlit as st
9
- import os
 
 
10
  import subprocess
11
- from langchain.chat_models import ChatOpenAI
12
- st.set_page_config(page_title="MBAL CHATBOT")
13
- col1, col2, col3 = st.columns([1,2,1])
14
- OPENAI_API_KEY = os.getenv("OPENAI_API")
15
  TOKEN=os.getenv('HF_TOKEN')
16
  subprocess.run(["huggingface-cli", "login", "--token", TOKEN, "--add-to-git-credential"])
17
- st.sidebar.title("Welcome to MBAL Chatbot")
18
- st.markdown(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  """
20
- <style>
21
- div.stButton > button:first-child {
22
- background-color: #ffd0d0;
23
- }
24
-
25
- div.stButton > button:active {
26
- background-color: #ff6262;
27
- }
28
-
29
- .st-emotion-cache-6qob1r {
30
- position: relative;
31
- height: 100%;
32
- width: 100%;
33
- background-color: black;
34
- overflow: overlay;
35
- }
36
-
37
- div[data-testid="stStatusWidget"] div button {
38
- display: none;
39
- }
40
-
41
- .reportview-container {
42
- margin-top: -2em;
43
- }
44
- #MainMenu {visibility: hidden;}
45
- .stDeployButton {display:none;}
46
- footer {visibility: hidden;}
47
- #stDecoration {display:none;}
48
- button[title="View fullscreen"]{
49
- visibility: hidden;}
50
- </style>
51
- """,
52
- unsafe_allow_html=True,
53
- )
54
-
55
- def reset_conversation():
56
- st.session_state.messages = []
57
- st.session_state.memory.clear()
58
-
59
- if "messages" not in st.session_state:
60
- st.session_state.messages = []
61
-
62
- if "memory" not in st.session_state:
63
- st.session_state.memory = ConversationBufferWindowMemory(k=2, memory_key="chat_history",return_messages=True)
64
-
65
- embeddings = HuggingFaceEmbeddings(model_name="bkai-foundation-models/vietnamese-bi-encoder", model_kwargs={"trust_remote_code": True})
66
- db = FAISS.load_local("mbal_faiss_db", embeddings,allow_dangerous_deserialization= True)
67
- db_retriever = db.as_retriever(search_type="similarity",search_kwargs={"k": 4})
68
-
69
- prompt_template = """<s>[INST] Bạn một chuyên viên vấn cho khách hàng về sản phẩm bảo hiểm của công ty MB Ageas Life tại Việt Nam. Hãy trả lời chuyên nghiệp, chính xác, cung cấp thông tin trước rồi hỏi câu tiếp theo. Tất cả các thông tin cung cấp đều trong phạm vi MBAL. Khi có đủ thông tin khách hàng thì mới mời khách hàng đăng ký để nhận tư vấn trên https://www.mbageas.life/
70
- {context}
71
- QUESTION: {question}
72
- CHAT HISTORY: {chat_history}[/INST]
73
- ASSISTANT:
74
- </s>
75
- """
76
-
77
- prompt = PromptTemplate(template=prompt_template,
78
- input_variables=['question', 'context', 'chat_history'])
79
-
80
-
81
- llm = ChatOpenAI(model="gpt-4o")
82
-
83
- # Create a conversational chain using only your database retriever
84
- qa = ConversationalRetrievalChain.from_llm(
85
- llm=llm,
86
- memory=st.session_state.memory,
87
- retriever=db_retriever,
88
- combine_docs_chain_kwargs={'prompt': prompt}
89
- )
90
-
91
- for message in st.session_state.messages:
92
- with st.chat_message(message.get("role")):
93
- st.write(message.get("content"))
94
-
95
- input_prompt = st.chat_input("Say something")
96
-
97
- if input_prompt:
98
- with st.chat_message("user"):
99
- st.write(input_prompt)
100
-
101
- st.session_state.messages.append({"role":"user","content":input_prompt})
102
-
103
- with st.chat_message("assistant"):
104
- with st.status("Lifting data, one bit at a time 💡...",expanded=True):
105
- result = qa.invoke(input=input_prompt)
106
-
107
- message_placeholder = st.empty()
108
-
109
- full_response = "⚠️ **_Note: Information provided may be inaccurate._** \n\n\n"
110
- for chunk in result["answer"]:
111
- full_response+=chunk
112
- time.sleep(0.02)
113
-
114
- message_placeholder.markdown(full_response+" ")
115
- st.button('Reset All Chat 🗑️', on_click=reset_conversation)
116
-
117
- st.session_state.messages.append({"role":"assistant","content":result["answer"]})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import pandas as pd
3
+ from openai import OpenAI
4
+ import os
5
  import subprocess
 
 
 
 
6
  TOKEN=os.getenv('HF_TOKEN')
7
  subprocess.run(["huggingface-cli", "login", "--token", TOKEN, "--add-to-git-credential"])
8
+ OPENAI_API_KEY = os.getenv("OPENAI_API")
9
+
10
+ client = OpenAI(api_key=OPENAI_API_KEY) #INSERT KEY INSODE HE QUOTES IN THE BRACKET
11
+ from docx import Document
12
+
13
+ # Function to extract text from a .docx file
14
+ def extract_text_from_docx(file):
15
+ doc = Document(file)
16
+ text = "\n".join([para.text for para in doc.paragraphs])
17
+ return text.strip()
18
+
19
+ # Function to parse the feedback into rubric components
20
+ def parse_feedback(feedback):
21
+ # You can customize this based on how GPT provides the feedback
22
+ # Here, I assume feedback includes specific scoring lines like 'Content Relevance: X/25'
23
+ scores = {
24
+ 'Content Relevance': None,
25
+ 'Clarity and Organisation': None,
26
+ 'Originality and Creativity': None,
27
+ 'Research and Evidence': None,
28
+ 'Writing Style and Language': None,
29
+ 'Conclusion': None,
30
+ 'Overall Impression': None,
31
+ 'Total Score': None
32
+ }
33
+
34
+ lines = feedback.split('\n')
35
+ for line in lines:
36
+ for key in scores.keys():
37
+ if key in line:
38
+ score = line.split(':')[-1].strip()
39
+ scores[key] = score
40
+
41
+ # Assume that the last numerical value mentioned is the total score
42
+ total_score = sum([int(score) for score in scores.values() if score])
43
+ scores['Total Score'] = total_score
44
+ return scores
45
+
46
+ # Function to grade the essay using GPT-4
47
+ def grade_essay(essay, guided_data, topic, rubric):
48
+ # Sample prompt for grading using GPT-4
49
+ prompt = f"""
50
+ You are an consultant that grades marketing and business proposal based on a provided rubric, ensuring an unbiased evaluation while considering clarity, originality, organization, and depth of analysis. Advise in Vietnamse, only use English for buzzwords.
51
+
52
+
53
+ Đánh giá dựa trên những đầu mục lớn và từng đầu mục nhỏ
54
+ Research: Ensure that the proposal has evaluation for 1. Market, 2. brand and competitors, while seeing the trend, opportunities and threats
55
+ Xác định rõ vấn đề, mục tiêu và vai trò nhãn hàng trong chiến dịch: 1. Xác định vấn đề truyền thông, 2. Xác định rõ mục tiêu của chiến dịch, 3.Nhìn nhận đúng vai trò của Brand trong chiến dịch
56
+ Phân tích đối tượng truyền thông: 1. Phân tích đối tượng mục tiêu cụ thể, đầy đủ và phù hợp với mục đích truyền thông, 2.Insight liên quan chặt chẽ và có tính khả thi cao với thương hiệu, 3. Insight có tính độc đáo, mới mẻ, có khả năng truyền tải tới đối tượng mục tiêu
57
+ Đề xuất chiến lược tiếp cận: 1. Mức độ liên kết chặt chẽ giữa chiến lược mới với các phân tích trước đó 2. Mức độ phù hợp của chiến lược đối với Brand và đối tượng mục tiêu 3. Mức độ đan xen yếu tố Brand role vào chiến lược tiếp cận
58
+ "Ý tưởng lớn (Big Idea): 1. Giải quyết được vấn đề của thương hiệu, thể hiện được vai trò thương hiệu 2.Phù hợp với insight của đối tượng mục tiêu 3. Ý tưởng đột phá, sáng tạo, có tính khả thi
59
+
60
+ Here is the rubric for grading:
61
+ {rubric}
62
+
63
+ Here are examples of previously graded essays and their scores: {guided_data}
64
+
65
+ Please grade the following essay and provide feedback:
66
+ {essay}
67
  """
68
+
69
+ # Call OpenAI's GPT-4 for grading
70
+ response = client.chat.completions.create(model="gpt-4",
71
+ messages=[
72
+ {"role": "user", "content": prompt}
73
+ ])
74
+ return response.choices[0].message.content
75
+
76
+ # Function to export results to CSV
77
+ def export_to_csv(data):
78
+ df = pd.DataFrame(data)
79
+ df.to_csv('essay_grades.csv', index=False)
80
+
81
+ # Main function for the Streamlit app
82
+ def main():
83
+ st.title("olukoAI Essay Grader by Effico")
84
+
85
+ # Predefined rubric for grading
86
+ rubric = """
87
+ INSTRUCTIONS FOR GRADING
88
+ 1. Research: 25
89
+ 2. Xác định rõ vấn đề, mục tiêu và vai trò nhãn hàng trong chiến dịch: 20
90
+ 3. Phân tích đối tượng truyền thông: 30
91
+ 4. Đề xuất chiến lược tiếp cận: 10
92
+ 5. Ý tưởng lớn: 10
93
+
94
+ Total: 110
95
+ """
96
+
97
+ # State to store results
98
+ if 'results' not in st.session_state:
99
+ st.session_state.results = []
100
+
101
+ # File uploader for example graded essays (DOCX)
102
+ example_files = st.file_uploader("Upload 10 example graded essays (DOCX)", type=["docx"], accept_multiple_files=True)
103
+
104
+ # File uploader for corresponding scores (DOCX)
105
+ scores_file = st.file_uploader("Upload the DOCX file containing corresponding scores", type=["docx"])
106
+
107
+ # File uploader for new essays to be graded (DOCX)
108
+ new_files = st.file_uploader("Upload DOCX files with essays to be graded", type=["docx"], accept_multiple_files=True)
109
+
110
+ # Grading button
111
+ if st.button("Grade Essays"):
112
+ if example_files and scores_file and new_files:
113
+ # Extract scores from the scores file
114
+ scores_text = extract_text_from_docx(scores_file)
115
+ scores_lines = scores_text.splitlines()
116
+
117
+ # Create a dictionary to match scores to participant names
118
+ scores_dict = {}
119
+ for line in scores_lines:
120
+ if ':' in line: # Assuming the format is "Participant Name: Score"
121
+ name, score = line.split(':', 1)
122
+ scores_dict[name.strip()] = score.strip()
123
+
124
+ # Prepare guided data from example graded essays
125
+ guided_data = {}
126
+ for example_file in example_files:
127
+ essay_text = extract_text_from_docx(example_file)
128
+ participant_name = os.path.splitext(example_file.name)[0] # Assuming name is file name
129
+ if participant_name in scores_dict:
130
+ guided_data[participant_name] = {
131
+ 'essay': essay_text,
132
+ 'score': scores_dict[participant_name]
133
+ }
134
+
135
+ # Combine guided essays with their scores
136
+ guided_data_combined = "\n".join([f"{name}: {data['essay']} (Score: {data['score']})" for name, data in guided_data.items()])
137
+
138
+ # Process each new essay
139
+ for new_file in new_files:
140
+ new_essay = extract_text_from_docx(new_file)
141
+ new_participant_name = os.path.splitext(new_file.name)[0] # Assuming name is file name
142
+ st.write(f"Grading essay for: {new_participant_name}")
143
+
144
+ # Grading the new essay using the provided rubric and example graded essays
145
+ result = grade_essay(new_essay, guided_data_combined, rubric)
146
+
147
+ # Parse feedback into rubric components
148
+ parsed_scores = parse_feedback(result)
149
+
150
+ # Store results in session state
151
+ st.session_state.results.append({
152
+ 'Participant Name': new_participant_name,
153
+ 'Essay File': new_file.name,
154
+ **parsed_scores,
155
+ 'Feedback': result,
156
+ })
157
+
158
+ # Display the grading feedback
159
+ st.write("Feedback:")
160
+ st.write(result)
161
+
162
+ st.success("Grading completed for all uploaded essays.")
163
+ else:
164
+ st.error("Please upload all required files.")
165
+
166
+ # Export results button always visible
167
+ with st.sidebar:
168
+ if st.button("Export All Results to CSV"):
169
+ if st.session_state.results:
170
+ export_to_csv(st.session_state.results)
171
+ st.success("All results exported to essay_grades.csv")
172
+ else:
173
+ st.warning("No results to export.")
174
+
175
+ if __name__ == "__main__":
176
+ main()