AamirAli123's picture
Create app.py
257e8f6 verified
raw
history blame
8.81 kB
from openai import OpenAI
import gradio as gr
import os
import base64
import numpy as np
from PIL import Image
import io
import pandas as pd
from dotenv import load_env
load_env()
api_key = os.getenv("OPENAI_API_KEY")
client = OpenAI(
# This is the default and can be omitted
api_key = api_key,
)
def analyze_feedback(feedback_text):
"""Analyzes feedback text and returns a summary.
Args:
feedback_text (str): The text of the feedback to analyze.
Returns:
str: A summary of the feedback.
"""
chat_completion = client.chat.completions.create(
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": feedback_text}
]
,
model="gpt-3.5-turbo"
)
return chat_completion.choices[0].message.content
def process_files(uploaded_files):
results = [["File Name", "Summary", "Areas of Improvement", "Actionable Objectives","Sentiment", "Themes"]]
for file_path in uploaded_files:
# Extract file name from the file path
file_name = os.path.basename(file_path)
# Open and read the file content
with open(file_path, 'r', encoding='utf-8') as file:
feedback_text = file.read()
#print(feedback_text)
# Process the feedback text
processed_feedback = process_feedback(feedback_text)
#print ('processed', processed_feedback)
# Example result format for each file
file_result = {
"summary": processed_feedback['summary'],
"areas_of_improvement": processed_feedback['areas_of_improvement'],
"actionable_objectives": processed_feedback['actionable_objectives'],
"sentiment": processed_feedback['sentiment'],
"themes": processed_feedback['themes']
}
#print(file_result)
#print (type(file_result))
return feedback_text, file_result
def process_feedback(feedback_text):
# Example processing steps
# You need to replace these with your actual feedback analysis logic
#print (feedback_text)
summary = analyze_feedback("Provide the summary of the feedback first and then after the summary, analyze and list down the top achievements in this Feedback and pull out any key themes from the Feedback: " + feedback_text)
# Simple sentiment analysis
sentiment = analyze_feedback("What are the overall sentiment score and reasons for the score in this feedback, if 1 is negative and 10 is rated as positive. Provide responses as colon delimeted format: Who gave the Feedback:What was the sentiment score:why was the score given for this feedback: " + feedback_text)
# Theme identification (implement your logic)
themes = analyze_feedback("What are the key recurring positive and negative themes in this feedback: " + feedback_text)
#print ("Summ",summary)
#strengths = analyze_feedback("What are the key strengths in this feedback: " + feedback_text)
areas_of_improvement = analyze_feedback("Which hard and soft skills may need development according to this Feedback: " + feedback_text)
actionable_objectives = analyze_feedback("Suggest actionable objectives based on this feedback and steps to accomplish these objectives: " + feedback_text)
# This depends on how the response is formatted. You may need to adjust the parsing logic
sentiment_data = [] # This will be a list of dictionaries
print (sentiment)
# Example of processing (you'll need to adjust this based on actual response format)
for line in sentiment.split('\n'):
if line.strip():
parts = line.split(':')
if len(parts) >= 3:
sentiment_data.append({
"Giver": parts[0].strip(),
"Score": parts[1].strip(),
"Reason": parts[2].strip()
})
# Assign the results to analysis_results
analysis_results = {
"summary": summary,
"themes": themes,
"areas_of_improvement": areas_of_improvement,
"actionable_objectives": actionable_objectives,
"sentiment": sentiment_data
}
#print (analysis_results)
return analysis_results
def display_results(uploaded_files):
"""
Processes uploaded feedback files and displays the results.
Args:
uploaded_files (list): A list of file paths to uploaded feedback files.
Returns:
tuple: A tuple containing various analysis results or an empty string if no files were uploaded.
"""
feedback, results = process_files(uploaded_files)
if results:
# Extract each area of feedback from the dictionary
summary = results['summary'] if 'summary' in results else ""
areas_of_improvement = results['areas_of_improvement'] if 'areas_of_improvement' in results else ""
actionable_objectives = results['actionable_objectives'] if 'actionable_objectives' in results else ""
themes_text = results['themes'] if 'themes' in results else ""
#sentiments_text = results['sentiment'] if 'sentiment' in results else ""
sentiment_table=[]
if results:
for sentiment_entry in results['sentiment']:
entry_as_list = [sentiment_entry['Giver'], sentiment_entry['Score'], sentiment_entry['Reason']]
sentiment_table.append(entry_as_list)
# Create a Pandas DataFrame
df = pd.DataFrame(sentiment_table, columns=["Giver", "Score", "Reason"])
df = df.iloc[1:]
return summary, themes_text, areas_of_improvement, actionable_objectives,df
else:
return "","","","",[], None
def image_to_base64(image_path):
"""
Reads an image file and returns its base64 encoded representation.
Args:
image_path (str): The path to the image file.
Returns:
str: The base64 encoded representation of the image data.
"""
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
# Encode the logo image into base64
logo_base64 = image_to_base64("pixelpk_logo.png")
markdown_content = f"""
<img src="data:image/png;base64,{logo_base64}" alt="Feedback Logo" style="width: 100px; height: 100px; margin-top: 10px;" />
<p style="margin-top: 5px;">Feedback analyzer give employee/students feedback, providing key insights into strengths, areas for improvement, and overall sentiments.</p>
"""
# Custom CSS for styling the interface
custom_css = """
<style>
.gradio-container {
font-family: 'Helvetica Neue', Arial, sans-serif;
}
.gradio-accordion {
border-radius: 5px;
}
.gradio-accordion .gradio-tab {
padding: 10px;
}
.gradio-textbox {
height: auto;
min-height: 50px;
max-height: 300px; /* Adjust as needed */
overflow-y: auto; /* Enables vertical scrolling */
}
</style>
"""
with gr.Blocks(gr.themes.Monochrome(), css=custom_css) as demo:
# Display introductory markdown content
gr.Markdown(f"<center>{markdown_content}</center>")
# Layout elements in a row
with gr.Column():
# Upload button for selecting files
upload_button = gr.File(file_types=["txt"], file_count="multiple")
# Button to trigger analysis
submit_button = gr.Button("Submit")
# Accordion to display analysis results
with gr.Accordion("Analysis Results"):
# Tab for summary information
with gr.Tab("Summary"):
output_summary = gr.Textbox(label="Summary", lines = 4, placeholder="Summary will appear here...")
# Tab for key insights
with gr.Tab("Key Insights"):
output_improvement_areas = gr.Textbox(label="Key Insights", lines = 15, placeholder="Themes will appear here...")
# Tab for specific improvement areas
with gr.Tab("Improvement Areas"):
output_themes = gr.Textbox(label="Analysis", lines = 15, placeholder="Analysis will appear here...")
# Tab for actionable objectives
with gr.Tab("Objectives"):
output_actionable_objectives = gr.Textbox(label="Actionable Objectives", lines = 15, placeholder="Objectives will appear here...")
# Tab for sentiment analysis results
with gr.Tab("Sentiments"):
output_sentiment_table = gr.Dataframe(label="Sediment Analysis")
# Connect button click to analysis function
submit_button.click(
display_results,
inputs = [upload_button],
outputs = [
output_summary,
output_themes,
output_improvement_areas,
output_actionable_objectives,
output_sentiment_table
]
)
# Launch the Gradio interface
demo.launch(share = True)