-
Notifications
You must be signed in to change notification settings - Fork 0
/
views.py
executable file
·2367 lines (2132 loc) · 101 KB
/
views.py
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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
from django.shortcuts import render
from django.core.mail import send_mail
from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import HttpResponse
import subprocess
import re
import pandas as pd
from subprocess import Popen, PIPE
import uuid
from repindexapi import settings
import docx2txt
from random import randint
from repindexapp.models import *
from django.contrib.auth import logout
from django.contrib.auth import authenticate
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from django.shortcuts import render_to_response
from django.contrib import messages
from django.contrib import auth
from django.contrib.auth import login
from django.contrib import messages
from django.views.decorators.cache import cache_control
from django.utils.datastructures import MultiValueDictKeyError
from django.views.decorators.csrf import csrf_exempt
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework import permissions
from rest_framework.decorators import permission_classes
from datetime import datetime
import csv
import sys
import json
import os
import datetime
from uuid import uuid4
from django.http import JsonResponse
from django.core.files.storage import FileSystemStorage
from django.core import serializers
from django.contrib.auth.decorators import login_required
import requests
import docx
import unicodedata
import collections
import pypandoc
from django.core.mail import EmailMessage
from uuid import uuid4
from bs4 import BeautifulSoup
import urllib
import dropbox
import subprocess
import json
from tika import parser
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from cStringIO import StringIO
from functools import wraps
import jwt
# Create your views here.
base_url = "/var/www/repindexapi/"
path_url="/var/www/html"
def emailTemplate(firstname,username,password):
url="http://repindex.com:4200/html/knowledge/"
emailTemplate.HTML="""
<div>
<p>Hi """+firstname+""",</p><p>Your Mattersmith Review account has been successfully created.</p><p>Here are the credentials</p><p><b>Username</b> : """+username+"""</p><p><b>Password</b> : """+password+"""</p><p>Click on button below to login</p>
<a href="""+url+""" target="_blank"><button style="background-color:green;color:white">Getting Started</button></a><br>
<br><br>Regards,<br><br><div><hr style="color:red;width:40px;float:left"><br>
<div><i style="color:#003746;font-family:arial;">Harecross,Longframlington, Morpeth NE65 8AN</i><br><i style="color:red">T</i> +44 (0)1665 570815<br><a href="http://www.mattersmith.co.uk" style="font-family:arial; font-size: 14px; line-height: 14px; color: #f0503c;">www.mattersmith.co.uk</a></div><br><a href="http://www.mattersmith.co.uk"><img src="http://www.thinkfarm.co.uk/extranet/Mattersmith/email_signature/images/mattersmith-banner.gif" alt="Mattersmith" style="display:block;" border="0"></a><br>
<div style="font-family:arial; font-size: 12px; line-height: 14px; color: #003746;width:657px"> <hr style="color:#003746"></hr><span style="font-weight: bold;">Authorisation</span><br>
<p>This email contains proprietary, privileged and confidential information. If you are not a named addressee (or responsible
for delivery to a named addressee), you must delete this email and any attachment immediately. We would be grateful if
you would contact the sender to report any such misdelivery.<p>
<span style="font-weight: bold;">Privacy and Confidentiality</span><br>
<p>This email contains proprietary, privileged and confidential information. If you are not a named addressee (or responsible for delivery to a named addressee), you must delete this email and any attachment immediately. We would be grateful if you would contact the sender to report any such misdelivery.</p>
<span style="font-weight: bold;">Email Security and Integrity</span><br>
<p>Do not open any attachment to this email without first scanning it for viruses, worms or other unwelcome content. We
regularly scan and disinfect our computer systems but this is no guarantee that attachments to emails are safe. If you
cannot determine for yourself that any attachment will not harm your computer systems or data, then delete it immediately
and ask us to provide the content of the attachment by fax or post. We accept no responsibility for loss, harm or damage
which results from the failure to follow these instructions.</p>
<hr style="color:#003746"></hr>
</div>
</div>
</div>
"""
def jwtValidator(func):
@wraps(func)
def decorator(request, *args, **kwargs):
if request.META.get('HTTP_AUTHORIZATION') is not None:
try:
Token=jwt.decode(request.META.get('HTTP_AUTHORIZATION'), 'secret', algorithms=['HS256'])
except jwt.DecodeError:
return JsonResponse({'msg' : 'Token verfication failed'},)
if Token:
return func(request, *args, **kwargs)
else:
return JsonResponse({'msg' : 'Please provide valid auth token'},)
return decorator
@csrf_exempt
def clientregsiter(request,userid):
print "=======login====user"
body_unicode = request.body.decode("utf-8")
body = json.loads(body_unicode)
print "body",body
username = body['username']
password = body['password']
firstname = body['firstname']
lastname = body['lastname']
email = body['email']
mobile_no=body['mobile_no']
dob=body['dob']
usertype=body['usertype']
print body['lastname']
addedUserCount = UserInfo.objects.filter(addedby=userid).count()
userLimit = UserInfo.objects.get(userid=userid)
if addedUserCount > int(userLimit.userlimit)-1:
print "==========in limit over====="
jsondata={"msg":"Your Limit is over please exceed it!","success" : "false"}
return JsonResponse(jsondata)
alredyexits = User.objects.filter(username=body['username'])[:1]
if alredyexits:
jsondata={"msg":"Username alredy exits","success":"false"}
else:
userobj= User.objects.create_user(username=username,first_name=firstname,password=password,last_name=lastname, email=email)
jsondata={"success":"true","msg":"Records created Successfully","userobj.username":str(userobj.username)}
print "user object",userobj
getClientid=UserInfo(userobject=userobj,addedby=userid,userid=userobj.id,mobile=mobile_no,dob=dob,user_type_id_id=usertype)
getClientid.save()
emailTemplate(firstname,username,password)
emailStatus = EmailMessage('Your Mattersmith Review account has been successfully created',emailTemplate.HTML ,"ms-legalservices@mattersmith.co.uk", to=[email])
emailStatus.content_subtype="html"
emailStatus.send()
return JsonResponse(jsondata)
@csrf_exempt
@jwtValidator
def adminregsiter(request):
body_unicode = request.body.decode("utf-8")
body = json.loads(body_unicode)
print "body",body
username = body['username']
password = body['password']
firstname = body['firstname']
lastname = body['lastname']
email = body['email']
userlimit=body['mobile_no']
dob=""
usertype=body['usertype']
print body['lastname']
alredyexits=User.objects.filter(username=body['username'])[:1]
if alredyexits:
jsondata={"msg":"admin alredy exits","success":"false"}
else:
userobj= User.objects.create_user(username=username,is_superuser=1,first_name=firstname,password=password,last_name=lastname, email=email)
jsondata={"success":"true","msg":"Records created Successfully","userobj.username":str(userobj.username)}
print "user object",userobj
getClientid=UserInfo(userobject=userobj,userid=userobj.id,userlimit=userlimit,dob=dob,user_type_id_id=usertype)
getClientid.save()
emailTemplate(firstname,username,password)
emailStatus = EmailMessage('Your Mattersmith Review account has been successfully created',emailTemplate.HTML ,"ms-legalservices@mattersmith.co.uk", to=[email])
emailStatus.content_subtype="html"
emailStatus.send()
return JsonResponse(jsondata)
@csrf_exempt
def Login(request):
body_unicode = request.body.decode("utf-8")
body = json.loads(body_unicode)
print "body",body
print body['username']
user=authenticate(username=body['username'], password=body['password'])
if user is not None:
userInfo = UserInfo.objects.get(userid = user.id)
if user.is_active:
encoded_jwt = jwt.encode({'user': user.username}, 'secret', algorithm='HS256')
if user.is_superuser:
print "super user"
login(request, user)
print "request", request.user
rand_token = uuid4()
usertype={"user_type":"admin","user_id":user.id,"username":user.username,"auth_token":encoded_jwt,'concept_status': userInfo.concept_status,'stoplist_status':userInfo.stoplist_status}
return JsonResponse(usertype)
else:
print "====else part==="
if user.is_staff:
print "superuser"
login(request, user)
print "request",request.user
rand_token = uuid4()
usertype={"user_type":"superuser","user_id":user.id,"username":user.username,"auth_token":encoded_jwt,'concept_status': userInfo.concept_status,'stoplist_status':userInfo.stoplist_status}
return JsonResponse(usertype)
else:
print "normal user"
login(request, user)
print "request",request.user
rand_token = uuid4()
usertype={"user_type":"user","user_id":user.id,"username":user.username,"auth_token":encoded_jwt,'concept_status': userInfo.concept_status,'stoplist_status':userInfo.stoplist_status}
return JsonResponse(usertype)
else:
msg={"error":"Invalid credentials"}
return JsonResponse(msg)
else:
if user is None:
msg={"error":"Invalid credentials"}
return JsonResponse(msg)
@csrf_exempt
def getAllClient(request,userid):
getclient=UserInfo.objects.filter(addedby=userid).values('mobile','userid', 'userobject__username','userobject__first_name','userobject__last_name','userobject__email','userobject__is_active','created_at')
getdate=UserInfo.objects.all().values('created_at')
print str(UserInfo.userid)
print "type",type(getclient)
dictionaries = [ obj for obj in getclient ]
created = [ obj["created_at"] for obj in getdate ]
print created
return HttpResponse(json.dumps({"data": dictionaries}, sort_keys=True, default=str),content_type='application/json')
@csrf_exempt
@jwtValidator
def getAlladmin(request):
getadmin=User.objects.filter(is_staff=0).values('userinfo__mobile','id','first_name','last_name','username','is_superuser','email','is_active','userinfo__created_at','userinfo__userlimit','userinfo__concept_status','userinfo__stoplist_status')
getdate=UserInfo.objects.all().values('created_at')
print str(UserInfo.userid)
print "type",type(getadmin)
dictionaries = [ obj for obj in getadmin ]
created = [ obj["created_at"] for obj in getdate ]
print created
return HttpResponse(json.dumps({"data": dictionaries}, sort_keys=True, default=str),content_type='application/json')
@csrf_exempt
def updateClientInfo(request,id):
print "===id===",id
body_unicode = request.body.decode("utf-8")
body = json.loads(body_unicode)
print "body",body
#username = body['username']
#password = body['password']
firstname = body['firstname']
lastname = body['lastname']
email = body['email']
mobile_no=body['mobile_no']
#dob=body['dob']
usertype=1
getclient=UserInfo.objects.get(userid=id)
getclient.mobile=mobile_no
#getclient.dob=dob
getclient.save()
userobj=User.objects.get(id=id)
#userobj.username=body['username']
#userobj.set_password(body['password'])
userobj.first_name=body['firstname']
userobj.last_name=body['lastname']
userobj.email=body['email']
userobj.save()
msg={"succss":"true","msg":"Record updated succssfully"}
return JsonResponse(msg)
@csrf_exempt
def updatesuperuser(request,id):
print "============in updatesuperuser========"
body_unicode = request.body.decode("utf-8")
body = json.loads(body_unicode)
print "body",body
firstname = body['firstname']
lastname = body['lastname']
email = body['email']
userobj=User.objects.get(id=id)
userobj.first_name=body['firstname']
userobj.last_name=body['lastname']
userobj.email=body['email']
userobj.save()
msg={"succss":"true","msg":"Record updated succssfully"}
return JsonResponse(msg)
@csrf_exempt
@jwtValidator
def addProject(request,user_id):
print "==========userid====",user_id
body_unicode = request.body.decode("utf-8")
body = json.loads(body_unicode)
if Projects.objects.filter(name=body['project_name'],created_by_id=user_id).exists():
msg={"error":"Project Name already exits","success":"false"}
return JsonResponse(msg)
project = Projects(status=1)
project.name = body['project_name']
project.created_by = project.updated_by = UserInfo.objects.get(userid=user_id)
project.save()
msg={"Succss":"Project Name saved Succssfully","success":"true"}
return JsonResponse(msg)
@csrf_exempt
def getProject(request,user_id):
allProject=Projects.objects.filter(created_by=user_id)
jsondata = serializers.serialize("json", allProject)
return HttpResponse(jsondata,status=200,content_type='application/json')
@csrf_exempt
@jwtValidator
def getprojectDetails(request, project_id):
project = Projects.objects.get(id = project_id)
folder_type_list = FolderType.objects.filter(project__id=project_id).values_list('folder__id', flat=True)
folders = Folder.objects.filter(id__in=folder_type_list)
text_list_data = json.loads(serializers.serialize("json", TextList.objects.filter(project_id = project_id)))
urls = Url.objects.filter(project_id = project_id)
urls = json.loads(serializers.serialize('json', urls))
#print "folders>>",folders
folders_list = []
temp_dict = {}
for f in folders:
temp_dict = {}
temp_dict['folder'] = f.name
temp_dict['id'] = f.id
tl_objs=TextList.objects.filter(folder_id=f)
tl_tmp=[]
for t in tl_objs:
tl_tmp.append({'id':t.id,'file_name':t.name})
temp_dict['tl'] = tl_tmp
temp_dict['sub_folders'] = [create_folder_dict(request,Folder.objects.filter(parent_folder_id=f)) if Folder.objects.filter(parent_folder_id=f).exists() else ""]
folders_list.append(temp_dict)
jsond = json.dumps({'urls': urls, 'project_id': project_id, 'text_folders': json.loads(serializers.serialize("json", Folder.objects.filter(project_id = project_id))) ,'text_list_data': text_list_data, 'text_list_folders': folders_list,'concept_lists':getConceptLists(request,project_id),'stop_lists':getStopLists(request,3)})
#msg={"project_id":project_id}
print jsond
return HttpResponse(jsond)
def getStopLists(request,project_id):
lst_stop_lists = []
try:
lst_stoplist_obj = StopList.objects.filter(id=project_id)
for x in lst_stoplist_obj:
dict_stop_list = {}
lst_stop_list_values = []
lst_stoplist_value_obj = StopListValue.objects.filter(stop_list=x)
for y in lst_stoplist_value_obj:
lst_stop_list_values.append(y.value)
dict_stop_list.update({"name": x.name, "id": x.id, "values": lst_stop_list_values})
lst_stop_lists.append(dict_stop_list)
except Exception, ex13:
print ex13
return lst_stop_lists
def getConceptLists(request,project_id):
project = Projects.objects.get(id=project_id)
try:
lst_concept_lists = []
lst_concept_list_obj = ConceptList.objects.filter(project_id=project)
for x in lst_concept_list_obj:
dict_concept_list = {}
lst_concept_list_values = []
lst_concept_list_value_obj = ConceptListValue.objects.filter(concept_list=x)
lst_umbrella = []
for y in lst_concept_list_value_obj:
dict_umbrella = {}
dict_umbrella.update({"umbrella": y.umbrella})
# lst_umbrella.append(y.umbrella)
lst_concept_list_umbrella_values_obj = ConceptListUmbrellaValues.objects.filter(concept_list_value=y)
for z in lst_concept_list_umbrella_values_obj:
lst_terms_obj = ConceptListUmbrellaValues.objects.filter(
concept_list_value=z.concept_list_value)
terms = ""
lst_terms=[]
for term_obj in lst_terms_obj:
terms = terms + term_obj.term + ","
lst_terms.append(term_obj.term)
terms = terms[:-1]
dict_umbrella.update({"terms": terms, "id": z.id,"lst_terms":lst_terms})
lst_umbrella.append(dict_umbrella)
dict_concept_list.update({"name": x.name,'folder_id':x.folder_id.id, "values": lst_umbrella, "id": x.id})
lst_concept_lists.append(dict_concept_list)
except Exception, ex23:
print ex23
#print "concept_lists=====", json.dumps(lst_concept_lists)
return lst_concept_lists
def create_folder_dict(request, folders):
folders_dict = {}
for f in folders:
print f
folders_dict['folder'] = f.name
folders_dict['id'] = f.id
tl_objs = TextList.objects.filter(folder_id=f)
tl_tmp = []
for t in tl_objs:
tl_tmp.append({'id': t.id, 'file_name': t.name})
folders_dict['tl'] = tl_tmp
#folders_dict['tl'] = list(TextList.objects.filter(folder_id=f))
folders_dict['sub_folders'] = [create_folder_dict(Folder.objects.filter(parent_folder_id=f)) if Folder.objects.filter(parent_folder_id=f).exists() else ""]
return folders_dict
@csrf_exempt
def addFolder(request,project_id,user_id):
print "======projectid",project_id
body_unicode = request.body.decode("utf-8")
body = json.loads(body_unicode)
try:
if 'folder_id' in body:
folder_id=body['folder_id']
if folder_id !="/":
folder_id=int(folder_id.split("/")[0].strip())
parent_folder = Folder.objects.get(id=folder_id)
else:
parent_folder = None
else:
parent_folder = None
folder = Folder(status=1)
folder.name = body['folder_name']
folder.project_id = project_id
folder.created_by = folder.updated_by = UserInfo.objects.get(id=user_id)
folder.status = 1
folder.save()
if parent_folder:
folder.parent_folder_id = parent_folder
folder.save()
else:
print "project id=",project_id
# map with folder type
foldertype_obj = FolderType(folder=folder, project_id=project_id,type="text-list")
foldertype_obj.save()
print folder, folder.id
msg={"msg":"Folder created successfully","success":"true"}
return JsonResponse(msg)
except Exception,ex:
print ex
def docx_to_text(request,filename):
doc = docx.Document(filename)
fullText = []
for para in doc.paragraphs:
fullText.append(para.text)
return '\n'.join(fullText)
def doc_to_text_catdoc(request):
(fi, fo, fe) = os.popen3('catdoc -w "%s"' % '/tmp/temp_doc')
fi.close()
retval = fo.read()
erroroutput = fe.read()
fo.close()
fe.close()
return retval
if not erroroutput:
return retval
else:
raise OSError("Executing the command caused an error: %s" % erroroutput)
@csrf_exempt
def Savetextlist(request,project_id,user_id,folder_id,access_token):
parent_folder=None
#body_unicode = request.body.decode("utf-8")
#body = json.loads(body_unicode)
print ">>>>>>>>>>>>>",request.FILES,len(request.FILES)
pfolder_id=folder_id
# File upload
if pfolder_id:
#parent_folder = Folder.objects.get(id=request.POST['folder_id'])
parent_folder = Folder.objects.get(id=pfolder_id)
print "file name in folder id", request.FILES
mag = {}
if len(request.FILES) > 0:
for i in request.FILES:
file_type=""
try:
file_type=request.FILES[i]._name.strip().split(".")[
len(request.FILES[i]._name.strip().split("."))-1]
except Exception,ex:
print ex
if 'msword' in request.FILES[i].content_type:
file_contents,html = "not found","not found"
myfile = request.FILES[i]
directory=settings.MEDIA_URL + str(uuid.uuid4()) + "/"
fs = FileSystemStorage(location=directory)
if not os.path.exists(directory):
os.makedirs(directory)
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(directory+filename)
access_token_value =access_token
if not access_token_value=="undefined":
file_from = directory+filename
file_to="/"+filename
dbx = dropbox.Dropbox(access_token_value)
f = open(file_from, 'rb')
dbx.files_upload(f.read(), file_to)
print subprocess.call(['soffice', '--headless', '--convert-to', 'docx', directory+filename])
file_contentswithslah=document_to_text(request,filename,directory+filename)
print subprocess.call(['soffice', '--headless', '--convert-to', 'docx', directory+filename])
file_contents=file_contentswithslah.replace("|"," ")
import mammoth
with open(base_url+filename+"x", "rb") as docx_file:
result = mammoth.convert_to_html(docx_file)
html = result.value # The generated HTML
messages = result.messages # Any messages, such as warnings during conversion
print "------>htmldata ===>=======> ",html
with_br_tag=html
elif file_type=="docx":
myfile = request.FILES[i]
directory = settings.MEDIA_URL + str(uuid.uuid4()) + "/"
fs = FileSystemStorage(location=directory)
if not os.path.exists(directory):
os.makedirs(directory)
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(directory+filename)
import mammoth
with open(directory+filename, "rb") as docx_file:
result = mammoth.convert_to_html(docx_file)
html = result.value
messages = result.messages
file_contents=docx2txt.process(request.FILES[i])
with_br_tag=html
import dropbox
access_token_value =access_token
if not access_token_value=="undefined":
file_from = directory+filename
file_to="/"+filename
dbx = dropbox.Dropbox(access_token_value)
f = open(file_from, 'rb')
dbx.files_upload(f.read(), file_to)
elif file_type == "txt":
file_contents = request.FILES[i].file.read()
with_br_tag = file_contents
print "------------------",file_contents
elif file_type == "pdf":
#import pdb
#pdb.set_trace()
myfile = request.FILES[i]
directory = settings.MEDIA_URL + str(uuid.uuid4()) + "/"
fs = FileSystemStorage(location=directory)
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(directory+filename)
pdfData=document_to_text(request,filename,directory+filename)
print "pdf -----content----",pdfData
file_contents = pdfData
with_br_tag = pdfData
#parsedPDF = parser.from_file(directory+filename)
#file_contents = parsedPDF["content"]
#with_br_tag = parsedPDF["content"]
elif file_type == "csv":
print "====in csv file======="
import csv
myfile = request.FILES[i]
directory = settings.MEDIA_URL + str(uuid.uuid4()) + "/"
fs = FileSystemStorage(location=directory)
if not os.path.exists(directory):
os.makedirs(directory)
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(directory+filename)
data=[]
with open(directory+filename) as File:
reader = csv.reader(File)
for row in reader:
data.append(row)
newvalue=''
for i in data:
print "value of i",i
newvalue+=' '.join(i)
file_contents=newvalue
with_br_tag=newvalue
text_list_obj = TextList(name=request.FILES[i]._name,
folder_id=parent_folder,project_id_id=project_id,status=1)
text_list_obj.created_by = text_list_obj.updated_by = UserInfo.objects.get(id=user_id)
text_list_obj.save()
text_list_detail_obj = TextListDetails(text_list_id=text_list_obj,file_content=with_br_tag,
file_content_plain_text=file_contents,status=1)
text_list_detail_obj.created_by = text_list_detail_obj.updated_by = UserInfo.objects.get(id=user_id)
if text_list_detail_obj.save():
msg={"succss":"Textlist created successfully","success":"true"}
else:
msg={"succss":"Textlist not created","success":"false"}
print '------------msg---------',msg
return JsonResponse(msg)
else:
msg={"succss":"Textlist not created","success":"false"}
return JsonResponse(msg)
def document_to_text(request,filename,file_path):
if filename[-4:] == ".doc":
cmd = ['antiword', file_path]
p = Popen(cmd, stdout=PIPE,shell=True)
stdout, stderr = p.communicate()
return stdout.decode('ascii', 'ignore')
elif filename[-4:] == ".pdf":
return convert_pdf_to_txt(file_path)
"""
@csrf_exempt
def Savetextlist(request,project_id,user_id):
parent_folder=None
#body_unicode = request.body.decode("utf-8")
#body = json.loads(body_unicode)
if len(request.FILES) > 0:
print "file save in outside folder id",request.FILES
if len(request.FILES) >0:
file_type=""
try:
print "files name====>",request.FILES['text_file']._name.strip().split(".")
file_type=request.FILES['text_file']._name.strip().split(".")[
len(request.FILES['text_file']._name.strip().split("."))-1]
except Exception,ex:
print ex
print "============>",file_type
file_contents = request.FILES['text_file'].file.read()
if 'msword' in request.FILES['text_file'].content_type:
file_contents="not found"
html="not found"
myfile = request.FILES['text_file']
directory=settings.MEDIA_URL + str(uuid.uuid4()) + "/"
print "diretory========",directory
fs = FileSystemStorage(location=directory)
if not os.path.exists(directory):
os.makedirs(directory)
filename = fs.save(myfile.name, myfile)
print "filename",filename
uploaded_file_url = fs.url(directory+filename)
print "uploaded_file_url=====",uploaded_file_url
print "actula path",directory+filename
file_contentswithslah=document_to_text(request,filename,directory+filename)
file_contents=file_contentswithslah.replace("|"," ")
#print "===========file_content=======",file_contents
html=file_contents.replace("\n","<br>")
print html
elif file_type=="docx":
file_obj = open('temp_doc', 'w')
file_obj.write(file_contents)
file_obj.close()
myfile = request.FILES['text_file']
directory=settings.MEDIA_URL + str(uuid.uuid4()) + "/"
fs = FileSystemStorage(location=directory)
if not os.path.exists(directory):
os.makedirs(directory)
filename = fs.save(myfile.name, myfile)
print "filename",filename
uploaded_file_url = fs.url(directory+filename)
print "uploaded_file_url=====",uploaded_file_url
print directory+filename
html = convert(directory+filename)
file_contents=docx2txt.process(request.FILES['text_file'])
print html
#print "file_contents===========================>",file_contents
text_list_obj = TextList(name=request.FILES['text_file']._name,
folder_id=parent_folder,project_id_id=project_id,status=1)
text_list_obj.created_by = text_list_obj.updated_by = UserInfo.objects.get(id=user_id)
text_list_obj.save()
with_br_tag = html
text_list_detail_obj = TextListDetails(text_list_id=text_list_obj,file_content=with_br_tag,
file_content_plain_text=file_contents,status=1)
#print "with_br_tag======================>",with_br_tag
text_list_detail_obj.created_by = text_list_detail_obj.updated_by = UserInfo.objects.get(id=user_id)
text_list_detail_obj.save()
msg={"succss":"Textlist created successfully","success":"true"}
return JsonResponse(msg)
else:
pass
msg={"succss":"Textlist created successfully","success":"true"}
return JsonResponse(msg)
"""
@csrf_exempt
def saveConceptlist(request,project_id,user_id,folder_id):
#print "9999999999999999", request.POST
file_name=request.FILES['browse_concept_list']._name
print "file name=",file_name
print "concept list>>>>>>>", request.FILES
if request.FILES:
file_contents = request.FILES['browse_concept_list'].file.read()
if file_contents.count('->') > 200:
msg={"success":"alert"}
return JsonResponse(msg)
print "file_contents=",file_contents
lst_concept_list=file_contents.split("\n")
conceptObject=ConceptList.objects.filter(project_id_id=project_id).values('name','status')
print "======conceptObject name======",conceptObject
coceptNames=[concept['name'] for concept in conceptObject]
print "====list of files",coceptNames
if file_name in coceptNames:
print "in =====if========="
jsondata={"msg":"concept list alredy exits","success":"false"}
return JsonResponse(jsondata)
else:
concept_list_obj=ConceptList(folder_id_id=folder_id,name=file_name,project_id=Projects.objects.get(id=project_id),status=1,created_on=datetime.datetime.now(),updated_on=datetime.datetime.now())
concept_list_obj.save()
for x in lst_concept_list:
if len(x)==0:
msg={"succss":"conceptlist added successfully"}
return JsonResponse(msg)
else:
umbrella=ConceptListValue(concept_list=concept_list_obj,umbrella=x.split("[")[0],status=1)
umbrella.save()
try:
for y in x.split("->")[1].split(","):
if len(y.strip())>0 and y is not None:
try:
defination=x[x.find("[")+1 : x.find("]")]
#print "=========defination",defination
#print "============terms=======",y.strip()
umbrella_value_obj=ConceptListUmbrellaValues(concept_list_value=umbrella,term=y.strip(),defination=defination)
umbrella_value_obj.save()
except Exception,ex21:
print "===ex2=====",ex21
except IndexError:
msg={"succss":"conceptlist added successfully"}
JsonResponse(msg)
context = {
'project': Projects.objects.get(id=project_id),
'text_list_folders': get_side_bar(request,project_id),
}
msg={"succss":"conceptlist added successfully"}
return JsonResponse(msg)
def get_side_bar(request,p_id):
project = Projects.objects.get(id=p_id)
folder_type_list = FolderType.objects.filter(project__id=p_id).values_list('folder__id', flat=True)
folders = Folder.objects.filter(id__in=folder_type_list)
#print "folders>>",folders
folders_list = []
temp_dict = {}
for f in folders:
temp_dict = {}
temp_dict['folder'] = f.name
temp_dict['id'] = f.id
tl_objs=TextList.objects.filter(folder_id=f)
tl_tmp=[]
for t in tl_objs:
tl_tmp.append({'id':t.id,'file_name':t.name})
temp_dict['tl'] = tl_tmp
temp_dict['sub_folders'] = [create_folder_dict(Folder.objects.filter(request,parent_folder_id=f)) if Folder.objects.filter(parent_folder_id=f).exists() else ""]
folders_list.append(temp_dict)
#print "temp_dict>>>>>",temp_dict
#print "folders_list>>>",folders_list
return folders_list
def create_folder_dict(request, folders):
folders_dict = {}
for f in folders:
print f
folders_dict['folder'] = f.name
folders_dict['id'] = f.id
tl_objs = TextList.objects.filter(folder_id=f)
tl_tmp = []
for t in tl_objs:
tl_tmp.append({'id': t.id, 'file_name': t.name})
folders_dict['tl'] = tl_tmp
#folders_dict['tl'] = list(TextList.objects.filter(folder_id=f))
folders_dict['sub_folders'] = [create_folder_dict(Folder.objects.filter(parent_folder_id=f)) if Folder.objects.filter(parent_folder_id=f).exists() else ""]
return folders_dict
@csrf_exempt
def deleteUser(request):
"====delete user==="
body_unicode = request.body.decode("utf-8")
body = json.loads(body_unicode)
user_id=body["user_id"]
getclient=User.objects.filter(id=user_id).delete();
getUserInfo = UserInfo.objects.filter(userid=user_id).delete();
msg={"msg":"records deleted successfully","user_id":user_id,"succss":"true"}
return JsonResponse(msg)
@csrf_exempt
def inactiveUser(request,user_id):
userobj=User.objects.get(id=user_id)
userobj.is_active=False
userobj.save()
msg={"msg":"User Inactive succssfully","user_id":user_id,"succss":"true"}
return JsonResponse(msg)
@csrf_exempt
def activateUser(request,user_id):
userobj=User.objects.get(id=user_id)
userobj.is_active=True
userobj.save()
msg={"msg":"User activted succssfully","user_id":user_id,"succss":"true"}
return JsonResponse(msg)
def getuserbyid(request,user_id):
getclient=UserInfo.objects.filter(userid=user_id).values('mobile','userid', 'userobject__username','userobject__first_name','userobject__last_name','userobject__email','userobject__is_active','created_at')
getdate=UserInfo.objects.all().values('created_at')
print str(UserInfo.userid)
print "type",type(getclient)
dictionaries = [ obj for obj in getclient ]
created = [ obj["created_at"] for obj in getdate ]
print created
return HttpResponse(json.dumps({"data": dictionaries}, sort_keys=True, default=str),content_type='application/json')
@csrf_exempt
def concordanceline(request,project_id):
body_unicode = request.body.decode("utf-8")
body = json.loads(body_unicode)
selected_files = unicodedata.normalize('NFKD', body['selected_ids']).encode('ascii','ignore').split(",")
selected_files = filter(None, selected_files)
exportCSV=[]
data_list = []
for file in selected_files:
file_contents = TextListDetails.objects.get(text_list_id__id=file).file_content_plain_text
file_contents_data = file_contents
file_contents_data = file_contents.replace("%",'')
print "file_contents_data========",file_contents_data
textlistname=TextList.objects.get(id=file)
toi_str = unicodedata.normalize('NFKD', body["txt_toi"] ).encode('ascii','ignore')
import copy
#termHeadValue=copy.deepcopy(lst_toi_str)
lst_toi_str = toi_str.split(',')
termHeadValue=copy.deepcopy(lst_toi_str)
# print lst_toi_str,'***********'
lst_toi_str = list(set([x.lower() for x in lst_toi_str])) #
termId=ConceptListUmbrellaValues.objects.filter(term=lst_toi_str[0])[0]
termHead=ConceptListUmbrellaValues.objects.filter(concept_list_value_id=termId.concept_list_value_id)[0]
print "termid===>",termId.concept_list_value_id
conceptId= ConceptListValue.objects.get(id=termId.concept_list_value_id)
print "term head===>",termHead.term
print "concpetlist id",conceptId.concept_list_id
allConceptsValues = getConceptListWordsWithHead(request,conceptId.concept_list_id)
#terms_obj = ConceptListUmbrellaValues.objects.filter(concept_list_value=y)
Conceptslist=[]
#print "allConceptsValues==========>",allConceptsValues
for i in allConceptsValues:
Conceptslist.append(i['values'])
print Conceptslist
for toi_lower in lst_toi_str:
sidesData = {}
rightData = {}
allData = []
line_number=0
# if toi_lower.count(' ') > 0:
pattern = toi_lower.lower() #
findData = [(m.start(0), m.end(0)) for m in re.finditer(pattern, file_contents_data.lower())]
if len(findData):
for ele in findData:
left = ele[0]
right = ele[1]
frontData = left-1 #
if not (file_contents_data[right].isalpha() or file_contents_data[frontData].isalpha()): #
totalLeftData = file_contents_data[0:left]
totalRightData = file_contents_data[right:]
if totalLeftData.count(" ") < 50:
sidesData['left_data'] = file_contents_data[0:]
else:
spaceCount = 0
flag = True
tempLeft = left
while flag:
if file_contents_data[tempLeft] == ' ':
spaceCount += 1
if spaceCount == 49:
flag = False
tempLeft = tempLeft - 1
sidesData['left_data'] = file_contents_data[tempLeft:left]
if totalRightData.count(" ") < 50:
sidesData['right_data'] = file_contents_data[ele[1]:]
else:
spaceCount = 0
flag = True
tempRight = right
while flag:
if file_contents_data[tempRight] == ' ':
spaceCount += 1
if spaceCount == 49:
flag = False
tempRight = tempRight + 1
sidesData['right_data'] = file_contents_data[right:tempRight]
data_list.append({'toi':toi_lower.lower(),
'combination_concept':CombinationHead(request,sidesData['left_data'],sidesData['right_data'],Conceptslist),
'left':sidesData['left_data'],
'head':termHeadValue[0].upper(),
'right':sidesData['right_data'],
'line_number':line_number,
"file_id":file,
'text_list':textlistname.name}
)
exportCSV.append([
textlistname.name,
' '.join(sidesData['left_data'].split(" ")[0:10]),
toi_lower,
' '.join(sidesData['right_data'].split(" ")[0:10]),
lst_toi_str[0].upper(),
ConcordeWith(request,sidesData['left_data'],sidesData['right_data'],lst_toi_str),
])
# exportCSV.append({'Toi':toi_lower.lower(),
# 'Combination Concept':ConcordeWith(request,sidesData['left_data'],sidesData['right_data'],lst_toi_str),
# 'Left':' '.join(sidesData['left_data'].split(" ")[0:10]),
# 'Head':lst_toi_str[0].upper(),
# 'Right':' '.join(sidesData['right_data'].split(" ")[0:10]),
# 'Text List':textlistname.name}
# )
continue
context = {
'results': data_list,
'result_type': "Concordance Lines",
'queries': QueryList.objects.filter(project_id_id=project_id),
'file_id':selected_files[0],
'totaltoi':toi_str
}
col = ['Text List','Left','Search','Right','Head','Combination']#
df = pd.DataFrame(exportCSV,columns=col)
df.to_csv(base_url +"ConcordanceResult.csv", index=False,header=True)
os.system("mv "+base_url +"ConcordanceResult.csv "+ path_url)
jsond = json.dumps({'totaltoi': toi_str,'head':lst_toi_str[0], 'file_id[0]': selected_files,'results':data_list})
return HttpResponse(jsond)
def getStopLists(request,sl_id):
lst_stop_lists = []
try:
lst_stoplist_obj = StopList.objects.filter(id=sl_id)
for x in lst_stoplist_obj:
dict_stop_list = {}
lst_stop_list_values = []
lst_stoplist_value_obj = StopListValue.objects.filter(stop_list=x)
for y in lst_stoplist_value_obj:
lst_stop_list_values.append(y.value)
dict_stop_list.update({"name": x.name, "id": x.id, "values": lst_stop_list_values})
lst_stop_lists.append(dict_stop_list)
except Exception, ex13:
print ex13
return lst_stop_lists
@csrf_exempt
def importstoplist(request):
file_name=request.FILES['browse_stop_list']
print "file_name======",file_name
if request.FILES:
file_contents = request.FILES['browse_stop_list'].file.read()
print "file_contents=",file_contents
lst_stop_list=file_contents.split("\n")
try:
stop_list_obj=StopList(name=file_name,project_id=Projects.objects.get(id=4),status=1,created_on=datetime.datetime.now(),updated_on=datetime.datetime.now())
stop_list_obj.save()
for x in lst_stop_list:
print "=================x============",x
if len(x)==0:
print "=========================in x===",len(x),type(x)
msg={"succss":"conceptlist added successfully"}
return JsonResponse(msg)
stop_list_value=StopListValue(stop_list=stop_list_obj,value=x.split("->")[0],status=1)
stop_list_value.save()