Spaces:
Sleeping
Sleeping
File size: 8,063 Bytes
3c7d3dd a2141da c6b42fa 9b50846 29169b7 50959bf 5559752 a2141da 918d18e 5559752 a2141da 5559752 2711a3e e6598c0 5559752 db30916 5559752 fc910ad 5559752 86d9f43 5559752 86d9f43 5559752 86d9f43 5559752 953795c a2141da 3fe763d a2141da 5559752 909e9ab 5559752 909e9ab 5559752 a2141da 5559752 2711a3e 5559752 a2141da 5559752 a2141da 0519994 a2141da 7771bdc fc61cd6 69b5449 87c8add 909e9ab 87c8add 909e9ab 87c8add 75e9a80 2736c27 fc61cd6 7771bdc 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 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 |
import streamlit as st
import pandas as pd
from openai import OpenAI
import os
import json
import ast
import subprocess
TOKEN=os.getenv('HF_TOKEN')
subprocess.run(["huggingface-cli", "login", "--token", TOKEN, "--add-to-git-credential"])
from langchain_openai import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain.prompts.few_shot import FewShotPromptTemplate
from langchain.prompts.prompt import PromptTemplate
import re
from docx import Document
from io import StringIO
from langchain.schema.runnable import RunnableSequence
from langchain.schema.output_parser import StrOutputParser
from langchain.prompts import ChatPromptTemplate
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
from langchain.llms import HuggingFacePipeline
OPENAI_API_KEY = os.getenv("OPENAI_API")
# client = OpenAI(api_key=os.getenv("OPENAI_API")) #INSERT KEY INSODE HE QUOTES IN THE BRACKET
def barem_score(file_path, json_name):
# 1. Đọc file
df = pd.read_excel(file_path, sheet_name="Trang tính1")
df_data = df.iloc[2:, [1, 2, 3]].copy()
# 2. Lấy từ dòng thứ 3 trở đi (index = 2 trong pandas)
df_data.columns = ['Tiêu_chí_chính', 'Tiêu_chí_con', 'Nhan_xet']
# 4. Điền các tiêu chí chính nếu bị merge (NaN)
df_data['Tiêu_chí_chính'] = df_data['Tiêu_chí_chính'].fillna(method='ffill')
# 5. Loại bỏ các dòng trống (không có tiêu chí con)
df_metadata = df_data.dropna(subset=['Tiêu_chí_con'], how='all')
df_metadata['Nhan_xet'] = df_metadata['Nhan_xet'].fillna(method='ffill')
# 6. Đưa cột index ra đầu bảng
df_metadata = df_metadata[['Tiêu_chí_chính', 'Tiêu_chí_con', 'Nhan_xet']]
# 7. Xuất ra xem thử
df_metadata.to_json(f"{json_name}.json")
capy_barem = barem_score("data/capy_feedback.xlsx", "capy")
mqm_barem = barem_score("data/mqm_feedback.xlsx", "mqm")
ta_barem = barem_score("data/ta_feedback.xlsx", "ta")
import json
from pypdf import PdfReader
with open('capy.json', 'r', encoding='utf-8') as f:
capy_barem = str(json.load(f))
capy_barem = capy_barem.replace("{", '')
capy_barem = capy_barem.replace("}", '')
with open('mqm.json', 'r', encoding='utf-8') as f:
mqm_barem = str(json.load(f))
mqm_barem = mqm_barem.replace("{", '')
mqm_barem = mqm_barem.replace("}", '')
with open('ta.json', 'r', encoding='utf-8') as f:
ta_barem = str(json.load(f))
ta_barem = ta_barem.replace("{", '')
ta_barem = ta_barem.replace("}", '')
def read_pdf(pdf_doc):
pdf = PdfReader(pdf_doc)
raw_text = ''
for index,page in enumerate(pdf.pages):
raw_text += page.extract_text()
return raw_text
file_path = "data/mqm_proposal.pdf"
mqm_proposal = read_pdf(file_path)
file_path = "data/ta_proposal.pdf"
ta_proposal = read_pdf(file_path)
file_path = "data/capy_proposal.pdf"
capy_proposal = read_pdf(file_path)
# file_path = "data/mamnon_proposal.pdf"
# input = read_pdf(file_path)
# Function to grade the essay using GPT-4
def grade_essay(input):
# Sample prompt for grading using GPT-4
template = f"""
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.
Chấm bài theo thang điểm:
1. Research: 25
2. Xác định rõ vị trí của 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
Tổng: 110
Trả kết quả theo đúng format JSON bằng tiếng Việt:
I. Research: "score": <0-25>
1. Phân tích thị trường: <nhận xét chi tiết điểm yếu 3 gạch đầu dòng>
2. Phân tích nhãn hàng và đối thủ: <nhận xét chi tiết điểm yếu trong 3 gạch đầu dòng>",
II. Xác định rõ vị trí của nhãn hàng trong chiến dịch": "score": <0-20>
1. Xác định vấn đề truyền thông: <nhận xét chi tiết điểm yếu trong 3 gạch đầu dòng>
2. Xác định rõ mục tiêu của chiến dịch: <nhận xét chi tiết điểm yếu trong 3 gạch đầu dòng>
3.Nhìn nhận đúng vai trò của nhãn hàng trong chiến dịch: <nhận xét chi tiết điểm yếu trong 3 gạch đầu dòng>,
III. Phân tích đối tượng truyền thông": "score": <0-30>
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>",
IV/ Đề xuất chiến lược tiếp cận": "score": <0-10>
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>
V/ Ý tưởng lớn": "score": <0-10>. <tóm tắt điểm mạnh và điểm yếu>
"Tổng điểm": <0-110>
"""
examples = [
{
"bài làm": f"{capy_proposal}",
"nhận xét": f"{capy_barem}"
},
{
"bài làm": f"{mqm_proposal}",
"nhận xét": f"{mqm_barem}"
},
{
"bài làm": f"{ta_proposal}",
"nhận xét": f"{ta_barem}"
}
]
example_prompt = PromptTemplate(input_variables=["bài làm", "nhận xét"], template="{bài làm}\n{nhận xét}")
model = 'gpt'
if model == 'gpt':
template = template + f"""Hãy đánh giá bài sau:
{input}</s>
<|assistant|>"""
elif model == 'vilm':
template = """<|im_start|>system
""" + template + f"""<|im_end|>
<|im_start|>user
Hãy đánh giá bài sau: {input}
<|im_end|>
<|im_start|>assistant"""
prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
suffix=template,
input_variables=["input"]
)
llm = ChatOpenAI(
model="gpt-4o-mini",
api_key=OPENAI_API_KEY,
temperature=0.6
)
prompt = PromptTemplate(input_variables =['input'], template = template)
# prompt = prompt.format(input=input)
chain = RunnableSequence(prompt| llm)
ans = chain.invoke({'input': input})
feedback = re.findall("```\w{4}(.*)```", str(ans))[0]
return feedback
def main():
st.title("Marwuy Proposal feedback")
# State to store results
if 'results' not in st.session_state:
st.session_state.results = []
pdf_file = st.file_uploader("Upload proposal của bạn dưới dạng pdf", type=["pdf"])
if pdf_file is not None:
# File uploader for new essays to be graded (DOCX)
new_file = read_pdf(pdf_file)
# Grading button
if st.button("Grade Proposal"):
if new_file:
final_feedback = grade_essay(input = new_file)
# final_feedback = json.loads(ast.literal_eval(f"'''{final_feedback.strip()}'''"))
# df = pd.DataFrame.from_dict(final_feedback)
# df = df.T
# Store results in session state
st.session_state.results.append({
'Feedback': final_feedback
})
st.write("Feedback:")
st.write(final_feedback)
st.success("Hoàn thành chấm điểm.")
else:
st.error("Upload lại dưới định dạng pdf")
if __name__ == "__main__":
main() |