Spaces:
Running
Running
File size: 7,075 Bytes
3c7d3dd a2141da c6b42fa 29169b7 50959bf a2141da fc910ad a2141da fc910ad a2141da fc910ad a2141da fc910ad a2141da c6b42fa a2141da d8aac59 a2141da 0519994 a2141da c6b42fa a2141da 0519994 a2141da c6b42fa a2141da c6b42fa a2141da c6b42fa a2141da c6b42fa a2141da c6b42fa a2141da |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 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 58 59 60 61 62 63 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 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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
import streamlit as st
import pandas as pd
from openai import OpenAI
import os
import json
IMPORT pypdf
import subprocess
TOKEN=os.getenv('HF_TOKEN')
subprocess.run(["huggingface-cli", "login", "--token", TOKEN, "--add-to-git-credential"])
OPENAI_API_KEY = os.getenv("OPENAI_API")
client = OpenAI(api_key=OPENAI_API_KEY) #INSERT KEY INSODE HE QUOTES IN THE BRACKET
from docx import Document
# Function to parse the feedback into rubric components
def parse_feedback(feedback):
# You can customize this based on how GPT provides the feedback
# Here, I assume feedback includes specific scoring lines like 'Content Relevance: X/25'
scores = {
'Research': None,
'Xác định rõ vấn đề, mục tiêu và vai trò nhãn hàng trong chiến dịch': None,
'Phân tích đối tượng truyền thông': None,
'Đề xuất chiến lược tiếp cận': None,
'Ý tưởng lớn': None,
'Total Score': None
}
# lines = feedback.split('\n')
# for line in lines:
# for key in scores.keys():
# if key in line:
# score = line.split(':')[-1].strip()
# scores[key] = score
# # Assume that the last numerical value mentioned is the total score
# total_score = sum([int(score) for score in scores.values() if score])
# scores['Total Score'] = total_score
return scores
# Function to grade the essay using GPT-4
def grade_essay(essay, guided_data, rubric):
# Sample prompt for grading using GPT-4
prompt = f"""
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.
Đánh giá dựa trên những đầu mục lớn và từng đầu mục nhỏ
Research: Ensure that the proposal has evaluation for 1. Market, 2. brand and competitors, while seeing the trend, opportunities and threats
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
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
Đề 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
"Ý 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
Here is the rubric for grading:
{rubric}
Here are examples of previously graded essays and their scores: {guided_data}
Please grade the following essay and provide feedback:
{essay}
"""
# Call OpenAI's GPT-4 for grading
response = client.chat.completions.create(model="gpt-4o-mini",
messages=[
{"role": "user", "content": prompt}
])
return response.choices[0].message.content
def read_pdf(pdf_reader):
for page in pdf_reader.pages:
page_text = page.extract_text()
if page_text:
all_text += page_text + "\n"
return all_text
# Function to export results to CSV
def export_to_csv(data):
df = pd.DataFrame(data)
df.to_csv('essay_grades.csv', index=False)
# Main function for the Streamlit app
def main():
st.title("Marwuy Proposal feedback")
# Predefined rubric for grading
rubric = """
INSTRUCTIONS FOR GRADING
1. Research: 25
2. Xác định rõ vấn đề, mục tiêu và vai trò nhãn hàng trong chiến dịch: 20
3. Phân tích đối tượng truyền thông: 30
4. Đề xuất chiến lược tiếp cận: 10
5. Ý tưởng lớn: 10
Total: 110
"""
# State to store results
if 'results' not in st.session_state:
st.session_state.results = []
# File uploader for example graded essays (DOCX)
# example_files = st.file_uploader("Upload 10 example graded essays (DOCX)", type=["docx"], accept_multiple_files=True)
for filename in os.listdir("data"):
if filename.lower().endswith(".pdf"):
pdf_path = os.path.join(pdf_directory, filename)
with open(pdf_path, "rb") as pdf_file:
pdf_reader = PyPDF2.PdfReader(pdf_file)
example_files = read_pdf(pdf_reader)
# File uploader for corresponding scores (DOCX)
# scores_file = st.file_uploader("Upload the json file containing corresponding scores", type=["xlsx"])
# Open and read the JSON file with utf-8 encoding
with open('abs.json', 'r', encoding='utf-8') as file:
scores_file = json.load(file)
# File uploader for new essays to be graded (DOCX)
pdf_file = st.file_uploader("Upload proposal to be graded", type=["pdf"], accept_multiple_files=True)
pdf_reader = PyPDF2.PdfReader(pdf_file)
new_file = read_pdf(pdf_reader)
# Grading button
if st.button("Grade Essays"):
if example_files and scores_file and new_file:
# Grading the new essay using the provided rubric and example graded essays
result = grade_essay(new_file, example_files, rubric)
# Parse feedback into rubric components
parsed_scores = parse_feedback(result)
# Store results in session state
st.session_state.results.append({
'Essay File': new_file.name,
**parsed_scores,
'Feedback': result,
})
# Display the grading feedback
st.write("Feedback:")
st.write(result)
st.success("Grading completed for all uploaded essays.")
else:
st.error("Please upload all required files.")
# Export results button always visible
with st.sidebar:
if st.button("Export All Results to CSV"):
if st.session_state.results:
export_to_csv(st.session_state.results)
st.success("All results exported to essay_grades.csv")
else:
st.warning("No results to export.")
if __name__ == "__main__":
main() |