Persuade / app.py
paragon-analytics's picture
Update app.py
22cd94e
raw
history blame
5.39 kB
# Import packages:
import numpy as np
import matplotlib.pyplot as plt
import re
# tensorflow imports:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import losses
from tensorflow.keras import layers
from tensorflow.keras.layers.experimental import preprocessing
from tensorflow.keras.optimizers import RMSprop
# # keras imports:
from keras.models import Model
from keras.layers import LSTM, Activation, Dense, Dropout, Input, Embedding, RepeatVector, TimeDistributed
from keras.preprocessing.text import Tokenizer
from keras_preprocessing import sequence
from tensorflow.keras.utils import to_categorical
from keras.callbacks import EarlyStopping
from keras.models import Sequential
from keras import layers
from keras.backend import clear_session
import pickle
import gradio as gr
import yake
import spacy
from spacy import displacy
import streamlit as st
import spacy_streamlit
nlp = spacy.load('en_core_web_sm')
kw_extractor = yake.KeywordExtractor()
custom_kw_extractor = yake.KeywordExtractor(lan="en", n=2, dedupLim=0.2, top=10, features=None)
max_words = 2000
max_len = 111
# load the model from disk
filename = 'lstm_model.sav'
lmodel = pickle.load(open(filename, 'rb'))
# load the model from disk
filename = 'tokenizer.pickle'
tok = pickle.load(open(filename, 'rb'))
def main(text):
X_test = str(text).lower()
l = []
l.append(X_test)
test_sequences = tok.texts_to_sequences(l)
test_sequences_matrix = sequence.pad_sequences(test_sequences,maxlen=max_len)
lstm_prob = lmodel.predict(test_sequences_matrix.tolist()).flatten()
lstm_pred = np.where(lstm_prob>=0.5,1,0)
# Get Keywords:
keywords = custom_kw_extractor.extract_keywords(X_test)
letter = []
score = []
for i in keywords:
if i[1]>0.4:
a = "+++"
elif (i[1]<=0.4) and (i[1]>0.1):
a = "++"
elif (i[1]<=0.1) and (i[1]>0.01):
a = "+"
else:
a = "NA"
letter.append(i[0])
score.append(a)
keywords = [(letter[i], score[i]) for i in range(0, len(letter))]
# Get NER:
# NER:
doc = nlp(text)
sp_html = displacy.render(doc, style="ent", page=True, jupyter=False)
NER = (
""
+ sp_html
+ ""
)
return {"Persuasive": float(lstm_prob[0]), "Non-Persuasive": 1-float(lstm_prob[0])},keywords,NER
title = "Welcome to **PersuAID** πŸͺ"
description = """
Before spending money on making your next new ad, try PersuAID to check how persuasive your ad is. Our AI models have been trained on tens of thousands of ad transcripts. Simply paste your text (ad transcript) below and hit Analyze. Click on the example ad transcripts to see how it works ✨
"""
with gr.Blocks(title=title) as demo:
gr.Markdown(f"## {title}")
gr.Markdown("""![marketing](file/marketing.jpg)""")
gr.Markdown(description)
gr.Markdown("""---""")
text = gr.Textbox(label="Text:",lines=2, placeholder="Please enter text here ...")
submit_btn = gr.Button("Analyze")
# tweet_btn = gr.Button("Tweet")
with gr.Column(visible=True) as output_col:
label = gr.Label(label = "Predicted Label")
impplot = gr.HighlightedText(label="Important Words", combine_adjacent=False).style(
color_map={"+++": "royalblue","++": "cornflowerblue",
"+": "lightsteelblue", "NA":"white"})
NER = gr.HTML(label = 'NER:')
submit_btn.click(
main,
text,
[label,impplot,NER], api_name="PrsTalk"
)
gr.Markdown("## Examples ✨")
gr.Examples(["What is performance? Zero to Sixty or Sixty to Zero? How a car performs a quarter mile or a quarter century? Is performance about the joy of driving or the importance of surviving?\
To us performance is not about doing one thing well ... it is about doing everything well .. because in the end everything matters.\
Performance without compromise.\
That is what drives you..... Mercedes Benz",
"Exhilaration. Unlike any other. Mercedes Benz delivers heart-racing performance with a blend of precision engineering and a little lightning under the hood. For those who see power as the ultimate luxury.",
"Unleash your wild side with new Feline Mascara. Feline's new quick charge brush captures every lash. Instant volume, ferocious full lash density. New Feline Mascara from Loreal Makeup Designer, Paris. Add new liner noir to complete your feline look.",
"To stay competitive, you're constantly searching for better ways to orchestrate the flow of information. How do you get more out of your PCS? How can you make the most of your existing systems? What can be done to streamline your organization? More often than not, the answer is IBM Client/Server. For more and more companies, IBM Client/Server is the key to getting everyone working in concert. We've done it for hundreds of companies...we can do it for you. IBM.",
"What could be more fun than having lunch with Dinosaurs, Goldfish or a few Shining Stars? They're 9 soups made especially for kids. They're fun favorites from Campbell's featuring 3 new varieties with pasta shapes: Tomato Goldfish, Chicken Goldfish and Dinosaur. Put fun where kids least expect it...in a soup bowl. Campbell's. M'm! M'm! Good!"],
[text], [label,impplot,NER], main, cache_examples=True)
demo.launch()