ngcanh commited on
Commit
5559752
·
verified ·
1 Parent(s): 5cbd01a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +151 -101
app.py CHANGED
@@ -8,125 +8,183 @@ import subprocess
8
  TOKEN=os.getenv('HF_TOKEN')
9
  subprocess.run(["huggingface-cli", "login", "--token", TOKEN, "--add-to-git-credential"])
10
  OPENAI_API_KEY = os.getenv("OPENAI_API")
11
-
 
 
 
 
 
12
  client = OpenAI(api_key=OPENAI_API_KEY) #INSERT KEY INSODE HE QUOTES IN THE BRACKET
13
  from docx import Document
14
 
 
 
 
15
 
16
- # Function to parse the feedback into barem components
17
- def parse_feedback(feedback):
18
- # You can customize this based on how GPT provides the feedback
19
- # Here, I assume feedback includes specific scoring lines like 'Content Relevance: X/25'
20
- scores = {
21
- 'Research': None,
22
- 'Xác định rõ vấn đề, mục tiêu và vai trò nhãn hàng trong chiến dịch': None,
23
- 'Phân tích đối tượng truyền thông': None,
24
- 'Đề xuất chiến lược tiếp cận': None,
25
- 'Ý tưởng lớn': None,
26
- 'Total Score': None
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
- }
30
-
31
- return scores
 
 
 
 
 
 
 
 
 
 
32
 
33
  # Function to grade the essay using GPT-4
34
- def grade_essay(essay, guided_data, barem):
35
  # Sample prompt for grading using GPT-4
36
- prompt = f"""
37
- 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.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
- Đánh giá dựa trên những đầu mục lớn và từng đầu mục nhỏ
41
- Research: Ensure that the proposal has evaluation for 1. Market, 2. brand and competitors, while seeing the trend, opportunities and threats
42
- 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
43
- 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
44
- Đề 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
45
- "Ý 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
46
-
47
- Here is the barem for grading:
48
- {barem}
49
 
50
- Here are examples of previously graded essays and their scores: {guided_data}
51
-
52
- Please grade the following essay and provide feedback:
53
- {essay}
54
- """
55
 
56
- # Call OpenAI's GPT-4 for grading
57
- response = client.chat.completions.create(model="gpt-4o-mini",
58
- messages=[
59
- {"role": "user", "content": prompt}
60
- ])
61
- return response.choices[0].message.content
62
- def read_pdf(pdf_reader):
63
- for page in pdf_reader.pages:
64
- all_text = ""
65
- page_text = page.extract_text()
66
- if page_text:
67
- all_text += page_text + "\n"
68
- return all_text
69
-
70
- # # Function to export results to CSV
71
- # def export_to_csv(data):
72
- # df = pd.DataFrame(data)
73
- # df.to_csv('essay_grades.csv', index=False)
74
-
75
- # Main function for the Streamlit app
76
  def main():
77
  st.title("Marwuy Proposal feedback")
78
 
79
- # Predefined barem for grading
80
- barem = """
81
- INSTRUCTIONS FOR GRADING
82
- 1. Research: 25
83
- 2. Xác định rõ vấn đề, mục tiêu và vai trò nhãn hàng trong chiến dịch: 20
84
- 3. Phân tích đối tượng truyền thông: 30
85
- 4. Đề xuất chiến lược tiếp cận: 10
86
- 5. Ý tưởng lớn: 10
87
-
88
- Total: 110
89
- """
90
 
91
  # State to store results
92
  if 'results' not in st.session_state:
93
  st.session_state.results = []
94
 
95
- # File uploader for example graded essays (DOCX)
96
- # example_files = st.file_uploader("Upload 10 example graded essays (DOCX)", type=["docx"], accept_multiple_files=True)
97
- for filename in os.listdir("data"):
98
- if filename.lower().endswith(".pdf"):
99
- pdf_path = os.path.join("data", filename)
100
- with open(pdf_path, "rb") as pdf_file:
101
- pdf_reader = PyPDF2.PdfReader(pdf_file)
102
- example_files = read_pdf(pdf_reader)
103
-
104
-
105
-
106
- # File uploader for corresponding scores (DOCX)
107
- # scores_file = st.file_uploader("Upload the json file containing corresponding scores", type=["xlsx"])
108
- # Open and read the JSON file with utf-8 encoding
109
- with open('barem.json', 'r', encoding='utf-8') as file:
110
- scores_file = json.load(file)
111
-
112
  # File uploader for new essays to be graded (DOCX)
113
- pdf_file = st.file_uploader("Upload proposal to be graded", type=["pdf"], accept_multiple_files=True)
114
- pdf_reader = PyPDF2.PdfReader(pdf_file)
115
- new_file = read_pdf(pdf_reader)
116
  # Grading button
117
- if st.button("Grade Essays"):
118
- if example_files and scores_file and new_file:
119
-
120
- # Grading the new essay using the provided barem and example graded essays
121
- result = grade_essay(new_file, example_files, barem)
122
-
123
- # Parse feedback into barem components
124
- parsed_scores = parse_feedback(result)
125
-
126
  # Store results in session state
127
  st.session_state.results.append({
128
  'Essay File': new_file.name,
129
- **parsed_scores,
130
  'Feedback': result,
131
  })
132
 
@@ -138,14 +196,6 @@ def main():
138
  else:
139
  st.error("Please upload a proposal in pdf")
140
 
141
- # # Export results button always visible
142
- # with st.sidebar:
143
- # if st.button("Export All Results to CSV"):
144
- # if st.session_state.results:
145
- # export_to_csv(st.session_state.results)
146
- # st.success("All results exported to essay_grades.csv")
147
- # else:
148
- # st.warning("No results to export.")
149
 
150
  if __name__ == "__main__":
151
  main()
 
8
  TOKEN=os.getenv('HF_TOKEN')
9
  subprocess.run(["huggingface-cli", "login", "--token", TOKEN, "--add-to-git-credential"])
10
  OPENAI_API_KEY = os.getenv("OPENAI_API")
11
+ from langchain_openai import ChatOpenAI
12
+ import os
13
+ from langchain.prompts import PromptTemplate
14
+ from langchain.prompts.few_shot import FewShotPromptTemplate
15
+ from langchain.prompts.prompt import PromptTemplate
16
+ import re
17
  client = OpenAI(api_key=OPENAI_API_KEY) #INSERT KEY INSODE HE QUOTES IN THE BRACKET
18
  from docx import Document
19
 
20
+ from langchain.schema.runnable import RunnableSequence
21
+ from langchain.schema.output_parser import StrOutputParser
22
+ from langchain.prompts import ChatPromptTemplate
23
 
24
+ import torch
25
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
26
+ from langchain.llms import HuggingFacePipeline
27
+ import os
 
 
 
 
 
 
 
28
 
29
+ import pandas as pd
30
+
31
+ def barem_score(file_path, json_name):
32
+ # 1. Đọc file
33
+
34
+ df = pd.read_excel(file_path, sheet_name="Trang tính1")
35
+ df_data = df.iloc[2:, [1, 2, 3]].copy()
36
+
37
+ # 2. Lấy từ dòng thứ 3 trở đi (index = 2 trong pandas)
38
+ df_data.columns = ['Tiêu_chí_chính', 'Tiêu_chí_con', 'Nhan_xet']
39
+
40
+ # 4. Điền các tiêu chí chính nếu bị merge (NaN)
41
+ df_data['Tiêu_chí_chính'] = df_data['Tiêu_chí_chính'].fillna(method='ffill')
42
+
43
+ # 5. Loại bỏ các dòng trống (không có tiêu chí con)
44
+ df_metadata = df_data.dropna(subset=['Tiêu_chí_con'], how='all')
45
+ df_metadata['Nhan_xet'] = df_metadata['Nhan_xet'].fillna(method='ffill')
46
+
47
+ # 6. Đưa cột index ra đầu bảng
48
+ df_metadata = df_metadata[['Tiêu_chí_chính', 'Tiêu_chí_con', 'Nhan_xet']]
49
+ # 7. Xuất ra xem thử
50
+ df_metadata.to_json(f"{json_name}.json")
51
+
52
+ capy_barem = barem_score("data/[ MARWUY - SƯ TỔ MKT] - Feedback kết quả team CAPYRUBY.xlsx", "capy")
53
+ mqm_barem = barem_score("data/[MARWUY - SƯ TỔ MKT] - Feedback kết quả Mèo Quy Mả.xlsx", "mqm")
54
+ ta_barem = barem_score("data/_[MARWUY - SƯ TỔ MKT] - Feedback kết quả T&A.xlsx", "ta")
55
+
56
+ import json
57
+ from pypdf import PdfReader
58
+ with open('capy.json', 'r', encoding='utf-8') as f:
59
+ capy_barem = str(json.load(f))
60
+ capy_barem = capy_barem.replace("{", '')
61
+ capy_barem = capy_barem.replace("}", '')
62
+ with open('mqm.json', 'r', encoding='utf-8') as f:
63
+ mqm_barem = str(json.load(f))
64
+ mqm_barem = mqm_barem.replace("{", '')
65
+ mqm_barem = mqm_barem.replace("}", '')
66
+ with open('ta.json', 'r', encoding='utf-8') as f:
67
+ ta_barem = str(json.load(f))
68
+ ta_barem = ta_barem.replace("{", '')
69
+ ta_barem = ta_barem.replace("}", '')
70
+
71
+ def read_pdf(pdf_doc):
72
+ pdf = PdfReader(pdf_doc)
73
+ raw_text = ''
74
+ for index,page in enumerate(pdf.pages):
75
+ raw_text += page.extract_text()
76
+
77
+ return raw_text
78
 
79
+
80
+
81
+ file_path = "data/Mèo Quy Mã + Bong Bóng đẹp trai quá đê_official - Hân Trịnh.pdf"
82
+ mqm_proposal = read_pdf(file_path)
83
+
84
+ file_path = "data/T&A + Bong Bóng đẹp trai quá đê (1) - Thinh Quach.pdf"
85
+ ta_proposal = read_pdf(file_path)
86
+
87
+ file_path = "data/CAPYRUBY + Bong Bóng đẹp trai quá đê - Lê Ngọc.pdf"
88
+ capy_proposal = read_pdf(file_path)
89
+
90
+ # file_path = "data/Mầm Non Bong Bóng đẹp trai quá đê - Trâm Đỗ.pdf"
91
+ # input = read_pdf(file_path)
92
 
93
  # Function to grade the essay using GPT-4
94
+ def grade_essay(input):
95
  # Sample prompt for grading using GPT-4
96
+ template = f"""
97
+
98
+ Bạn là một giám khảo chấm và đánh giá proposal marketing và kinh doanh dự trên barem điểm. Hãy đưa ra những phán xét gay gắt và dài.
99
+ Chấm bài theo thang điểm:
100
+ 1. Research: 25
101
+ 2. Xác định rõ vấn đề, mục tiêu và vai trò nhãn hàng trong chiến dịch: 20
102
+ 3. Phân tích đối tượng truyền thông: 30
103
+ 4. Đề xuất chiến lược tiếp cận: 10
104
+ 5. Ý tưởng lớn: 10
105
+
106
+ Tổng: 110
107
+ Trả kết quả theo đúng format JSON bằng tiếng Việt, không thêm giải thích ngoài JSON:
108
+
109
+
110
+ "Research": "score": <0-25>, "comment": "1. Market: <nhận xét chi tiết>, 2. brand and competitors: <nhận xét chi tiết>",
111
+ "Xác định rõ vấn đề, mục tiêu và vai trò nhãn hàng trong chiến dịch": "score": <0-20>, "comment": "1. Xác định vấn đề truyền thông: <nhận xét chi tiết>, 2. Xác định rõ mục tiêu của chiến dịch: <nhận xét chi tiết>, 3.Nhìn nhận đúng vai trò của Brand trong chiến dịch: <nhận xét chi tiết>",
112
+ "Phân tích đối tượng truyền thông": "score": <0-30>, "comment": "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: <nhận xét chi tiết>, 2.Insight liên quan chặt chẽ và có tính khả thi cao với thương hiệu: <nhận xét chi tiết>, 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: <nhận xét chi tiết>",
113
+ "Đề xuất chiến lược tiếp cận": "score": <0-10>, "comment": "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 đó: <nhận xét chi tiết>, 2. Mức độ phù hợp của chiến lược đối với Brand và đối tượng mục tiêu: <nhận xét chi tiết>, 3. Mức độ đan xen yếu tố Brand role vào chiến lược tiếp cận: <nhận xét chi tiết>",
114
+ "Ý tưởng lớn": "score": <0-10>, "comment": "<tóm tắt điểm mạnh và điểm yếu>"
115
+ "Tổng điểm": <0-110>
116
+ """
117
 
118
+ examples = [
119
+ {
120
+ "bài làm": f"{capy_proposal}",
121
+ "nhận xét": f"{capy_barem}"
122
+ },
123
+ {
124
+ "bài làm": f"{mqm_proposal}",
125
+ "nhận xét": f"{mqm_barem}"
126
+ },
127
+ {
128
+ "bài làm": f"{ta_proposal}",
129
+ "nhận xét": f"{ta_barem}"
130
+ }
131
+ ]
132
+
133
+ example_prompt = PromptTemplate(input_variables=["bài làm", "nhận xét"], template="{bài làm}\n{nhận xét}")
134
+
135
+ model = 'gpt'
136
+ if model == 'gpt':
137
+ template = template + f"""Hãy đánh giá bài sau:
138
+ {input}</s>
139
+ <|assistant|>"""
140
+ elif model == 'vilm':
141
+ template = """<|im_start|>system
142
+ """ + template + f"""<|im_end|>
143
+ <|im_start|>user
144
+ Hãy đánh giá bài sau: {input}
145
+ <|im_end|>
146
+ <|im_start|>assistant"""
147
+ prompt = FewShotPromptTemplate(
148
+ examples=examples,
149
+ example_prompt=example_prompt,
150
+ suffix=template,
151
+ input_variables=["input"]
152
+ )
153
+ llm = ChatOpenAI(
154
+ model="gpt-4o-mini",
155
+ api_key=os.getenv("OPENAI_API_KEY"),
156
+ temperature=0.6
157
+ )
158
+
159
+ prompt = PromptTemplate(input_variables =['input'], template = template)
160
+ # prompt = prompt.format(input=input)
161
+ chain = RunnableSequence(prompt| llm)
162
+
163
+ ans = chain.invoke({'input': input})
164
+ feedback = re.findall("```\w{4}(.*)```", str(ans))[0]
165
 
 
 
 
 
 
 
 
 
 
166
 
167
+ return feedback
 
 
 
 
168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  def main():
170
  st.title("Marwuy Proposal feedback")
171
 
 
 
 
 
 
 
 
 
 
 
 
172
 
173
  # State to store results
174
  if 'results' not in st.session_state:
175
  st.session_state.results = []
176
 
177
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  # File uploader for new essays to be graded (DOCX)
179
+ pdf_file = st.file_uploader("Upload proposal to be graded", type=["pdf"], accept_multiple_files=False)
180
+ new_file = read_pdf(pdf_file)
 
181
  # Grading button
182
+ if st.button("Grade Proposal"):
183
+ if new_file:
184
+ result = grade_essay(input = new_file)
 
 
 
 
 
 
185
  # Store results in session state
186
  st.session_state.results.append({
187
  'Essay File': new_file.name,
 
188
  'Feedback': result,
189
  })
190
 
 
196
  else:
197
  st.error("Please upload a proposal in pdf")
198
 
 
 
 
 
 
 
 
 
199
 
200
  if __name__ == "__main__":
201
  main()