Compliance_Test / app.py
dwipper's picture
Update app.py
b2d04df
raw
history blame
7.93 kB
import os
import openai
import datetime
import gradio as gr
import json
from jinja2 import Template
import csv
# openai.api_key = os.getenv("OPENAI_API_KEY")
openai.api_key = "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"
#Write log file function
def append_to_qalog(your_role, school_selection, output_format, input_text, gpt_response,response_time,question_cost):
# Define the filename
filename = "qalog.csv"
# Check if file exists to decide if headers are needed
file_exists = os.path.isfile(filename)
# Open the file in append mode
with open(filename, 'a', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=["your_role", "school_selection", "output_format", "input_text", "gpt_response","response_time","question_cost"])
# If the file didn't exist, write the headers first
if not file_exists:
writer.writeheader()
# Append the data
writer.writerow({
"your_role": your_role,
"school_selection": school_selection,
"output_format": output_format,
"input_text": input_text,
"gpt_response": gpt_response,
"response_time": response_time,
"question_cost": question_cost
})
#Chatbot Function
def chatbot(your_role,school_selection,output_format,input_text):
start_time = datetime.datetime.now()
# Read in the prompt header for engagement analysis
with open('prompts/nili_analysis_header.txt', 'r') as file:
header = file.read()
# school_selection holds an array of one or more schools, so create a comma delimited str to process.
print(school_selection)
#str=",".join(school_selection)
# Read the Hydrated policies
policies = ''
folder_path = 'nili_hydrated_policies'
for school in school_selection:
file_path = f"{folder_path}/{school}.txt"
try:
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
if policies: # If 'policies' already has content, add separator before appending
policies += "\n----------\n"
policies += content
except FileNotFoundError:
print(f"File {file_path} not found!")
with open('combined_policies.txt', 'w', encoding='utf-8') as out_file:
out_file.write(policies)
#print(policies)
# Insert into prompt
with open("prompts/nili_engagement_user_v2.j2", "r") as file:
#with open("prompts/nili_engagement_user_v3.j2", "r") as file:
template_content = file.read()
# Create a Jinja2 template from the content
template = Template(template_content)
# Render the template with the policy JSON
analysis_input = template.render(policies=policies, question=input_text,format=output_format)
with open('analysis_input.txt', 'w', encoding='utf-8') as out_file:
out_file.write(analysis_input)
response = openai.ChatCompletion.create(
model="gpt-4",
# model="gpt-3.5-turbo",
temperature=0,
messages=[
{
"role": "system",
"content": header
},
{
"role": "user",
"content": analysis_input
}
]
)
gpt_response = response.choices[0].message["content"]
tokens_used = response.usage
question_cost = (tokens_used.get('total_tokens', 0) / 1000) * .03
#print(question_cost)
with open('response.txt', 'w', encoding='utf-8') as out_file:
out_file.write(gpt_response)
"""print(ui_examples)
# Read the csv file
with open('examples/examples_v3.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
next(reader) # Skip the header row
for row in reader:
ui_examples.append([convert_to_none(item) for item in row])
print(ui_examples)"""
# Define the style and content
label_text = "NILI Response"
color = "#6562F4"
background_color = "white"
border_radius = "10px" # You can adjust this value as needed
response_label = f'<h3 style="color: {color}; background-color: {background_color}; border-radius: {border_radius}; padding: 10px;display: inline-block;">{label_text}</h3>'
end_time = datetime.datetime.now()
response_time = end_time - start_time
append_to_qalog(your_role, school_selection, output_format, input_text, gpt_response,response_time,question_cost)
return response_label,gpt_response
def load_example(example_id):
global ui_examples
return ui_examples[example_id][0]
#Gradio UI
CIMStheme = gr.themes.Soft().set(button_primary_background_fill='#6562F4')
# Initialize an empty list to store the examples
ui_examples = []
nili_response = "Test"
# Function to convert 'None' string to None object
def convert_to_none(value):
return None if value == 'None' else value
# Read the csv file
with open('examples/examples_v2.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
next(reader) # Skip the header row
for row in reader:
ui_examples.append([convert_to_none(item) for item in row])
#response_label='<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Formatted Text</title><style>.formatted-text {color: black;font-weight: bold;text-align: left;}</style></head><body><div class="formatted-text">NILI Response</div></body></html>'
# Define the style and content
label_text = "NILI Response"
color = "#6562F4"
background_color = "white"
border_radius = "10px" # You can adjust this value as needed
response_label = f'<h3 style="color: {color}; background-color: {background_color}; border-radius: {border_radius}; padding: 10px;display: inline-block;">{label_text}</h3>'
with gr.Blocks(CIMStheme) as iface:
with gr.Row():
with gr.Column(scale=2):
gr.Image(label="Logo",value="CIMS Logo Purple.png",width=10,show_download_button=False,interactive=False,show_label=False,elem_id="logo",container=False)
with gr.Column(scale=2):
#gr.Textbox(value="# NILI - Powered by CIMS.AI",show_label=False,interactive=False,text_align="center",elem_id="CIMSTitle")
gr.Markdown(value="# NILI - Powered by CIMS.AI")
with gr.Column(scale=2):
gr.Markdown("")
with gr.Row():
with gr.Column():
gr.Interface(fn=chatbot,
inputs=[
gr.components.Dropdown(["Student Athlete","Parent","Athletic Director"],multiselect=False,info="Select a role.",label="User Role"),
gr.components.Dropdown(["Stanford","CU","LSU","CMU","Tulane","Cal Poly","Long Beach State University","Auburn"],multiselect=True,info="Select one or more schools. This will help set the context of your question.",label="School Context"),
gr.components.Dropdown(["Summary","Detailed Analysis","Table"],multiselect=False,info="Select the desired output format.",label="Output Format"),
gr.components.Textbox(lines=5, placeholder="Enter your question here", label="NIL Question")],
outputs=[
gr.components.Markdown(response_label),
gr.components.HTML(label="NILI Response")
],
description="Ask any question about Name, Image, Likeness (NIL)",
allow_flagging="manual",
examples=ui_examples,
flagging_options=["The response is incorrect","The response is inappropriate","The response doesn't make sense"]
)
with gr.Row():
with gr.Column():
gr.HTML('<center><i>CIMS.AI Confidential 2023</i></center>')
iface.launch(share=True)