File size: 30,864 Bytes
029ffc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e83a41
 
a87bc00
 
1726132
a87bc00
 
 
 
 
 
 
 
 
 
 
cd8ad01
529eea1
a87bc00
 
22af537
 
a87bc00
7b11062
d887fe7
a87bc00
 
 
 
c27c36d
a87bc00
 
aa5087f
 
029ffc9
 
 
 
 
 
 
 
8b674fc
8d7d358
a87bc00
 
 
d963f31
a87bc00
029ffc9
 
 
 
 
 
 
 
 
 
 
 
a87bc00
 
 
5f546a1
 
 
b183374
5f546a1
2791a19
5f546a1
a87bc00
 
5f546a1
a87bc00
 
 
 
 
 
 
 
 
 
 
c90d42e
a87bc00
 
c90d42e
 
a87bc00
 
 
 
 
 
 
c90d42e
a87bc00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1726132
 
 
e030268
1726132
b36e9af
a87bc00
 
 
 
 
 
 
5577484
a87bc00
 
 
 
1dadadf
dd57fb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4357809
1dadadf
 
dd57fb3
 
a87bc00
 
 
 
 
 
029ffc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a87bc00
 
029ffc9
a87bc00
029ffc9
a87bc00
 
 
 
 
029ffc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a87bc00
7fa8edb
a87bc00
5577484
a87bc00
 
 
5696ea4
7fa8edb
5696ea4
7a4b822
bc86dbe
 
 
 
 
 
 
a87bc00
 
d7c764c
 
 
 
427074d
d7c764c
e9f9b30
d7c764c
 
f10fd87
d7c764c
 
0a637cc
d7c764c
ed4ccd5
 
d7c764c
 
 
 
 
 
 
 
a87bc00
6542f5d
5577484
 
 
 
 
 
6542f5d
 
5577484
 
 
a82e853
6542f5d
 
 
 
 
 
 
 
 
54ed831
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5beb0e
 
afae3ae
54ed831
d5beb0e
 
54ed831
 
 
 
 
 
a32f1aa
54ed831
 
 
 
 
a32f1aa
d5beb0e
54ed831
 
 
 
 
 
 
a32f1aa
b8c6825
54ed831
d5beb0e
40c1a81
54ed831
 
 
9d29f03
 
b4aeabd
d5beb0e
97c2647
54ed831
 
 
 
 
 
 
 
 
 
9e60b4c
 
9788480
d5beb0e
c457784
54ed831
 
 
 
 
 
 
9e60b4c
54ed831
 
 
58893fc
 
9788480
d5beb0e
c457784
54ed831
 
 
 
75a8a58
54ed831
 
 
 
 
9788480
54ed831
 
 
 
 
 
 
 
 
 
 
 
76ec819
529eea1
67f8b07
529eea1
7a966d7
529eea1
 
 
6542f5d
529eea1
 
 
76ec819
1df8bb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2791a19
1df8bb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a87bc00
884d940
544d752
3130a75
28346aa
029ffc9
28346aa
 
 
 
 
029ffc9
6542f5d
de45d29
029ffc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70b7c33
a87bc00
1df8bb0
 
 
 
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
# """
# # 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('punkt_tab')
# 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'],cache_examples=True
# #  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 conc(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 get_all_phases_containing_tar_wrd(target_word, tar_passage, left_margin = 10, right_margin = 10,numLins=4):
#     """
#         Function to get all the phases that contain the target word in a text/passage tar_passage.
#         Workaround to save the output given by nltk Concordance function
         
#         str target_word, str tar_passage int left_margin int right_margin --> list of str
#         left_margin and right_margin allocate the number of words/pununciation before and after target word
#         Left margin will take note of the beginning of the text
#     """     
#     ## Create list of tokens using nltk function
#     tokens = nltk.word_tokenize(tar_passage)
     
#     ## Create the text of tokens
#     text = nltk.Text(tokens)
 
#     ## Collect all the index or offset position of the target word
#     c = nltk.ConcordanceIndex(text.tokens, key = lambda s: s.lower())
 
#     ## Collect the range of the words that is within the target word by using text.tokens[start;end].
#     ## The map function is use so that when the offset position - the target range < 0, it will be default to zero
#     concordance_txt = ([text.tokens[list(map(lambda x: x-5 if (x-left_margin)>0 else 0,[offset]))[0]:offset+right_margin] for offset in c.offsets(target_word)])
                         
#     ## join the sentences for each of the target phrase and return it
#     result = [''.join([x.replace("Y","")+' ' for x in con_sub]) for con_sub in concordance_txt][:-1]
#     result=result[:numLins+1]
    
#     res='\n\n'.join(result)
#     return res  
  

# 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.figure(figsize=(4,3))
#   plt.title('Dispersion Plot')
#   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'
# def Original_Image(path):
#   img= cv2.imread(path)
#   img= cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  
#   return img

# def Image_Processed(path):
#   '''
#   Reading the image file
#   '''
#   img= cv2.imread(path)
#   img= cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  
#   #Thresholding
#   ret, bw_img = cv2.threshold(img, 124, 255, cv2.THRESH_BINARY)

#   return bw_img

# def word_cloud(orgIm,mask_img,text_Party_pr,maxWord=2000,colorGener=True,
#     contCol='white',bckColor='white'):
#   '''
#   #Generating word cloud
#   '''  
#   mask =mask_img
#   # Create and generate a word cloud image:
#   wordcloud = WordCloud(max_words=maxWord, background_color=bckColor,
#                         mask=mask,
#                         colormap='nipy_spectral_r',
#                         contour_color=contCol,
#                         width=800, height=800,
#                         margin=2,
#                         contour_width=3).generate(text_Party_pr)

#   # create coloring from image

  
#   plt.axis("off")
#   if colorGener==True:
#     image_colors = ImageColorGenerator(orgIm)
#     plt.imshow(wordcloud.recolor(color_func= image_colors),interpolation="bilinear")
    
  
#   else:    
#     plt.imshow(wordcloud)
    
  
  
 
# def word_cloud_generator(parsed_text_name,text_Party):
#   parsed=parsed_text_name.lower()

#   if 'bjp' in parsed:
#     orgImg=Original_Image('bjpImg2.jpeg')
#     bwImg=Image_Processed('bjpImg2.jpeg')
#     plt.figure(figsize=(6,5))
#     word_cloud(orgImg,bwImg,text_Party,maxWord=3000,colorGener=True,
#     contCol='white', bckColor='black')
#     plt.tight_layout()
#     buf = BytesIO()
#     plt.savefig(buf)
#     buf.seek(0)
#     img1 = Image.open(buf)
#     plt.clf() 
#     return img1

  
#   elif 'congress' in parsed:
#     orgImg=Original_Image('congress3.jpeg')
#     bwImg=Image_Processed('congress3.jpeg')
#     plt.figure(figsize=(5,4))
#     word_cloud(orgImg,bwImg,text_Party,maxWord=3000,colorGener=True)
    
#     plt.tight_layout()
#     buf = BytesIO()
#     plt.savefig(buf)
#     buf.seek(0)
#     img2 = Image.open(buf)
#     plt.clf() 
#     return img2
#     #congrsMain.jpg
    
  
#   elif 'aap' in parsed:
#     orgImg=Original_Image('aapMain2.jpg')
#     bwImg=Image_Processed('aapMain2.jpg')
#     plt.figure(figsize=(5,4))
#     word_cloud(orgImg,bwImg,text_Party,maxWord=3000,colorGener=False,contCol='black')
    
#     plt.tight_layout()
#     buf = BytesIO()
#     plt.savefig(buf)
#     buf.seek(0)
#     img3 = Image.open(buf)
#     plt.clf() 
#     return img3
  
#   else :
#     wordcloud = WordCloud(max_words=2000, background_color="white",mode="RGB").generate(text_Party)
#     plt.figure(figsize=(5,5))
#     plt.imshow(wordcloud, interpolation="bilinear")
#     plt.axis("off")   
#     plt.tight_layout()
#     buf = BytesIO()
#     plt.savefig(buf)
#     buf.seek(0)
#     img4 = Image.open(buf)
#     plt.clf()
#     return img4



# '''
# 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()
    
#   img3 = word_cloud_generator(Manifesto.name,text_Party)
  
#   fdist_Party=fDistance(text_Party)
#   img4=fDistancePlot(text_Party)
#   img5=DispersionPlot(text_Party)
#   #concordance(text_Party,Search)
#   searChRes=get_all_phases_containing_tar_wrd(Search,text_Party)
#   searChRes=searChRes.replace(Search,"\u0332".join(Search))
#   plt.close('all') 
#   return searChRes,fdist_Party,img1,img2,img3,img4,img5


# Search_txt= "text"
# filePdf = "file"
# text = gr.Textbox(label='Context Based Search')
# mfw=gr.Label(label="Most Relevant Topics")
# plot1=gr.Image(label='Sentiment Analysis')
# plot2=gr.Image(label='Subjectivity Analysis')
# plot3=gr.Image(label='Word Cloud')
# plot4=gr.Image(label='Frequency Distribution')
# plot5=gr.Image(label='Dispersion Plot')

# io=gr.Interface(fn=analysis, inputs=[filePdf,Search_txt], outputs=[text,mfw,plot1,plot2,plot3,plot4,plot5], title='Manifesto Analysis',examples=[['Example/AAP_Manifesto_2019.pdf','government'],['Example/Bjp_Manifesto_2019.pdf','environment'],['Example/Congress_Manifesto_2019.pdf','safety']],theme='peach')
# io.launch(debug=True,share=False)


# #allow_screenshot=False,allow_flagging="never",
# #examples=[['manifestos/Bjp_Manifesto_2019.pdf','modi'],['AAP_Manifesto_2019.pdf','delhi'],['manifestos/Congress_Manifesto_2019.pdf','safety']])


"""
# 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
import groq
import json
from dotenv import load_dotenv
from sklearn.feature_extraction.text import TfidfVectorizer
from collections import Counter

# Load environment variables from .env file
load_dotenv()

nltk.download('punkt_tab')
nltk.download('stopwords')
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('words')

# Initialize Groq client for LLM capabilities
try:
    groq_api_key = os.getenv("GROQ_API_KEY")
    if groq_api_key:
        groq_client = groq.Groq(api_key=groq_api_key)
    else:
        print("Warning: GROQ_API_KEY not found in environment variables. Summarization will be disabled.")
        groq_client = None
except Exception as e:
    print(f"Error initializing Groq client: {e}")
    groq_client = None


"""## PARSING FILES"""

#def Parsing(parsed_text):
  #parsed_text=parsed_text.name
  #raw_party =parser.from_file(parsed_text) 
 # raw_party = raw_party['content'],cache_examples=True
#  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 conc(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 get_all_phases_containing_tar_wrd(target_word, tar_passage, left_margin = 10, right_margin = 10,numLins=4):
    """
        Function to get all the phases that contain the target word in a text/passage tar_passage.
        Workaround to save the output given by nltk Concordance function
         
        str target_word, str tar_passage int left_margin int right_margin --> list of str
        left_margin and right_margin allocate the number of words/pununciation before and after target word
        Left margin will take note of the beginning of the text
    """     
    ## Create list of tokens using nltk function
    tokens = nltk.word_tokenize(tar_passage)
     
    ## Create the text of tokens
    text = nltk.Text(tokens)
 
    ## Collect all the index or offset position of the target word
    c = nltk.ConcordanceIndex(text.tokens, key = lambda s: s.lower())
 
    ## Collect the range of the words that is within the target word by using text.tokens[start;end].
    ## The map function is use so that when the offset position - the target range < 0, it will be default to zero
    concordance_txt = ([text.tokens[list(map(lambda x: x-5 if (x-left_margin)>0 else 0,[offset]))[0]:offset+right_margin] for offset in c.offsets(target_word)])
                         
    ## join the sentences for each of the target phrase and return it
    result = [''.join([x.replace("Y","")+' ' for x in con_sub]) for con_sub in concordance_txt][:-1]
    result=result[:numLins+1]
    
    res='\n\n'.join(result)
    return res  
  

def normalize(d, target=1.0):
   raw = sum(d.values())
   factor = target/raw
   return {key:value*factor for key,value in d.items()}


def generate_summary(text, max_length=1000):
    """
    Generate a summary of the manifesto text using Groq LLM
    """
    if not groq_client:
        return "Summarization is not available. Please set up your GROQ_API_KEY in the .env file."
    
    # Truncate text if it's too long to fit in context window
    if len(text) > 10000:
        text = text[:10000]
    
    try:
        # Use Groq's LLaMA 3 model for summarization
        completion = groq_client.chat.completions.create(
            model="llama3-8b-8192",  # Using LLaMA 3 8B model
            messages=[
                {"role": "system", "content": "You are a helpful assistant that summarizes political manifestos. Provide a concise, objective summary that captures the key policy proposals, themes, and promises in the manifesto."},
                {"role": "user", "content": f"Please summarize the following political manifesto text in about 300-500 words, focusing on the main policy areas, promises, and themes:\n\n{text}"}
            ],
            temperature=0.3,  # Lower temperature for more focused output
            max_tokens=800,   # Limit response length
        )
        
        return completion.choices[0].message.content
    except Exception as e:
        return f"Error generating summary: {str(e)}. Please check your API key and connection."

def fDistance(text2Party):
  '''
  Most frequent words search using TF-IDF to find more relevant words
  '''
  # Traditional frequency distribution
  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]
    
  # Enhanced with TF-IDF for better relevance
  sentences = sent_tokenize(text2Party)
  
  # Use TF-IDF to find more relevant words
  vectorizer = TfidfVectorizer(max_features=15, stop_words='english')
  tfidf_matrix = vectorizer.fit_transform(sentences)
  
  # Get feature names (words)
  feature_names = vectorizer.get_feature_names_out()
  
  # Calculate average TF-IDF score for each word across all sentences
  tfidf_scores = {}
  for i, word in enumerate(feature_names):
      scores = [tfidf_matrix[j, i] for j in range(len(sentences)) if i < tfidf_matrix[j].shape[1]]
      if scores:
          tfidf_scores[word] = sum(scores) / len(scores)
  
  # Sort by score and get top words
  sorted_tfidf = dict(sorted(tfidf_scores.items(), key=lambda x: x[1], reverse=True)[:10])
  
  # Combine traditional frequency with TF-IDF for better results
  combined_scores = {}
  for word in set(list(mem.keys()) + list(sorted_tfidf.keys())):
      # Normalize and combine both scores (with more weight to TF-IDF)
      freq_score = mem.get(word, 0) / max(mem.values()) if mem else 0
      tfidf_score = sorted_tfidf.get(word, 0) / max(sorted_tfidf.values()) if sorted_tfidf else 0
      combined_scores[word] = (freq_score * 0.3) + (tfidf_score * 0.7)  # Weight TF-IDF higher
  
  # Get top 10 words by combined score
  top_words = dict(sorted(combined_scores.items(), key=lambda x: x[1], reverse=True)[:10])
  
  return normalize(top_words)

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.figure(figsize=(4,3))
  plt.title('Dispersion Plot')
  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'
def Original_Image(path):
  img= cv2.imread(path)
  img= cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  
  return img

def Image_Processed(path):
  '''
  Reading the image file
  '''
  img= cv2.imread(path)
  img= cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  
  #Thresholding
  ret, bw_img = cv2.threshold(img, 124, 255, cv2.THRESH_BINARY)

  return bw_img

def word_cloud(orgIm,mask_img,text_Party_pr,maxWord=2000,colorGener=True,
    contCol='white',bckColor='white'):
  '''
  #Generating word cloud
  '''  
  mask =mask_img
  # Create and generate a word cloud image:
  wordcloud = WordCloud(max_words=maxWord, background_color=bckColor,
                        mask=mask,
                        colormap='nipy_spectral_r',
                        contour_color=contCol,
                        width=800, height=800,
                        margin=2,
                        contour_width=3).generate(text_Party_pr)

  # create coloring from image

  
  plt.axis("off")
  if colorGener==True:
    image_colors = ImageColorGenerator(orgIm)
    plt.imshow(wordcloud.recolor(color_func= image_colors),interpolation="bilinear")
    
  
  else:    
    plt.imshow(wordcloud)
    
  
  
 
def word_cloud_generator(parsed_text_name,text_Party):
  parsed=parsed_text_name.lower()

  if 'bjp' in parsed:
    orgImg=Original_Image('bjpImg2.jpeg')
    bwImg=Image_Processed('bjpImg2.jpeg')
    plt.figure(figsize=(6,5))
    word_cloud(orgImg,bwImg,text_Party,maxWord=3000,colorGener=True,
    contCol='white', bckColor='black')
    plt.tight_layout()
    buf = BytesIO()
    plt.savefig(buf)
    buf.seek(0)
    img1 = Image.open(buf)
    plt.clf() 
    return img1

  
  elif 'congress' in parsed:
    orgImg=Original_Image('congress3.jpeg')
    bwImg=Image_Processed('congress3.jpeg')
    plt.figure(figsize=(5,4))
    word_cloud(orgImg,bwImg,text_Party,maxWord=3000,colorGener=True)
    
    plt.tight_layout()
    buf = BytesIO()
    plt.savefig(buf)
    buf.seek(0)
    img2 = Image.open(buf)
    plt.clf() 
    return img2
    #congrsMain.jpg
    
  
  elif 'aap' in parsed:
    orgImg=Original_Image('aapMain2.jpg')
    bwImg=Image_Processed('aapMain2.jpg')
    plt.figure(figsize=(5,4))
    word_cloud(orgImg,bwImg,text_Party,maxWord=3000,colorGener=False,contCol='black')
    
    plt.tight_layout()
    buf = BytesIO()
    plt.savefig(buf)
    buf.seek(0)
    img3 = Image.open(buf)
    plt.clf() 
    return img3
  
  else :
    wordcloud = WordCloud(max_words=2000, background_color="white",mode="RGB").generate(text_Party)
    plt.figure(figsize=(5,5))
    plt.imshow(wordcloud, interpolation="bilinear")
    plt.axis("off")   
    plt.tight_layout()
    buf = BytesIO()
    plt.savefig(buf)
    buf.seek(0)
    img4 = Image.open(buf)
    plt.clf()
    return img4



'''
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): 
  '''
  Main analysis function that processes the manifesto and generates all outputs
  Manifesto: PDF file uploaded by the user
  Search: Search term entered by the user
  '''
  try:
    # Process the uploaded PDF
    raw_party = Parsing(Manifesto)
    text_Party = clean_text(raw_party)
    text_Party_processed = Preprocess(text_Party)

    # Generate summary using LLM
    summary = generate_summary(raw_party)

    # Sentiment analysis
    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)
    
    # Generate sentiment analysis plot
    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() 
    
    # Generate subjectivity analysis plot
    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()
      
    # Generate word cloud
    img3 = word_cloud_generator(Manifesto.name, text_Party_processed)
    
    # Generate frequency distribution and dispersion plots
    fdist_Party = fDistance(text_Party_processed)
    img4 = fDistancePlot(text_Party_processed)
    img5 = DispersionPlot(text_Party_processed)
    
    # Search for the term in the text
    searChRes = get_all_phases_containing_tar_wrd(Search, text_Party_processed)
    searChRes = searChRes.replace(Search, "\u0332".join(Search))
    
    plt.close('all') 
    return searChRes, fdist_Party, img1, img2, img3, img4, img5, summary
    
  except Exception as e:
    error_message = f"Error analyzing manifesto: {str(e)}"
    print(error_message)
    # Return placeholder values in case of error
    return error_message, {}, None, None, None, None, None, "Error generating summary. Please check the console for details."


Search_txt= "text"
filePdf = "file"
text = gr.Textbox(label='Context Based Search')
mfw=gr.Label(label="Most Relevant Topics (LLM Enhanced)")
plot1=gr.Image(label='Sentiment Analysis')
plot2=gr.Image(label='Subjectivity Analysis')
plot3=gr.Image(label='Word Cloud')
plot4=gr.Image(label='Frequency Distribution')
plot5=gr.Image(label='Dispersion Plot')
summary_output = gr.Textbox(label='AI-Generated Summary', lines=10)

with gr.Blocks(title='Manifesto Analysis') as demo:
    gr.Markdown("# Manifesto Analysis with LLM Enhancement")
    gr.Markdown("### Analyze political manifestos with advanced NLP and LLM techniques")
    
    with gr.Row():
        with gr.Column(scale=1):
            file_input = gr.File(label="Upload Manifesto PDF", file_types=[".pdf"])
            search_input = gr.Textbox(label="Search Term", placeholder="Enter a term to search in the manifesto")
            submit_btn = gr.Button("Analyze Manifesto")
    
    with gr.Tabs():
        with gr.TabItem("Summary"):
            summary_output
        
        with gr.TabItem("Search Results"):
            text
        
        with gr.TabItem("Key Topics"):
            mfw
        
        with gr.TabItem("Visualizations"):
            with gr.Row():
                with gr.Column(scale=1):
                    plot3
                with gr.Column(scale=1):
                    plot4
            
            with gr.Row():
                with gr.Column(scale=1):
                    plot1
                with gr.Column(scale=1):
                    plot2
            
            with gr.Row():
                plot5
    
    submit_btn.click(
        fn=analysis,
        inputs=[file_input, search_input],
        outputs=[text, mfw, plot1, plot2, plot3, plot4, plot5, summary_output]
    )
    
    gr.Examples(
        examples=[
            ['Example/AAP_Manifesto_2019.pdf', 'government'],
            ['Example/Bjp_Manifesto_2019.pdf', 'environment'],
            ['Example/Congress_Manifesto_2019.pdf', 'safety']
        ],
        inputs=[file_input, search_input]
    )

demo.launch(debug=True, share=False)


# Old interface code replaced by the Blocks implementation above
# io=gr.Interface(fn=analysis, inputs=[filePdf,Search_txt], outputs=[text,mfw,plot1,plot2,plot3,plot4,plot5], title='Manifesto Analysis',examples=[['Example/AAP_Manifesto_2019.pdf','government'],['Example/Bjp_Manifesto_2019.pdf','environment'],['Example/Congress_Manifesto_2019.pdf','safety']])
# io.launch(debug=True,share=False)