Spaces:
Runtime error
Runtime error
File size: 7,988 Bytes
a87bc00 2e83a41 a87bc00 1726132 a87bc00 cd8ad01 529eea1 a87bc00 22af537 a87bc00 7b11062 d887fe7 a87bc00 c27c36d a87bc00 aa5087f 8b674fc a87bc00 d963f31 a87bc00 5f546a1 a87bc00 5f546a1 a87bc00 c90d42e a87bc00 c90d42e a87bc00 c90d42e a87bc00 1726132 e030268 1726132 a87bc00 5577484 a87bc00 1726132 a87bc00 7fa8edb a87bc00 5577484 a87bc00 5696ea4 7fa8edb 5696ea4 7a4b822 bc86dbe a87bc00 d7c764c 427074d d7c764c e9f9b30 d7c764c f10fd87 d7c764c ed4ccd5 d7c764c a87bc00 6542f5d 5577484 6542f5d 5577484 a82e853 6542f5d 76ec819 529eea1 67f8b07 529eea1 7a966d7 529eea1 6542f5d 529eea1 76ec819 a87bc00 6542f5d bc86dbe 7a4b822 41f896c 22af537 41f896c 6542f5d bc86dbe 7a4b822 41f896c d332967 41f896c 6542f5d bc86dbe 6542f5d a87bc00 bc86dbe d7c764c 6542f5d a87bc00 d7c764c a87bc00 6542f5d bc86dbe 6542f5d d7c764c 6542f5d 5a2e6b5 9a06070 872d79d 6bd38d3 a87bc00 5a2e6b5 |
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 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 |
# -*- coding: utf-8 -*-
"""
# MANIFESTO ANALYSIS
"""
##IMPORTING LIBRARIES
import random
import matplotlib.pyplot as plt
import nltk
from nltk.tokenize import word_tokenize,sent_tokenize
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.probability import FreqDist
from cleantext import clean
import textract
import urllib.request
import nltk.corpus
from nltk.text import Text
import io
from io import StringIO,BytesIO
import sys
import pandas as pd
import cv2
import re
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
from textblob import TextBlob
from PIL import Image
import os
import gradio as gr
from zipfile import ZipFile
import contractions
import unidecode
nltk.download('stopwords')
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('words')
"""## PARSING FILES"""
#def Parsing(parsed_text):
#parsed_text=parsed_text.name
#raw_party =parser.from_file(parsed_text)
# raw_party = raw_party['content']
# return clean(raw_party)
def Parsing(parsed_text):
parsed_text=parsed_text.name
raw_party =textract.process(parsed_text, encoding='ascii',method='pdfminer')
return clean(raw_party)
#Added more stopwords to avoid irrelevant terms
stop_words = set(stopwords.words('english'))
stop_words.update('ask','much','thank','etc.', 'e', 'We', 'In', 'ed','pa', 'This','also', 'A', 'fu','To','5','ing', 'er', '2')
"""## PREPROCESSING"""
def clean_text(text):
'''
The function which returns clean text
'''
text = text.encode("ascii", errors="ignore").decode("ascii") # remove non-asciicharacters
text=unidecode.unidecode(text)# diacritics remove
text=contractions.fix(text) # contraction fix
text = re.sub(r"\n", " ", text)
text = re.sub(r"\n\n", " ", text)
text = re.sub(r"\t", " ", text)
text = re.sub(r"/ ", " ", text)
text = text.strip(" ")
text = re.sub(" +", " ", text).strip() # get rid of multiple spaces and replace with a single
text = [word for word in text.split() if word not in stop_words]
text = ' '.join(text)
return text
# text_Party=clean_text(raw_party)
def Preprocess(textParty):
'''
Removing special characters extra spaces
'''
text1Party = re.sub('[^A-Za-z0-9]+', ' ', textParty)
#Removing all stop words
pattern = re.compile(r'\b(' + r'|'.join(stopwords.words('english')) + r')\b\s*')
text2Party = pattern.sub('', text1Party)
# fdist_cong = FreqDist(word_tokens_cong)
return text2Party
'''
Using Concordance, you can see each time a word is used, along with its
immediate context. It can give you a peek into how a word is being used
at the sentence level and what words are used with it
'''
def concordance(text_Party,strng):
word_tokens_party = word_tokenize(text_Party)
moby = Text(word_tokens_party)
resultList = []
for i in range(0,1):
save_stdout = sys.stdout
result = StringIO()
sys.stdout = result
moby.concordance(strng,lines=4,width=82)
sys.stdout = save_stdout
s=result.getvalue().splitlines()
return result.getvalue()
def normalize(d, target=1.0):
raw = sum(d.values())
factor = target/raw
return {key:value*factor for key,value in d.items()}
def fDistance(text2Party):
'''
Most frequent words search
'''
word_tokens_party = word_tokenize(text2Party) #Tokenizing
fdistance = FreqDist(word_tokens_party).most_common(10)
mem={}
for x in fdistance:
mem[x[0]]=x[1]
return normalize(mem)
def fDistancePlot(text2Party,plotN=15):
'''
Most Frequent Words Visualization
'''
word_tokens_party = word_tokenize(text2Party) #Tokenizing
fdistance = FreqDist(word_tokens_party)
plt.title('Frequency Distribution')
plt.axis('off')
plt.figure(figsize=(4,3))
fdistance.plot(plotN)
plt.tight_layout()
buf = BytesIO()
plt.savefig(buf)
buf.seek(0)
img1 = Image.open(buf)
plt.clf()
return img1
def DispersionPlot(textParty):
'''
Dispersion PLot
'''
word_tokens_party = word_tokenize(textParty) #Tokenizing
moby = Text(word_tokens_party)
fdistance = FreqDist(word_tokens_party)
word_Lst=[]
for x in range(5):
word_Lst.append(fdistance.most_common(6)[x][0])
plt.axis('off')
plt.title('Dispersion Plot')
plt.figure(figsize=(4,3))
moby.dispersion_plot(word_Lst)
plt.plot(color="#EF6D6D")
plt.tight_layout()
buf = BytesIO()
plt.savefig(buf)
buf.seek(0)
img = Image.open(buf)
plt.clf()
return img
def getSubjectivity(text):
'''
Create a function to get the polarity
'''
return TextBlob(text).sentiment.subjectivity
def getPolarity(text):
'''
Create a function to get the polarity
'''
return TextBlob(text).sentiment.polarity
def getAnalysis(score):
if score < 0:
return 'Negative'
elif score == 0:
return 'Neutral'
else:
return 'Positive'
'''
url = "http://library.bjp.org/jspui/bitstream/123456789/2988/1/BJP-Election-english-2019.pdf"
path_input = "./Bjp_Manifesto_2019.pdf"
urllib.request.urlretrieve(url, filename=path_input)
url="https://drive.google.com/uc?id=1BLCiy_BWilfVdrUH8kbO-44DJevwO5CG&export=download"
path_input = "./Aap_Manifesto_2019.pdf"
urllib.request.urlretrieve(url, filename=path_input)
url="https://drive.google.com/uc?id=1HVZvTtYntl0YKLnE0cwu0CvAIRhXOv60&export=download"
path_input = "./Congress_Manifesto_2019.pdf"
urllib.request.urlretrieve(url, filename=path_input)
'''
def analysis(Manifesto,Search):
raw_party = Parsing(Manifesto)
text_Party=clean_text(raw_party)
text_Party= Preprocess(text_Party)
df = pd.DataFrame(raw_party.split('\n'), columns=['Content'])
df['Subjectivity'] = df['Content'].apply(getSubjectivity)
df['Polarity'] = df['Content'].apply(getPolarity)
df['Analysis on Polarity'] = df['Polarity'].apply(getAnalysis)
df['Analysis on Subjectivity'] = df['Subjectivity'].apply(getAnalysis)
plt.title('Sentiment Analysis')
plt.xlabel('Sentiment')
plt.ylabel('Counts')
plt.figure(figsize=(4,3))
df['Analysis on Polarity'].value_counts().plot(kind ='bar',color="#FF9F45")
plt.tight_layout()
buf = BytesIO()
plt.savefig(buf)
buf.seek(0)
img1 = Image.open(buf)
plt.clf()
plt.figure(figsize=(4,3))
df['Analysis on Subjectivity'].value_counts().plot(kind ='bar',color="#B667F1")
plt.tight_layout()
buf = BytesIO()
plt.savefig(buf)
buf.seek(0)
img2 = Image.open(buf)
plt.clf()
wordcloud = WordCloud(max_words=2000, background_color="white",mode="RGB").generate(text_Party)
plt.figure(figsize=(4,3))
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.tight_layout()
buf = BytesIO()
plt.savefig(buf)
buf.seek(0)
img3 = Image.open(buf)
plt.clf()
fdist_Party=fDistance(text_Party)
img4=fDistancePlot(text_Party)
img5=DispersionPlot(text_Party)
searchRes=concordance(text_Party,Search)
searChRes=clean(searchRes)
searChRes=searchRes.replace(Search,"\u0332".join(Search))
return searChRes,fdist_Party,img1,img2,img3,img4,img5
Search_txt=gr.inputs.Textbox()
filePdf = gr.inputs.File()
text = gr.outputs.Textbox(label='SEARCHED OUTPUT')
mfw=gr.outputs.Label(label="Most Relevant Topics")
plot1=gr.outputs. Image(label='Sentiment Analysis')
plot2=gr.outputs.Image(label='Subjectivity Analysis')
plot3=gr.outputs.Image(label='Word Cloud')
plot4=gr.outputs.Image(label='Frequency Distribution')
plot5=gr.outputs.Image(label='Dispersion Plot')
io=gr.Interface(fn=analysis, inputs=[filePdf,Search_txt], outputs=[text,mfw,plot1,plot2,plot3,plot4,plot5], title='Manifesto Analysis',)
io.launch(debug=True,share=False)
#,examples=[['./Bjp_Manifesto_2019.pdf','india'],['./Aap_Manifesto_2019.pdf',],['./Congress_Manifesto_2019.pdf',]]
#allow_screenshot=False, allow_flagging="never",
#examples=[['manifestos/Bjp_Manifesto_2019.pdf','modi'],['Aap_Manifesto_2019.pdf','delhi'],['manifestos/Congress_Manifesto_2019.pdf','safety']])
|