Browse Source

App Chnages

Adeel 4 years ago
parent
commit
39094d2e27
5 changed files with 1319 additions and 337 deletions
  1. 337 225
      app.py
  2. BIN
      baangt.db
  3. 182 0
      static/css/amsify.suggestags.css
  4. 393 0
      static/js/jquery.amsify.suggestags.js
  5. 407 112
      templates/index.html

+ 337 - 225
app.py

@@ -1,4 +1,3 @@
-
 from flask import Flask,request,jsonify,render_template,send_file,Response,redirect,url_for
 import base64
 from flask_bootstrap import Bootstrap
@@ -9,48 +8,135 @@ import PyPDF2
 import difflib
 import fitz
 from zipfile import ZipFile
-
+import uuid
+import sys
+import os
 
 ALLOWED_EXTENSIONS = {'pdf'}
 app = Flask(__name__)
 Bootstrap(app)
 app.secret_key = '12345'
-app.run
 def allowed_file(filename):
     return '.' in filename and \
            filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
 
-@app.route('/uploadajax', methods=['GET', 'POST'])
-def upload_file():
-    sqliteConnection = sqlite3.connect('baaangt.db')
+@app.route('/upload_reference_ajax', methods=['GET', 'POST'])
+def upload_reference_file():
+    uu_id = uuid.uuid1()
+    sqliteConnection = sqlite3.connect('baangt.db')
     cursor = sqliteConnection.cursor()
     print("Connected to SQLite")
-    cursor.execute('''CREATE TABLE IF NOT EXISTS files (
-    UUID integer PRIMARY KEY,
-    original_pdf_name NOT NULL, 
-    original_pdf text NOT NULL,
-    reference_pdf_name NOT NULL, 
-    reference_pdf text NOT NULL 
-);''')
-    query = """ INSERT INTO files
-                                  (UUID,original_pdf_name, original_pdf,reference_pdf_name,reference_pdf) VALUES (?, ?, ?,?,?)"""
+    cursor.execute('''CREATE TABLE IF NOT EXISTS reference_file (
+        UUID NOT NULL,
+        reference_pdf_name NOT NULL, 
+        reference_pdf text NOT NULL 
+    );''')
+    query = """ INSERT INTO reference_file
+                                  (UUID,reference_pdf_name,reference_pdf) VALUES (?,?,?)"""
     if request.method == 'POST':
         if request.files:
-            file_orig = request.files['original']
             file_ref = request.files['reference']
-            uuid = request.form['UUID']
-            files_json = [{'file_orig':file_orig.filename,'file_ref':file_ref.filename,'uuid':uuid}]
+            files_json = [{'file_ref':file_ref.filename,'uuid':str(uu_id.int)}]
             print(files_json)
-            print(allowed_file(file_orig.filename))
+            # print(allowed_file(file_orig.filename))
             try:
-                if allowed_file(file_orig.filename) and allowed_file(file_ref.filename) and uuid:
-                    blob_orig = base64.b64encode(file_orig.read())
+                if  allowed_file(file_ref.filename):
+                    blob_ref = base64.b64encode(file_ref.read())
+                    data_tuple = (str(uu_id.int),file_ref.filename,blob_ref)
+                    cursor.execute(query,data_tuple)
+                    sqliteConnection.commit()
+                    cursor.close()
+                    return jsonify(files_json)
+                else:
+                    return Response("All fields must be selected", status=400, mimetype='application/json')
+            except Exception as e:
+                exc_type, exc_obj, exc_tb = sys.exc_info()
+                fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
+                print(exc_type, fname, exc_tb.tb_lineno)
+                print(e)
+                return Response("Error in uploading", status=400, mimetype='application/json')
+        else:
+            uuid_value = request.json['uuid']
+            print(str(uuid_value))
+            sql = 'Delete from reference_file where UUID = "{}"'.format(str(uuid_value))
+            print(sql)
+            cursor.execute(sql)
+            sqliteConnection.commit()
+    else:
+        try:
+            cursor.execute('Select UUID, reference_pdf_name from reference_file')
+            db_data = [i for i in cursor.fetchall()]
+            print(db_data)
+            cursor.close()
+            # print(db_data)
+            return jsonify(db_data)
+        except:
+            return jsonify('')
+    return render_template('index.html')
+
+@app.route('/update_reference_ajax', methods=['GET', 'POST'])
+def update_reference_file():
+    
+    sqliteConnection = sqlite3.connect('baangt.db')
+    cursor = sqliteConnection.cursor()
+    print("Connected to SQLite")
+    
+    query = """ UPDATE reference_file
+                SET reference_pdf_name = :name , reference_pdf = :file
+                WHERE UUID = :uuid        
+            """
+    if request.method == 'POST':
+        if request.files:
+            uuid = request.form['uuid']
+            file_ref = request.files['reference']
+            files_json = [{'file_ref':file_ref.filename,'uuid':str(uuid)}]
+            # print(files_json)
+            # print(allowed_file(file_orig.filename))
+            try:
+                if  allowed_file(file_ref.filename):
                     blob_ref = base64.b64encode(file_ref.read())
-                    cursor.execute('select uuid from files where uuid = {}'.format(int(uuid)))
-                    data = [i for i in cursor.fetchall()]
-                    if len(data)!= 0:
-                        return Response("UUID Already Exists", status=400, mimetype='application/json')
-                    data_tuple = (uuid,file_orig.filename,blob_orig,file_ref.filename,blob_ref)
+                    data_tuple = (file_ref.filename,blob_ref,str(uuid))
+                    data = {'name' : file_ref.filename, 'file' : blob_ref, 'uuid' : str(uuid)}
+                    cursor.execute(query,data)
+                    sqliteConnection.commit()
+                    cursor.close()
+                    return jsonify(files_json)
+                else:
+                    return Response("All fields must be selected", status=400, mimetype='application/json')
+            except Exception as e:
+                exc_type, exc_obj, exc_tb = sys.exc_info()
+                fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
+                print(exc_type, fname, exc_tb.tb_lineno)
+                print(e)
+                return Response("Error in uploading", status=400, mimetype='application/json')
+        
+    return render_template('index.html')
+
+
+
+@app.route('/upload_original_ajax', methods=['GET', 'POST'])
+def upload_original_file():
+    uu_id = uuid.uuid1()
+    sqliteConnection = sqlite3.connect('baangt.db')
+    cursor = sqliteConnection.cursor()
+    print("Connected to SQLite")
+    cursor.execute('''CREATE TABLE IF NOT EXISTS original_file (
+        UUID NOT NULL,
+        original_pdf_name NOT NULL, 
+        original_pdf text NOT NULL 
+    );''')
+    query = """ INSERT INTO original_file
+                                  (UUID,original_pdf_name,original_pdf) VALUES (?,?,?)"""
+    if request.method == 'POST':
+        if request.files:
+            file_orig = request.files['original']
+            files_json = [{'file_orig':file_orig.filename,'uuid':str(uu_id.int)}]
+            print(files_json)
+            # print(allowed_file(file_orig.filename))
+            try:
+                if  allowed_file(file_orig.filename):
+                    blob_orig = base64.b64encode(file_orig.read())
+                    data_tuple = (str(uu_id.int),file_orig.filename,blob_orig)
                     cursor.execute(query,data_tuple)
                     sqliteConnection.commit()
                     cursor.close()
@@ -58,231 +144,257 @@ def upload_file():
                 else:
                     return Response("All fields must be selected", status=400, mimetype='application/json')
             except Exception as e:
+                exc_type, exc_obj, exc_tb = sys.exc_info()
+                fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
+                print(exc_type, fname, exc_tb.tb_lineno)
+                print(e)
                 return Response("Error in uploading", status=400, mimetype='application/json')
         else:
-            uuid_value = int(request.json['uuid'])
-            print(type(uuid_value))
-            cursor.execute('Delete from files where UUID = {}'.format(uuid_value))
+            uuid_value = request.json['uuid']
+            print(str(uuid_value))
+            sql = 'Delete from original_file where UUID = "{}"'.format(str(uuid_value))
+            print(sql)
+            cursor.execute(sql)
             sqliteConnection.commit()
-            print(request.json['uuid'])
     else:
         try:
-            cursor.execute('Select UUID, original_pdf_name,reference_pdf_name from files')
+            cursor.execute('Select UUID, original_pdf_name from original_file')
             db_data = [i for i in cursor.fetchall()]
+            print(db_data)
             cursor.close()
             # print(db_data)
             return jsonify(db_data)
         except:
             return jsonify('')
     return render_template('index.html')
+
+
 @app.route('/')
 def index():
     return render_template('index.html')
+# /<uuid1, uuid2>
+@app.route('/comparison',methods=['POST', 'GET'])
+def comparison_():
+    if request.method == 'GET':
+        try:
+            uuid1 = request.args.get('uuid1', None)
+            uuid2 = request.args.get('uuid2', None)
+            print(uuid1,uuid2)
+            
+            sqliteConnection = sqlite3.connect('baangt.db')
+            cursor = sqliteConnection.cursor()
+            
+            orig_sql = 'Select original_pdf from original_file where UUID = "{}"'.format(str(uuid1))
+            cursor.execute(orig_sql)
+            blob = cursor.fetchone()
+            blob_orig = base64.b64decode(blob[0])
+
+            ref_sql = 'Select reference_pdf from reference_file where UUID = "{}"'.format(str(uuid2))
+            cursor.execute(ref_sql)
+            blob = cursor.fetchone()
+            blob_ref = base64.b64decode(blob[0])
+            with open('temp/temp_orig.pdf', 'wb') as f:
+                f.write(blob_orig)
+            with open('temp/temp_ref.pdf', 'wb') as f:
+                f.write(blob_ref)
+
+            input_file1 = 'temp/temp_orig.pdf'
+            input_file2 = 'temp/temp_ref.pdf'
+
+            output_file1 = 'output/Original_file.pdf'
+            output_file2 = 'output/Reference_file.pdf'
+            print('Comparing files ', input_file1, ' and ', input_file2, '.....')
+
+            fullText1 = ""
+
+            pdfFileObj = open(input_file1, 'rb')
+
+            #The pdfReader variable is a readable object that will be parsed
+            pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
+
+            #discerning the number of pages will allow us to parse through all #the pages
+            num_pages = pdfReader.numPages
+            count = 0
+            text = ""
+            pages1 = []
+
+            #The while loop will read each page
+            while count < num_pages:
+                pageObj = pdfReader.getPage(count)
+                count +=1
+                temp = pageObj.extractText()
+                text += temp
+                pages1.append(temp)
+
+            fullText1 = text
+            fullText1 = fullText1.replace('\n', ' ')
+            fullText1 = fullText1.replace(' \n', ' ')
+            fullText1 = re.sub(' +', ' ', fullText1)
+
+            while True:
+                try:
+                    inz = fullText1.index('Seite')
+                    temp = ' '.join(fullText1[inz:].split()[:4])
+                    fullText1 = fullText1.replace(temp, '')
+                except:
+                    break
 
-@app.route('/comparison/<uuid>',methods=['GET'])
-def comparison_(uuid):
-    try:
-    # uuid = int(request.json['uuid'])
-        uuid = int(uuid)
-        sqliteConnection = sqlite3.connect('baaangt.db')
-        cursor = sqliteConnection.cursor()
-        cursor.execute("Select UUID, original_pdf,reference_pdf from files where uuid = {}".format(uuid))
-        blob = cursor.fetchone()
-        blob_orig = base64.b64decode(blob[1])
-        blob_ref = base64.b64decode(blob[2])
-        with open('temp/temp_orig.pdf', 'wb') as f:
-            f.write(blob_orig)
-        with open('temp/temp_ref.pdf', 'wb') as f:
-            f.write(blob_ref)
-
-        input_file1 = 'temp/temp_orig.pdf'
-        input_file2 = 'temp/temp_ref.pdf'
-
-        output_file1 = 'output/Original_file.pdf'
-        output_file2 = 'output/Reference_file.pdf'
-        print('Comparing files ', input_file1, ' and ', input_file2, '.....')
-
-        fullText1 = ""
-
-        pdfFileObj = open(input_file1, 'rb')
-
-        #The pdfReader variable is a readable object that will be parsed
-        pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
-
-        #discerning the number of pages will allow us to parse through all #the pages
-        num_pages = pdfReader.numPages
-        count = 0
-        text = ""
-        pages1 = []
-
-        #The while loop will read each page
-        while count < num_pages:
-            pageObj = pdfReader.getPage(count)
-            count +=1
-            temp = pageObj.extractText()
-            text += temp
-            pages1.append(temp)
-
-        fullText1 = text
-        fullText1 = fullText1.replace('\n', ' ')
-        fullText1 = fullText1.replace(' \n', ' ')
-        fullText1 = re.sub(' +', ' ', fullText1)
-
-        while True:
-            try:
-                inz = fullText1.index('Seite')
-                temp = ' '.join(fullText1[inz:].split()[:4])
-                fullText1 = fullText1.replace(temp, '')
-            except:
-                break
+            fullText2 = ""
+
+            pdfFileObj = open(input_file2, 'rb')
 
-        fullText2 = ""
+            #The pdfReader variable is a readable object that will be parsed
+            pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
 
-        pdfFileObj = open(input_file2, 'rb')
+            #discerning the number of pages will allow us to parse through all #the pages
+            num_pages = pdfReader.numPages
+            count = 0
+            text = ""
+            pages2 = []
 
-        #The pdfReader variable is a readable object that will be parsed
-        pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
+            #The while loop will read each page
+            while count < num_pages:
+                pageObj = pdfReader.getPage(count)
+                count +=1
+                temp = pageObj.extractText()
+                text += temp
+                pages2.append(temp)
 
-        #discerning the number of pages will allow us to parse through all #the pages
-        num_pages = pdfReader.numPages
-        count = 0
-        text = ""
-        pages2 = []
 
-        #The while loop will read each page
-        while count < num_pages:
-            pageObj = pdfReader.getPage(count)
-            count +=1
-            temp = pageObj.extractText()
-            text += temp
-            pages2.append(temp)
+            fullText2 = text
+            fullText2 = fullText2.replace('\n', ' ')
+            fullText2 = fullText2.replace(' \n', ' ')
+            fullText2 = re.sub(' +', ' ', fullText2)
+
+            while True:
+                try:
+                    inz = fullText2.index('Seite')
+                    temp = ' '.join(fullText2[inz:].split()[:4])
+                    fullText2 = fullText2.replace(temp, '')
+                except:
+                    break
 
+            str1 = fullText1
+            str2 = fullText2
 
-        fullText2 = text
-        fullText2 = fullText2.replace('\n', ' ')
-        fullText2 = fullText2.replace(' \n', ' ')
-        fullText2 = re.sub(' +', ' ', fullText2)
+            delta = difflib.Differ().compare(str1.split(), str2.split())
+            # difflist = []
+            one = []
+            two = []
 
-        while True:
+
+            for line in delta:
+                if line[0] == '?':
+                    continue
+                elif line[0] == ' ':
+                    continue
+                else:
+                    if line[0] == '-':
+                        one.append(line[2:])
+                    elif line[0] == '+':
+                        two.append(line[2:])
+
+                    # difflist.append(line)
+
+
+            # mix = [l[:] for l in '\n'.join(difflist).splitlines() if l]
+            one = [l[:] for l in '\n'.join(one).splitlines() if l]
+            two = [l[:] for l in '\n'.join(two).splitlines() if l]
+
+            one_text = ' '.join(one)
+            two_text = ' '.join(two)
+
+            one_final = one_text
+            two_final = two_text
+            matches = SequenceMatcher(None, one_text, two_text).get_matching_blocks()
+            for match in matches:
+                sen = one_text[match.a:match.a + match.size]
+                if len(sen) > 6:
+                    # print(sen)
+                    one_final = one_final.replace(sen, ' ', 1)
+                    two_final = two_final.replace(sen, ' ', 1)
+
+            one_text = one_final
+            two_text = two_final
+
+            matches = SequenceMatcher(None, two_text, one_text).get_matching_blocks()
+            for match in matches:
+                sen = two_text[match.a:match.a + match.size]
+                if len(sen) > 6:
+                    # print(sen)
+                    one_final = one_final.replace(sen, ' ', 1)
+                    two_final = two_final.replace(sen, ' ', 1)
+
+            print('Generating', output_file1, '.....')
+            one_list = one_final.split()
+
+            doc1 = fitz.open(input_file1)
+            page_no = 0
+            for word in one_list:
+                for i in range(page_no, len(pages1)):
+                    if word in pages1[i]:
+                        page = doc1[i]
+                        text_instances = page.searchFor(word)
+                        for inst in text_instances:
+                            highlight = page.addHighlightAnnot(inst)
+                            break
+                        break
+                    page_no += 1
             try:
-                inz = fullText2.index('Seite')
-                temp = ' '.join(fullText2[inz:].split()[:4])
-                fullText2 = fullText2.replace(temp, '')
+                if one_list[0].isdigit():
+                    word = one_list[0]
+                    for i in range(len(pages1)):
+                        page = doc1[i]
+                        text_instances = page.searchFor(word)
+                        for inst in text_instances:
+                            highlight = page.addHighlightAnnot(inst)
+                            break
             except:
-                break
-
-        str1 = fullText1
-        str2 = fullText2
-
-        delta = difflib.Differ().compare(str1.split(), str2.split())
-        # difflist = []
-        one = []
-        two = []
-
-
-        for line in delta:
-            if line[0] == '?':
-                continue
-            elif line[0] == ' ':
-                continue
-            else:
-                if line[0] == '-':
-                    one.append(line[2:])
-                elif line[0] == '+':
-                    two.append(line[2:])
-
-                # difflist.append(line)
-
-
-        # mix = [l[:] for l in '\n'.join(difflist).splitlines() if l]
-        one = [l[:] for l in '\n'.join(one).splitlines() if l]
-        two = [l[:] for l in '\n'.join(two).splitlines() if l]
-
-        one_text = ' '.join(one)
-        two_text = ' '.join(two)
-
-        one_final = one_text
-        two_final = two_text
-        matches = SequenceMatcher(None, one_text, two_text).get_matching_blocks()
-        for match in matches:
-            sen = one_text[match.a:match.a + match.size]
-            if len(sen) > 6:
-                # print(sen)
-                one_final = one_final.replace(sen, ' ', 1)
-                two_final = two_final.replace(sen, ' ', 1)
-
-        one_text = one_final
-        two_text = two_final
-
-        matches = SequenceMatcher(None, two_text, one_text).get_matching_blocks()
-        for match in matches:
-            sen = two_text[match.a:match.a + match.size]
-            if len(sen) > 6:
-                # print(sen)
-                one_final = one_final.replace(sen, ' ', 1)
-                two_final = two_final.replace(sen, ' ', 1)
-
-        print('Generating', output_file1, '.....')
-        one_list = one_final.split()
-
-        doc1 = fitz.open(input_file1)
-        page_no = 0
-        for word in one_list:
-            for i in range(page_no, len(pages1)):
-                if word in pages1[i]:
-                    page = doc1[i]
-                    text_instances = page.searchFor(word)
-                    for inst in text_instances:
-                        highlight = page.addHighlightAnnot(inst)
-                        break
-                    break
-                page_no += 1
-
-        if one_list[0].isdigit():
-            word = one_list[0]
-            for i in range(len(pages1)):
-                page = doc1[i]
-                text_instances = page.searchFor(word)
-                for inst in text_instances:
-                    highlight = page.addHighlightAnnot(inst)
-                    break
-
-        doc1.save(output_file1, garbage=4, deflate=True, clean=True)
-
-        print('Generating', output_file2, '.....')
-        two_list = two_final.split()
-
-        # for i, page in enumerate(pages1):
-        doc2 = fitz.open(input_file2)
-        page_no = 0
-        for word in two_list:
-            for i in range(page_no, len(pages2)):
-                if word in pages2[i]:
-                    page = doc2[i]
-                    text_instances = page.searchFor(word)
-                    for inst in text_instances:
-                        highlight = page.addHighlightAnnot(inst)
+                pass
+            doc1.save(output_file1, garbage=4, deflate=True, clean=True)
+
+            print('Generating', output_file2, '.....')
+            two_list = two_final.split()
+
+            # for i, page in enumerate(pages1):
+            doc2 = fitz.open(input_file2)
+            page_no = 0
+            for word in two_list:
+                for i in range(page_no, len(pages2)):
+                    if word in pages2[i]:
+                        page = doc2[i]
+                        text_instances = page.searchFor(word)
+                        for inst in text_instances:
+                            highlight = page.addHighlightAnnot(inst)
+                            break
                         break
-                    break
-                page_no += 1
-        if two_list[0].isdigit():
-            word = two_list[0]
-            for i in range(len(pages2)):
-                page = doc2[i]
-                text_instances = page.searchFor(word)
-                for inst in text_instances:
-                    highlight = page.addHighlightAnnot(inst)
-                    break
-        doc2.save(output_file2, garbage=4, deflate=True, clean=True)
-        zipObj = ZipFile('output/output.zip', 'w')
-        zipObj.write(output_file1)
-        zipObj.write(output_file2)
-        zipObj.close()
-        print('Finish')
-    except:
-        print('error in comparison')
-        return redirect(url_for('.index',message = 'error in comparison'))
-    return send_file('C:\\Users\\Siraj\\PycharmProjects\\baangt\\output\\output.zip',as_attachment=True)
-
+                    page_no += 1
+            try:
+                if two_list[0].isdigit():
+                    word = two_list[0]
+                    for i in range(len(pages2)):
+                        page = doc2[i]
+                        text_instances = page.searchFor(word)
+                        for inst in text_instances:
+                            highlight = page.addHighlightAnnot(inst)
+                            break
+            except:
+                pass
+            doc2.save(output_file2, garbage=4, deflate=True, clean=True)
+            zipObj = ZipFile('output/output.zip', 'w')
+            zipObj.write(output_file1)
+            zipObj.write(output_file2)
+            zipObj.close()
+            print('Finish')
+        except Exception as e:
+
+            print('error in comparison')
+            print(e)
+            return redirect(url_for('.index',message = 'error in comparison'))
+        
+        
+        return send_file('output\\output.zip', as_attachment=True)
+    else:
+        return redirect(url_for('.index',message = 'Request type not matched.'))
 if __name__ == "__main__":
     app.run()

BIN
baangt.db


+ 182 - 0
static/css/amsify.suggestags.css

@@ -0,0 +1,182 @@
+.amsify-suggestags-area
+.amsify-suggestags-input-area-default {
+	cursor: pointer;
+    border: 1px solid #cccccc;
+    min-height: 20px;
+    padding: 8px 5px;
+}
+
+.amsify-suggestags-area
+.amsify-suggestags-input-area {
+	text-align: left;
+	height: auto;
+}
+
+.amsify-suggestags-area
+.amsify-suggestags-input-area:hover {
+	cursor: text;
+}
+
+.amsify-suggestags-area
+.amsify-suggestags-input-area
+.amsify-suggestags-input {
+	max-width: 200px;
+	padding: 0px 4px;
+	border: 0;
+}
+
+.amsify-suggestags-area
+.amsify-suggestags-input-area
+.amsify-suggestags-input:focus {
+	outline: 0;
+}
+
+.amsify-focus {
+	border-color: #66afe9;
+	outline: 0;
+	-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102,175,233,.6);
+	box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102,175,233,.6);
+}
+
+.amsify-focus-light {
+	border-color: #cacaca;
+	outline: 0;
+	-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(189, 189, 189, 0.6);
+	box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(189, 189, 189, 0.6);
+}
+
+.amsify-suggestags-area
+.amsify-suggestags-label {
+	cursor: pointer;
+	min-height: 20px;
+}
+
+.amsify-toggle-suggestags {
+	float: right;
+	cursor: pointer;
+}
+
+.amsify-suggestags-area .amsify-suggestags-list {
+	display: none;
+	position: absolute;
+	background: white;
+	border: 1px solid #dedede;
+	z-index: 1;
+}
+
+.amsify-suggestags-area
+.amsify-suggestags-list
+ul.amsify-list {
+	list-style: none;
+	padding: 3px 0px;
+	max-height: 150px;
+    overflow-y: auto;
+}
+
+.amsify-suggestags-area
+.amsify-suggestags-list
+ul.amsify-list
+li.amsify-list-item {
+	text-align: left;
+    cursor: pointer;
+    padding: 0px 10px;	
+}
+
+.amsify-suggestags-area
+.amsify-suggestags-list
+ul.amsify-list
+li.amsify-list-item:active {
+	background: #717171;
+    color: white;
+    -moz-box-shadow:    inset 0 0 10px #000000;
+    -webkit-box-shadow: inset 0 0 10px #000000;
+    box-shadow:         inset 0 0 10px #000000;
+}
+
+.amsify-suggestags-area
+.amsify-suggestags-list
+ul.amsify-list
+li.amsify-list-group {
+	text-align: left;
+    padding: 0px 10px;
+    font-weight: bold;
+}
+
+.amsify-suggestags-area
+.amsify-suggestags-list
+ul.amsify-list
+li.amsify-item-pad {
+    padding-left: 30px;
+}
+
+.amsify-suggestags-area
+.amsify-suggestags-list
+ul.amsify-list
+li.amsify-item-noresult {
+    display: none;
+    color: #ff6060;
+    font-weight: bold;
+    text-align: center;
+}
+
+.amsify-suggestags-area
+.amsify-suggestags-list
+.amsify-select-input {
+	display: none;
+}
+
+.amsify-suggestags-area
+.amsify-suggestags-list
+ul.amsify-list
+li.active {
+	background: #d9d8d8;
+}
+
+.amsify-suggestags-area
+.amsify-suggestags-list
+ul.amsify-list
+li.amsify-item-pad.active {
+	font-weight: normal;
+}
+
+.amsify-suggestags-input-area
+.amsify-select-tag {
+    padding: 2px 7px;
+    margin: 0px 4px 1px 0px;
+    -webkit-border-radius: 2px;
+    -moz-border-radius: 2px;
+    border-radius: 2px;
+    display: inline-block;
+}
+
+.amsify-suggestags-input-area
+.amsify-select-tag.col-bg {
+	background: #d8d8d8;
+    color: black;
+}
+
+/*.amsify-suggestags-input-area
+.amsify-select-tag:hover {
+	background: #737373;
+    color: white;
+}*/
+
+.amsify-suggestags-input-area
+.disabled.amsify-select-tag {
+    background: #eaeaea;
+    color: #b9b9b9;
+    pointer-events: none;
+}
+
+.amsify-suggestags-input-area
+.flash.amsify-select-tag {
+    background-color: #f57f7f;
+    -webkit-transition: background-color 200ms linear;
+    -ms-transition: background-color 200ms linear;
+    transition: background-color 200ms linear;
+}
+
+.amsify-suggestags-input-area
+.amsify-remove-tag {
+	cursor: pointer;
+}

+ 393 - 0
static/js/jquery.amsify.suggestags.js

@@ -0,0 +1,393 @@
+/**
+ * Amsify Jquery Select 1.1
+ * https://github.com/amsify42/jquery.amsify.suggestags
+ * http://www.amsify42.com
+ */
+(function($) {
+
+    $.fn.amsifySuggestags = function(options, method) {
+        /**
+         * Merging default settings with custom
+         * @type {object}
+         */
+        var settings = $.extend({
+            type          : 'bootstrap',
+            tagLimit      : -1,
+            suggestions   : [],
+            classes       : [],
+            backgrounds   : [],
+            colors        : [],
+            whiteList     : false,
+            afterAdd      : {},
+            afterRemove   : {},
+        }, options);
+
+        /**
+         * Initialization begins from here
+         * @type {Object}
+         */
+        var AmsifySuggestags = function() {
+            this.selector      = null;
+            this.name          = null;
+            this.defaultLabel  = 'Type here';
+            this.classes       = {
+              sTagsArea     : '.amsify-suggestags-area',
+              inputArea     : '.amsify-suggestags-input-area',
+              inputAreaDef  : '.amsify-suggestags-input-area-default',
+              focus         : '.amsify-focus',
+              sTagsInput    : '.amsify-suggestags-input',
+              listArea      : '.amsify-suggestags-list',
+              list          : '.amsify-list',
+              listItem      : '.amsify-list-item',
+              itemPad       : '.amsify-item-pad',
+              inputType     : '.amsify-select-input',
+              tagItem       : '.amsify-select-tag',
+              colBg         : '.col-bg',
+              removeTag     : '.amsify-remove-tag',
+              readyToRemove : '.ready-to-remove',
+           };
+           this.selectors     = {
+              sTagsArea     : null,
+              inputArea     : null,
+              inputAreaDef  : null,
+              sTagsInput    : null,
+              listArea      : null,
+              list          : null,
+              listGroup     : null,
+              listItem      : null,
+              itemPad       : null,
+              inputType     : null,
+           };
+           this.tagNames = [];
+        };
+
+        AmsifySuggestags.prototype = {
+            /**
+             * Executing all the required settings
+             * @param  {selector} form
+             */
+            _init : function(selector) {
+                if(this.refresh(selector, method)) {
+                  this.selector   = selector;
+                  this.name       = ($(selector).attr('name'))? $(selector).attr('name')+'_amsify': 'amsify_suggestags';
+                  this.createHTML();
+                  this.setEvents();
+                  $(this.selector).hide();
+                  this.setDefault();
+                }
+            },
+
+            createHTML : function() {
+              var HTML                      = '<div class="'+this.classes.sTagsArea.substring(1)+'"></div>';
+              this.selectors.sTagsArea      = $(HTML).insertAfter(this.selector);
+              var labelHTML                 = '<div class="'+this.classes.inputArea.substring(1)+'"></div>';
+              this.selectors.inputArea      = $(labelHTML).appendTo(this.selectors.sTagsArea);
+
+              this.defaultLabel             = ($(this.selector).attr('placeholder') !== undefined)? $(this.selector).attr('placeholder'): this.defaultLabel;
+              var sTagsInput                = '<input type="text" class="'+this.classes.sTagsInput.substring(1)+'" placeholder="'+this.defaultLabel+'">';
+              this.selectors.sTagsInput     = $(sTagsInput).appendTo(this.selectors.inputArea).attr('autocomplete', 'off');
+
+              var listArea              = '<div class="'+this.classes.listArea.substring(1)+'"></div>';
+              this.selectors.listArea   = $(listArea).appendTo(this.selectors.sTagsArea);
+              $(this.selectors.listArea).width($(this.selectors.sTagsArea).width()-3);
+
+              var list                  = '<ul class="'+this.classes.list.substring(1)+'"></ul>';
+              this.selectors.list       = $(list).appendTo(this.selectors.listArea);
+              $(this.createList()).appendTo(this.selectors.list);
+              this.fixCSS();
+            },           
+
+            setEvents : function() {
+              var _self = this;
+              $(this.selectors.inputArea).attr('style', $(this.selector).attr('style'))
+                                         .addClass($(this.selector).attr('class'));
+              $(this.selectors.sTagsInput).focus(function(){
+                $(this).closest(_self.classes.inputArea).addClass(_self.classes.focus.substring(1));
+                if(settings.type == 'materialize') {
+                  $(this).css({
+                    'border-bottom': 'none',
+                    '-webkit-box-shadow': 'none',
+                    'box-shadow': 'none',
+                  });
+                }
+              });
+              $(this.selectors.sTagsInput).blur(function(){
+                $(this).closest(_self.classes.inputArea).removeClass(_self.classes.focus.substring(1));
+              });
+              $(this.selectors.sTagsInput).keyup(function(e){
+                var keycode = (e.keyCode ? e.keyCode : e.which);
+                if(keycode == '13' || keycode == '188') {
+                   var value = $.trim($(this).val().replace(/,/g , ''));
+                   $(this).val('');
+                  _self.addTag(value);
+                } else if(keycode == '8' && !$(this).val()) {
+                  var removeClass = _self.classes.readyToRemove.substring(1);
+                  if($(this).hasClass(removeClass)) {
+                    $item = $(this).closest(_self.classes.inputArea).find(_self.classes.tagItem+':last');
+                    _self.removeTag($item, false);
+                    $(this).removeClass(removeClass);
+                  } else {
+                    $(this).addClass(removeClass);
+                  }
+                } else if(settings.suggestions.length && $(this).val()) {
+                  $(this).removeClass(_self.classes.readyToRemove.substring(1));
+                  _self.processWhiteList(keycode, $(this).val());
+                }
+              });
+              $(window).resize(function(){
+                $(_self.selectors.listArea).width($(_self.selectors.sTagsArea).width()-3);
+              });
+              $(this.selectors.sTagsArea).click(function(){
+                $(_self.selectors.sTagsInput).focus();
+              });
+              $(this.selectors.listArea).find(this.classes.listItem).hover(function(){
+                $(_self.selectors.listArea).find(_self.classes.listItem).removeClass('active');
+                $(this).addClass('active');
+                $(_self.selectors.sTagsInput).val($(this).data('val'));
+              }, function() {
+                 $(this).removeClass('active');
+              });
+              $(this.selectors.listArea).find(this.classes.listItem).click(function(){
+                 _self.addTag($(this).data('val'));
+                 $(_self.selectors.sTagsInput).val('').focus();
+              });
+              this.setRemoveEvent();
+            },
+
+            processWhiteList : function(keycode, value) {
+              if(keycode == '40' || keycode == '38') {
+                var type = (keycode == '40')? 'down': 'up';
+                this.upDownSuggestion(value, type);
+              } else {
+                this.suggestWhiteList(value);
+              }
+            },
+
+            upDownSuggestion : function(value, type) {
+              var _self     = this;
+              var isActive  = false;
+              $(this.selectors.listArea).find(this.classes.listItem+':visible').each(function(){
+                   if($(this).hasClass('active')) {
+                    $(this).removeClass('active');
+                      if(type == 'up') {
+                        $item = $(this).prevAll(_self.classes.listItem+':visible:first');
+                      } else {
+                        $item = $(this).nextAll(_self.classes.listItem+':visible:first');
+                      }
+                      if($item.length) {
+                        isActive = true;
+                        $item.addClass('active');
+                        $(_self.selectors.sTagsInput).val($item.data('val'));
+                      }
+                    return false;
+                   }
+              });
+              if(!isActive) {
+                var childItem = (type == 'down')? 'first': 'last';
+                $item = $(this.selectors.listArea).find(this.classes.listItem+':visible:'+childItem);
+                if($item.length) {
+                  $item.addClass('active');
+                  $(_self.selectors.sTagsInput).val($item.data('val'));
+                }
+              }
+            },
+
+            suggestWhiteList : function(value) {
+              var _self = this;
+              var found = false;
+              $(this.selectors.listArea).find(this.classes.listItem).each(function(){
+                if(~$(this).attr('data-val').toLowerCase().indexOf(value.toLowerCase()) && $.inArray($(this).attr('data-val'), _self.tagNames) === -1) {
+                  $(this).show();
+                  found = true;
+                } else {
+                  $(this).hide();
+                }
+              });
+              if(found)
+                $(this.selectors.listArea).show();
+              else
+                $(this.selectors.listArea).hide();
+            },
+
+            setDefault : function() {
+              var _self = this;
+              var items = $(this.selector).val().split(',');
+              if(items.length) {
+                $.each(items, function(index, item){
+                  _self.addTag($.trim(item));
+                });
+              }
+            },
+
+            setRemoveEvent: function() {
+              var _self = this;
+              $(this.selectors.inputArea).find(this.classes.removeTag).click(function(e){
+                  e.stopImmediatePropagation();
+                  $tagItem = $(this).closest(_self.classes.tagItem);
+                  _self.removeTag($tagItem, false);
+              });
+            },
+
+            createList : function() {
+              var _self     = this;
+              var listHTML  = '';
+              $.each(settings.suggestions, function(index, item){
+                  listHTML += '<li class="'+_self.classes.listItem.substring(1)+'" data-val="'+item+'">'+item+'</li>';
+              });
+              return listHTML;
+            },
+
+            addTag : function(value) {
+              if(!value) return;
+              var html  = '<span class="'+this.classes.tagItem.substring(1)+'" data-val="'+value+'">'+value+' '+this.setIcon()+'</span>';
+              $item = $(html).insertBefore($(this.selectors.sTagsInput));
+              if(settings.tagLimit != -1 && settings.tagLimit > 0 && this.tagNames.length >= settings.tagLimit) {
+              	this.animateRemove($item, true);
+                this.flashItem(value);
+                return false;
+              }
+              var itemKey = $.inArray(value, settings.suggestions);
+              if(settings.whiteList && itemKey === -1) {
+                this.animateRemove($item, true);
+                this.flashItem(value);
+                return false;
+              }
+              if(this.isPresent(value)) {
+                this.animateRemove($item, true);
+                this.flashItem(value);
+              } else {
+                this.customStylings($item, itemKey);
+                this.tagNames.push(value);
+                this.setRemoveEvent();
+                this.setInputValue();
+                if(settings.afterAdd && typeof settings.afterAdd == "function") {
+                  settings.afterAdd(value);
+                }
+              }
+              $(this.selector).trigger('suggestags.add', [value]);
+              $(this.selectors.listArea).find(this.classes.listItem).removeClass('active');
+              $(this.selectors.listArea).hide();
+            },
+
+            isPresent : function(value) {
+              var present = false;
+              $.each(this.tagNames, function(index, tag){
+                if(value.toLowerCase() == tag.toLowerCase()) {
+                  present = true;
+                  return false;
+                }
+              });
+              return present;
+            },
+
+            customStylings : function(item, key) {
+              var isCutom = false;
+              if(settings.classes[key]) {
+                isCutom = true;
+                $(item).addClass(settings.classes[key]);
+              }
+              if(settings.backgrounds[key]) {
+                isCutom = true;
+                $(item).css('background', settings.backgrounds[key]);
+              }
+              if(settings.colors[key]) {
+                isCutom = true;
+                $(item).css('color', settings.colors[key]);
+              }
+              if(!isCutom) $(item).addClass(this.classes.colBg.substring(1));
+            },
+
+            removeTag : function(item, animate) {
+              this.tagNames.splice($(item).index(), 1);
+              this.animateRemove(item, animate);
+              this.setInputValue();
+              $(this.selector).trigger('suggestags.remove', [$(item).attr('data-val')]);
+              if(settings.afterRemove && typeof settings.afterRemove == "function") {
+                settings.afterRemove($(item).attr('data-val'));
+              }
+            },
+
+            animateRemove : function(item, animate) {
+              $(item).addClass('disabled');
+              if(animate) {
+                setTimeout(function(){
+                  $(item).slideUp();
+                  setTimeout(function(){
+                    $(item).remove();
+                  }, 500);
+                }, 500);
+              } else {
+                $(item).remove();
+              }
+            },
+
+            flashItem : function(value) {
+              $item  = '';
+              $(this.selectors.sTagsArea).find(this.classes.tagItem).each(function(){
+                var tagName = $.trim($(this).attr('data-val'));
+                if(value.toLowerCase() == tagName.toLowerCase()) {
+                  $item = $(this);
+                  return false;
+                }
+              });
+              if($item) {
+                $item.addClass('flash');
+                setTimeout(function(){
+                  $item.removeClass('flash');
+                }, 1500);
+              }
+            },
+
+            setIcon : function() {
+              var removeClass = this.classes.removeTag.substring(1);
+              if(settings.type == 'bootstrap') {
+                return '<span class="fa fa-times '+removeClass+'"></span>';
+              } else if(settings.type == 'materialize') {
+                return '<i class="material-icons right '+removeClass+'">clear</i>';
+              } else {
+                return '<b class="'+removeClass+'">&#10006;</b>';
+              }
+            },
+
+            setInputValue: function() {
+              $(this.selector).val(this.tagNames.join(','));
+              this.printValues();
+            },
+
+            fixCSS : function() {
+              if(settings.type == 'amsify') {
+                $(this.selectors.inputArea).addClass(this.classes.inputAreaDef.substring(1)).css({'padding': '5px 5px'});
+              } else if(settings.type == 'materialize') {
+                $(this.selectors.inputArea).addClass(this.classes.inputAreaDef.substring(1)).css({'height': 'auto', 'padding': '5px 5px'});
+                $(this.selectors.sTagsInput).css({'margin': '0', 'height': 'auto'});
+              }
+            },
+
+            printValues : function() {
+              console.info(this.tagNames, $(this.selector).val());
+            },
+
+            refresh : function(selector, method) {
+              $findTags = $(selector).next(this.classes.sTagsArea);
+              if($findTags.length)  $findTags.remove();
+              $(selector).show();
+              if(typeof method !== undefined && method == 'destroy') {
+                return false;
+              } else {
+                return true;
+              }
+            },
+           
+        };
+        
+        /**
+         * Initializing each instance of selector
+         * @return {object}
+         */
+        return this.each(function() {
+            (new AmsifySuggestags)._init(this);
+        });
+
+    };
+
+}(jQuery));

+ 407 - 112
templates/index.html

@@ -9,143 +9,438 @@
 {% import "bootstrap/utils.html" as utils %}
 
 
-
 {% block content %}
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
-    <link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet">
-     <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
-  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
-    <script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
-    <script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
+<link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet">
+<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
+<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
+<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
+<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
+
+
+<!-- Bootstrap CSS -->
+<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
+
+<!-- Bootstrap JS -->
+<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
 
+<!-- Basic Style for Tags Input{{ url_for('static',filename='js/jquery.amsify.suggestags.js') }} -->
+<link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/amsify.suggestags.css') }}">
 
-  <div class="container">
+<!-- Suggest Tags Js -->
+<script type="text/javascript" src="{{ url_for('static',filename='js/jquery.amsify.suggestags.js') }}"></script>
+
+<div class="container">
     <div class="row">
-      <div class="col-md-12">
-        <div id="msg" class="alert alert-primary" role="alert"></div>
-      </div>
+        <div class="col-md-12">
+            <div id="msg" class="alert alert-primary" role="alert"></div>
+        </div>
     </div>
-    <div class="jumbotron">
-      <h1>Upload new File</h1>
-    <form id="upload-file" method="post" enctype="multipart/form-data" onsubmit="return false">
-        <div class="form-group">
-  <label for="uuid">UUID:</label>
-  <input type="text" class="form-control" name="UUID" id="uuid">
+    <section id="reference-file">
+        <div class="jumbotron">
+            <h1>Upload Reference File</h1>
+
+            <form id="upload-reference-file" method="post" enctype="multipart/form-data" onsubmit="return false">
+                <div class="custom-file">
+                    <input type="file" class="custom-file-input" name="reference" id="customFile2">
+                    <label class="custom-file-label" id="custom-file-label2" for="customFile">Choose Reference File</label>
+                    
+                    <div class="form-group">
+                        <input id='taginput' type="text" class="form-control" name="planets", placeholder="Enter Regex">
+                    </div>
+
+                </div>
+                <hr>
+                <br>
+            
+                <button id="ref" class="btn btn-primary"  >Upload</button>
+            </form>
+        </div>
+
+        <table id="reference" class="table table-striped table-bordered" style="width:100%">
+            <thead>
+                <tr>
+                    <th>UUID</th>
+                    <th>Reference File</th>
+                    <th>Update</th>
+                </tr>
+            </thead>
+            <tbody>
+
+
+            </tbody>
+        </table>
+    </section>
+    <section id="orignal-file">
+        <!-- <a href ='#' id='compare_link' style="display: None;">Click Here</a> -->
+        <div class="jumbotron">
+            <h1>Upload Original File</h1>
+
+            <form id="upload-original-file" method="post" enctype="multipart/form-data" onsubmit="return false">
+                <div class="custom-file">
+                    <input type="file" class="custom-file-input" name="original" id="customFile1">
+                    <label class="custom-file-label" id="custom-file-label1" for="customFile">Choose Original File</label>
+                </div>
+                <hr>
+                <br>
+            
+                <button id="orig" class="btn btn-primary"  >Upload</button>
+            </form>
+        </div>
+
+        <table id="original" class="table table-striped table-bordered" style="width:100%">
+            <thead>
+                <tr>
+                    <th>UUID</th>
+                    <th>Original File</th>
+                    <th>UUID Reference File</th>
+                    <th>Delete/Compare</th>
+                </tr>
+            </thead>
+            <tbody>
+
+
+            </tbody>
+        </table>
+    </section>
 </div>
-      <div class="custom-file">
-    <input type="file" class="custom-file-input" name="original" id="customFile1">
-    <label class="custom-file-label" id="custom-file-label1" for="customFile">Choose Original file</label>
-  </div>
-       <div class="custom-file">
-    <input type="file" class="custom-file-input" name="reference" id="customFile2">
-    <label class="custom-file-label" id="custom-file-label2" for="customFile">Choose Reference file</label>
-  </div>
-        <hr>
-        <br>
-
-      <button id="sub" class="btn btn-primary"  >Upload</button>
-    </form>
-    </div>
-  <table id="example" class="table table-striped table-bordered" style="width:100%">
-        <thead>
-            <tr>
-                <th>UUID</th>
-                <th>Original File</th>
-                <th>Reference File</th>
-                <th>Delete/Compare</th>
-            </tr>
-        </thead>
-      <tbody>
-
-
-      </tbody>
-  </table>
-   </div>
-
-    <script>
-
-        {% if  message %}
-             alert({{ message }})
-        {% endif %}
-
-// Add the following code if you want the name of the file appear on select
-$("#customFile1").on("change", function() {
-  var fileName = $(this).val().split("\\").pop();
-  $(this).siblings("#custom-file-label1").addClass("selected").html(fileName);
-});
-$("#customFile2").on("change", function() {
-  var fileName = $(this).val().split("\\").pop();
-  $(this).siblings("#custom-file-label2").addClass("selected").html(fileName);
-});
-
-var data_tables = $('#example').DataTable();
-
-$('#example').on('click', 'a.Delete', function (e) {
-        e.preventDefault();
-        var uuid = data_tables.row( $(this).parents('tr')).data()[0];
-        var json_text = {'uuid':uuid}
-         $.ajax({
-        url: '/uploadajax',
-        type:'POST',
-        data:JSON.stringify(json_text),
-        contentType: 'application/json;charset=UTF-8',
-        success: function() {
-              console.log('deleted')
-        }
+<a href ='#' id='compare_link' style="display: None;">Click Here</a>
+<input style="display: none;" type="file" class="custom-file-input" name="original" id="updatereference">
+
+
+
+<script>
+    $(document).ready(function(){
+        $('input[name="planets"]').amsifySuggestags({
+            suggestions: [], //'Mercury', 'Venus', 'Earth', 'Mars', 'Jupitor', 'Uranus', 'Neptune', 'Pluto'
+        });
+    });
+    // customFile1 ==> Original File
+    // customFile2 ==> Reference File
+    // Add the following code if you want the name of the file appear on select
+    $("#customFile1").on("change", function() {
+      var fileName = $(this).val().split("\\").pop();
+      $(this).siblings("#custom-file-label1").addClass("selected").html(fileName);
     });
-        data_tables
+    $("#customFile2").on("change", function() {
+      var fileName = $(this).val().split("\\").pop();
+      $(this).siblings("#custom-file-label2").addClass("selected").html(fileName);
+    });
+    
+    var data_tables_reference = $('#reference').DataTable();
+    var data_tables_original = $('#original').DataTable();
+    
+    function show_original(){
+        data_tables_original.clear().draw();
+
+        $.ajax({
+            url: '/upload_original_ajax',
+            type:'GET',
+            success: function(data) {
+                var table = $('#reference').DataTable();
+                var plainArray = table
+                    .column( 0 )
+                    .data()
+                    .toArray();
+                
+                
+                $.each(data, function (key, item) {
+                    var buton = '<a href = "" class="Delete">Delete</a>/<a href = "" class="Compare">Compare</a>';
+                    var selct = '<select class="browser-default custom-select myselect"></select>';
+                    var selectString = '<select class="browser-default custom-select myselect" id="'+ item[0] +'">';
+                    $.each(plainArray, function(key, value) {
+                        selectString += '<option value="' + value +'">' + value + '</option>'; 
+                        
+                    });
+
+                    selectString += '</select>';
+                    selct = selectString;
+                    data_tables_original.row.add([item[0],item[1],selct,buton]).draw(true)
+                    
+                });
+                var mySelect = $('.mySelect');
+                $('.mySelect').find('option').remove().end();
+                $.each(plainArray, function(key, value) {
+                    var $option = $("<option/>", {
+                        value: value,
+                        text: value
+                    });
+                    mySelect.append($option);
+                });
+    
+            }
+        });
+    }
+
+
+    $('#reference').on('click', 'a.Delete', function (e) {
+        e.preventDefault();
+        var uuid = data_tables_reference.row( $(this).parents('tr')).data()[0];
+        var json_text = {'uuid':uuid};
+        $.ajax({
+            url: '/upload_reference_ajax',
+            type:'POST',
+            data:JSON.stringify(json_text),
+            contentType: 'application/json;charset=UTF-8',
+            success: function() {
+                console.log('deleted')
+            }
+        });
+        data_tables_reference
             .row( $(this).parents('tr') )
             .remove()
             .draw();
+        show_original();
     } );
+    
+    
+    $('#reference').on('click', 'a.Update', function (e) {
+        e.preventDefault();
+        
+        var temp = data_tables_reference.row( $(this).parents('tr')).data(temp);
+        var uuid = data_tables_reference.row( $(this).parents('tr')).data()[0];
+        // var json_text = {'uuid':uuid};
+        
+        $("#updatereference").trigger('click');
+        // $('input#updatereference').off();
+        jQuery("input#updatereference").change(function () {
+            var form_data = new FormData(); 
+            var files = $('#updatereference')[0].files[0]; 
+            
+            form_data.append('uuid', uuid);
+            form_data.append('reference', files); 
+    
+            $.ajax({
+                type: 'POST',
+                url: '/update_reference_ajax',
+                data: form_data,
+                contentType: false,
+                cache: false,
+                processData: false,
+                success: function(data) {
+                    $('#msg').show();
+                    $('#msg').text('Success');
+                    $("#msg").fadeOut(6000);
+                    
+                    data_tables_reference.clear().draw();
 
+                    $.ajax({
+                        url: '/upload_reference_ajax',
+                        type:'GET',
+                        success: function(data) {
+                            // data_tables_original.ajax.reload();
+                            $.each(data, function (key, item) {
+                                var buton = '<a href = "" class="Delete">Delete</a>/<a href = "" class="Update">Update</a>';
+                                data_tables_reference.row.add([item[0],item[1],buton]).draw(true)
+                                
+                            });
 
+                        }
+                    });
+                },
+                statusCode: {
+                    400: function(data) {
+                            $('#msg').html(data.responseText);
+                            $('#msg').show();
+                            $("#msg").fadeOut(6000);
+                }}
+    
+            });
+                    
+        });
 
-$(document).ready(function() {
-    $('#msg').hide()
-    $.ajax({
-        url: '/uploadajax',
-        type:'GET',
-        success: function(data) {
-              $.each(data, function (key, item) {
-                          var buton = '<a href = "" class="Delete">Delete</a>/<a href = "/comparison/'+ item[0]+'" class="Compare">Compare</a>';
-                          data_tables.row.add([item[0],item[1],item[2],buton]).draw(true)
-                        });
 
+              
+        
+    } );
+
+    $('#original').on('click', 'a.Delete', function (e) {
+        e.preventDefault();
+        var uuid = data_tables_original.row( $(this).parents('tr')).data()[0];
+        var json_text = {'uuid':uuid};
+        $.ajax({
+            url: '/upload_original_ajax',
+            type:'POST',
+            data:JSON.stringify(json_text),
+            contentType: 'application/json;charset=UTF-8',
+            success: function() {
+                console.log('deleted')
+            }
+        });
+        data_tables_original
+            .row( $(this).parents('tr') )
+            .remove()
+            .draw();
+    } );
+
+    $('#original').on('click', 'a.Compare', function (e) {
+        e.preventDefault();
+        var uuid1 = data_tables_original.row( $(this).parents('tr')).data()[0];
+        var uuid2 = $("#" + uuid1).val()
+        
+        console.log(uuid1, uuid2);
+
+        var data = {
+            'uuid1' : uuid1,
+            'uuid2' : uuid2,
         }
-    });
-} );
 
+        var queryString = $.param(data);
+        var url = '/comparison?' + queryString;
+        console.log(url);
+        $("#compare_link").attr("href", url);
+        
+        $("#compare_link").on("click",function(){
+        var url = $(this).attr('href');
+            $(location).attr('href',url);
+            
+        });
+        $("#compare_link").trigger("click");
+
+        
+    } );
+    
+    
+    
+    $(document).ready(function() {
+        $("#msg").hide();
+        $.ajax({
+            url: '/upload_reference_ajax',
+            type:'GET',
+            success: function(data) {
+                // data_tables_original.ajax.reload();
+                $.each(data, function (key, item) {
+                    var buton = '<a href = "" class="Delete">Delete</a>/<a href = "" class="Update">Update</a>';
+                    data_tables_reference.row.add([item[0],item[1],buton]).draw(true)
+                    
+                });
+    
+            }
+        });
+    } );
 
-$(function() {
-    $('#sub').click(function() {
-        var form_data = new FormData($('#upload-file')[0]);
+    $(document).ready(function() {
+        $("#msg").hide();
         $.ajax({
-            type: 'POST',
-            url: '/uploadajax',
-            data: form_data,
-            contentType: false,
-            cache: false,
-            processData: false,
+            url: '/upload_original_ajax',
+            type:'GET',
             success: function(data) {
-                $('#msg').show();
-                $('#msg').text('Success');
-
-              $.each(data, function (key, item) {
-                  var buton = '<a href = "" class="Delete">Delete</a>/<a href = "/comparison/'+ item["uuid"]+'" class="Compare">Compare</a>';
-                  data_tables.row.add([item['uuid'],item['file_orig'],item['file_ref'],buton]).draw(true)
-              });
-            },
-            statusCode: {
-        400: function(data) {
-                $('#msg').html(data.responseText);
-                $('#msg').show();
-    }}
+                var table = $('#reference').DataTable();
+                var plainArray = table
+                    .column( 0 )
+                    .data()
+                    .toArray();
+                    
+                $.each(data, function (key, item) {
+                    var buton = '<a href = "" class="Delete">Delete</a>/<a href = "" class="Compare">Compare</a>';
+                    var selct = '<select class="browser-default custom-select myselect"></select>';
+                    var selectString = '<select class="browser-default custom-select myselect" id="'+ item[0] +'">';
+                    $.each(plainArray, function(key, value) {
+                        selectString += '<option value="' + value +'">' + value + '</option>'; 
+                        
+                    });
 
+                    selectString += '</select>';
+                    selct = selectString;
+                    data_tables_original.row.add([item[0],item[1],selct,buton]).draw(true)
+                    
+                });
+                
+    
+            }
+        });
+    } );
+    
+    
+    $(function() {
+        $('#ref').click(function() {
+            var form_data = new FormData($('#upload-reference-file')[0]);
+            
+            $.ajax({
+                type: 'POST',
+                url: '/upload_reference_ajax',
+                data: form_data,
+                contentType: false,
+                cache: false,
+                processData: false,
+                success: function(data) {
+                    $('#msg').show();
+                    $('#msg').text('Success');
+                    $("#msg").fadeOut(6000);
+
+                    // document.getElementById("#upload-reference-file").reset();
+                    // $("#upload-reference-file")[0].reset();
+                    // $('input[name=planets]').val('');
+                    // $('input[name=reference]').val('');
+                    show_original();
+                    $.each(data, function (key, item) {
+                        var buton = '<a href = "" class="Delete">Delete</a>/<a href = "" class="Update">Update</a>'; //"/update/'+ item[0]+'"
+                      data_tables_reference.row.add([item['uuid'],item['file_ref'],buton]).draw(true)
+                      
+                    });
+                    
+                    
+                },
+                statusCode: {
+                    400: function(data) {
+                            $('#msg').html(data.responseText);
+                            $('#msg').show();
+                            $("#msg").fadeOut(6000);
+                }}
+    
+            });
         });
     });
-});
+    
 
+    $(function() {
+        $('#orig').click(function() {
+            var form_data1 = new FormData($('#upload-original-file')[0]);
 
+            $.ajax({
+                type: 'POST',
+                url: '/upload_original_ajax',
+                data: form_data1,
+                contentType: false,
+                cache: false,
+                processData: false,
+                success: function(data) {
+                    $('#msg').show();
+                    $('#msg').text('Success');
+                    $("#msg").fadeOut(6000);
+                    var table = $('#reference').DataTable();
+                    var plainArray = table
+                        .column( 0 )
+                        .data()
+                        .toArray();
+                    
+                    $.each(data, function (key, item) {
+                      
+                      var buton = '<a href = "" class="Delete">Delete</a>/<a href = "" class="Compare">Compare</a>'; //var buton = '<a href = "" class="Delete">Delete</a>/<a href = "/comparison/'+ item["uuid"]+'" class="Compare">Compare</a>'; 
+                      var selct = '<select class="browser-default custom-select myselect"></select>';
+                      var selectString = '<select class="browser-default custom-select myselect" id="'+ item['uuid'] +'">';
+                        $.each(plainArray, function(key, value) {
+                            selectString += '<option value="' + value +'">' + value + '</option>'; 
+                            
+                        });
+
+                        selectString += '</select>';
+                        selct = selectString;
+                      data_tables_original.row.add([item['uuid'],item['file_orig'],selectString,buton]).draw(true)
+                      
+                    });
+                
+                },
+                statusCode: {
+                    400: function(data) {
+                            $('#msg').html(data.responseText);
+                            $('#msg').show();
+                            $("#msg").fadeOut(6000);
+                }}
+    
+            });
+        });
+    });
+    
 </script>
 {%- endblock %}