ngcanh's picture
Update app.py
0e7a596 verified
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 barem 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
}
return scores
# Function to grade the essay using GPT-4
def grade_essay(essay, guided_data, barem):
# Sample prompt for grading using GPT-4
prompt = f"""
You are an consultant that grades marketing and business proposal based on a provided barem, 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 barem for grading:
{barem}
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:
all_text = ""
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 barem for grading
barem = """
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("data", 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('barem.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 barem and example graded essays
result = grade_essay(new_file, example_files, barem)
# Parse feedback into barem 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 uploaded proposal.")
else:
st.error("Please upload a proposal in pdf")
# # 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()