File size: 6,632 Bytes
3c7d3dd
a2141da
 
 
c6b42fa
0e7a596
29169b7
50959bf
 
a2141da
 
 
 
 
 
f6db900
a2141da
 
 
 
fc910ad
 
 
 
 
a2141da
fc910ad
 
a2141da
 
 
 
 
f6db900
a2141da
 
f6db900
a2141da
 
 
 
 
 
 
 
 
f6db900
 
a2141da
 
 
 
 
d8aac59
a2141da
 
0519994
a2141da
 
 
 
c6b42fa
 
e33396a
c6b42fa
 
 
13b86a6
c6b42fa
e33396a
 
 
 
a2141da
 
 
0519994
a2141da
f6db900
 
a2141da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6b42fa
 
 
7117cba
c6b42fa
 
 
 
 
a2141da
 
c6b42fa
 
f6db900
c6b42fa
 
a2141da
c6b42fa
 
 
a2141da
 
c6b42fa
 
a331d36
 
a2141da
a331d36
 
a2141da
a331d36
 
 
 
 
 
a2141da
a331d36
 
 
a2141da
a331d36
a2141da
10fa374
 
 
 
 
 
 
 
 
 
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
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()