Spaces:
Running
Running
Update app.py
Browse files
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
|
|
|
|
|
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 |
-
|
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 |
-
st.
|
58 |
-
|
59 |
-
|
60 |
-
st.
|
61 |
-
|
62 |
-
|
63 |
-
st.
|
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 |
-
for
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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()
|