Adeel 4 years ago
parent
commit
04deebbbd8

+ 40 - 7
README.md

@@ -1,5 +1,9 @@
 # PDF Comparison Microservice
 
+### Root Folder
+
+Please go into pdf_comaprison_flask_api folder. 
+
 ### Installation
 
 ```
@@ -16,15 +20,44 @@ python app.py
 
 The app will start running on server ```127.0.0.1:5000```
 
-The app contains three fields
+The ```APP ``` contains two sections
 
-* UUID
-* Original File
+### Upload Reference File
+
+This section contains three fields
 * Reference File
+* Description
+* Regex
+
+### Actions
+* Fill in the info. After you upload the form by clicking ```Upload``` button, data will be stored in database and updated in the below table.
+* Click on ```Delete``` link data will be deleted from database and updated in the below table.
+* Click on ```Update``` link after taht choose a file and data will be updated in database and in below table.
+
+### Upload Original File
+
+This section contains three fields
+* Original File
+* Description
+* UUID of Reference File
+
+### Actions
+* Fill in the info. After you upload the form by clicking ```Upload``` button, data will be stored in database and updated in the below table, on success it will automatically call the ```compare``` function to get the comparison of files.
+* Click on ```Delete``` link data will be deleted from database and updated in the below table.
+
+### API ENDPOINTS
+* Upload Reference File : http://127.0.0.1:5000/upload_reference_ajax
+* View Reference Files : http://127.0.0.1:5000/upload_reference_ajax
+* Update Reference File : http://127.0.0.1:5000/update_reference_ajax
+* Delete Reference File : http://127.0.0.1:5000/upload_reference_ajax
+* Upload Original File : http://127.0.0.1:5000/upload_original_ajax
+* View Original Files : http://127.0.0.1:5000/upload_original_ajax
+* Delete Original File : http://127.0.0.1:5000/upload_original_ajax
+* Compare Files : http://127.0.0.1:5000/comparison?uuid1=&uuid2=
+
 
-Fill in the info. After you upload the form by clicking ```Upload``` button, data will be stored in database and updated in the below table.
-Now just click the ```Compare``` link to get the comparison files.
+### Screenshots
 
-### Screenshot
+![alt Picture](https://gogs.earthsquad.global/athos/baangt-PDFComparison/raw/master/a.png)
 
-![alt Picture](https://gogs.earthsquad.global/athos/baangt-PDFComparison/raw/master/images/Capture.PNG)
+![alt Picture](https://gogs.earthsquad.global/athos/baangt-PDFComparison/raw/master/b.png)

static/css/amsify.suggestags.css → api_frontend/css/amsify.suggestags.css


+ 404 - 0
api_frontend/index.html

@@ -0,0 +1,404 @@
+<!DOCTYPE html>
+<html>
+    <head>
+        <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="https://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="css/amsify.suggestags.css">
+
+        <!-- Suggest Tags Js -->
+        <script type="text/javascript" src="js/jquery.amsify.suggestags.js"></script>
+    </head>
+    <body>
+        <div class="container">
+            <div class="row">
+                <div class="col-md-12">
+                    <div id="msg" class="alert alert-primary" role="alert"></div>
+                </div>
+            </div>
+            <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>
+                            
+                            <textarea name="description" class="form-control" id="exampleFormControlTextarea2" rows="3" placeholder="Enter description" style="margin-top: 10px;"></textarea>
+                            
+                            <div class="form-group">
+                                <input id='taginput' type="text" class="form-control" name="planets", placeholder="Enter Regex" style="margin-top: 10px;">
+                            </div>
+        
+                        </div>
+                        
+                        <br>
+                        <div>
+                            <button id="ref" class="btn btn-primary" style="margin-top: 30px;">Upload</button>
+                        </div>
+                    </form>
+                </div>
+        
+                <table id="reference" class="table table-striped table-bordered" style="width:100%">
+                    <thead>
+                        <tr>
+                            <th>UUID</th>
+                            <th>Reference File</th>
+                            <th>Description</th>
+                            <th>Actions</th>
+                        </tr>
+                    </thead>
+                    <tbody>
+        
+        
+                    </tbody>
+                </table>
+            </section>
+            <section id="orignal-file">
+                <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>
+
+                            <textarea name="description" class="form-control" id="exampleFormControlTextarea1" rows="3" placeholder="Enter description" style="margin-top: 10px;"></textarea>
+                            
+                        </div>
+                        <div class="form-group" style="margin-top: 105px;">
+                            <!-- <label for="sel1">Select Reference File UUID</label> -->
+                            <select name="reference_uuid" class="form-control" id="sel1">
+                              <option selected="true" disabled="disabled">Select Reference File UUID</option>   
+                              
+                            </select>
+                          </div>
+                        <br>
+                        <div>
+                            <button id="orig" class="btn btn-primary" style="margin-top:-10px;">Upload & Compare</button>
+                        </div>
+                    </form>
+                </div>
+        
+                <table id="original" class="table table-striped table-bordered" style="width:100%">
+                    <thead>
+                        <tr>
+                            <th>UUID</th>
+                            <th>Original File</th>
+                            <th>Description</th>
+                            <th>UUID Reference File</th>
+                            <th>Actions</th>
+                        </tr>
+                    </thead>
+                    <tbody>
+        
+        
+                    </tbody>
+                </table>
+            </section>
+        </div>
+        <input style="display: none;" type="file" class="custom-file-input" name="original" id="updatereference">
+        <a href ='#' id='compare_link' style="display: None;">Use for compare</a>
+        <script>
+            var URL = 'http://127.0.0.1:5000';
+            
+            $(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);
+            });
+            $("#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();
+            
+            $('#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: URL + '/upload_reference_ajax',
+                    type:'POST',
+                    data:JSON.stringify(json_text),
+                    contentType: 'application/json;charset=UTF-8',
+                    success: function() {
+                        console.log('deleted')
+                        $.ajax({
+                            url: URL + '/upload_reference_ajax',
+                            type:'GET',
+                            success: function(data) {
+                                var newOptionsHtml = '<option selected="true" disabled="disabled">Select Reference File UUID</option>';
+                                
+                                $.each(data, function (key, item) {
+                                    newOptionsHtml += "<option value='" +item[0] +"'>" +item[0] +"</option>";                 
+                                });
+                                $("#sel1").html(newOptionsHtml);
+                            }
+                        });
+                    }
+                });
+
+                
+
+                data_tables_reference
+                    .row( $(this).parents('tr') )
+                    .remove()
+                    .draw();
+                
+            } );
+            
+            $('#reference').on('click', 'a.Update', function (e) {
+                e.preventDefault();
+                
+                var uuid = data_tables_reference.row( $(this).parents('tr')).data()[0];
+                var desc = data_tables_reference.cell($(this).parents('tr'), 2).nodes().to$().find('textarea').val();
+                
+                $("#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('desc', desc);
+                    form_data.append('reference', files); 
+            
+                    $.ajax({
+                        type: 'POST',
+                        url: 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: URL + '/upload_reference_ajax',
+                                type:'GET',
+                                success: function(data) {
+                                    $.each(data, function (key, item) {
+                                        var buton = '<a href = "" class="Delete">Delete</a>/<a href = "" class="Update">Update</a>'; //<a href = "' + URL + '/comparison/'+ item[0]+'" class="Compare">Compare</a>
+                                        var text = '<textarea name="description" class="form-control" id="exampleFormControlTextarea1" rows="3" placeholder="Enter description">'+ item[2] +'</textarea>';
+                                        data_tables_reference.row.add([item[0],item[1],text,buton]).draw(true)
+                                        
+                                    });
+                                }
+                            });
+                        },
+                        statusCode: {
+                            400: function(data) {
+                                    $('#msg').html(data.responseText);
+                                    $('#msg').show();
+                                    $("#msg").fadeOut(6000);
+                        }}
+                    });         
+                });
+            } );
+        
+            $('#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: 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();
+            } );
+
+            
+            $(document).ready(function() {
+                $("#msg").hide();
+                $.ajax({
+                    url: URL + '/upload_reference_ajax',
+                    type:'GET',
+                    success: function(data) {
+                        var newOptionsHtml = '<option selected="true" disabled="disabled">Select Reference File UUID</option>';
+                        
+                        $.each(data, function (key, item) {
+                            newOptionsHtml += "<option value='" +item[0] +"'>" +item[0] +"</option>";
+                            var buton = '<a href = "" class="Delete">Delete</a>/<a href = "" class="Update">Update</a>'; //<a href = "' + URL + '/comparison/'+ item[0]+'" class="Compare">Compare</a>
+                            var text = '<textarea name="description" class="form-control" id="exampleFormControlTextarea1" rows="3" placeholder="Enter description">'+ item[2] +'</textarea>';
+                            data_tables_reference.row.add([item[0],item[1],text,buton]).draw(true)
+                            
+                        });
+                        $("#sel1").html(newOptionsHtml);
+                    }
+                });
+            } );
+            
+            $(document).ready(function() {
+                $("#msg").hide();
+                $.ajax({
+                    url: URL + '/upload_original_ajax',
+                    type:'GET',
+                    success: function(data) {
+                           
+                        $.each(data, function (key, item) {
+                            var buton = '<a href = "" class="Delete">Delete</a>'; ///<a href = "" class="Compare">Compare</a>
+                            var text = '<textarea class="form-control" readonly>'+ item[2] +'</textarea>';
+                            data_tables_original.row.add([item[0],item[1],text, item[3],buton]).draw(true)
+                            
+                        });
+                        
+            
+                    }
+                });
+            } );
+
+
+            $(function() {
+                $('#ref').click(function() {
+                    var form_data = new FormData($('#upload-reference-file')[0]);
+                    
+                    $.ajax({
+                        type: 'POST',
+                        url: URL + '/upload_reference_ajax',
+                        data: form_data,
+                        contentType: false,
+                        cache: false,
+                        processData: false,
+                        success: function(data) {
+                            $('#msg').show();
+                            $('#msg').text('Success');
+                            $("#msg").fadeOut(6000);
+
+                            $.each(data, function (key, item) {
+                              var buton = '<a href = "" class="Delete">Delete</a>/<a href = "" class="Update">Update</a>'; //<a href = "' + URL + '/comparison/'+ item["uuid"]+'" class="Compare">Compare</a>
+                              var text = '<textarea name="description" class="form-control" id="exampleFormControlTextarea1" rows="3" placeholder="Enter description">'+ item['desc'] +'</textarea>';
+                              data_tables_reference.row.add([item['uuid'],item['file_ref'],text,buton]).draw(true)
+                              
+                            });
+                            $.ajax({
+                                url: URL + '/upload_reference_ajax',
+                                type:'GET',
+                                success: function(data) {
+                                    var newOptionsHtml = '<option selected="true" disabled="disabled">Select Reference File UUID</option>';
+                                    
+                                    $.each(data, function (key, item) {
+                                        newOptionsHtml += "<option value='" +item[0] +"'>" +item[0] +"</option>";
+                                                                        
+                                    });
+                                    $("#sel1").html(newOptionsHtml);
+                                }
+                            });
+                        },
+                        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]);
+                    
+                    var uuid1;
+                    var uuid2;
+
+                    $.ajax({
+                        type: 'POST',
+                        url: URL + '/upload_original_ajax',
+                        data: form_data1,
+                        contentType: false,
+                        cache: false,
+                        processData: false,
+                        success: function(data) {
+                            $('#msg').show();
+                            $('#msg').text('Success');
+                            $("#msg").fadeOut(6000);
+                            
+                            $.each(data, function (key, item) {
+                                uuid1 = item['uuid'];
+                                uuid2 = item['ref_uuid'];
+                                var buton = '<a href = "" class="Delete">Delete</a>'; //var buton = '<a href = "" class="Delete">Delete</a>/<a href = "/comparison/'+ item["uuid"]+'" class="Compare">Compare</a>'; 
+                                var text = '<textarea class="form-control" readonly>'+ item['desc'] +'</textarea>';
+                                data_tables_original.row.add([item['uuid'],item['file_orig'],text,item['ref_uuid'],buton]).draw(true)
+                            
+                            });
+                            
+                            // console.log(uuid1, uuid2);
+
+                            var jsondata = {
+                                'uuid1' : uuid1,
+                                'uuid2' : uuid2,
+                            }
+
+                            var queryString = $.param(jsondata);
+                            var url = 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");
+
+
+                        },
+                        statusCode: {
+                            400: function(data) {
+                                    $('#msg').html(data.responseText);
+                                    $('#msg').show();
+                                    $("#msg").fadeOut(6000);
+                            
+                            },
+                            422: function(data) {
+                                    $('#msg').text('Missing Data')
+                                    $('#msg').show();
+                                    $("#msg").fadeOut(6000);
+                            
+                            }
+                        }
+            
+                    });
+                });
+            });
+        
+        </script>
+    </body>
+</html>

static/js/jquery.amsify.suggestags.js → api_frontend/js/jquery.amsify.suggestags.js


BIN
baangt.db


BIN
images/a.png


BIN
images/b.png


BIN
output/Original_file.pdf


BIN
output/Reference_file.pdf


BIN
output/output.zip


+ 91 - 62
app.py

@@ -4,6 +4,7 @@ from flask_bootstrap import Bootstrap
 import sqlite3
 import re
 from difflib import SequenceMatcher
+from flask_cors import CORS
 import PyPDF2
 import difflib
 import fitz
@@ -11,9 +12,11 @@ from zipfile import ZipFile
 import uuid
 import sys
 import os
+from pathlib import Path
 
 ALLOWED_EXTENSIONS = {'pdf'}
 app = Flask(__name__)
+CORS(app)
 Bootstrap(app)
 app.secret_key = '12345'
 def allowed_file(filename):
@@ -27,22 +30,27 @@ def upload_reference_file():
     cursor = sqliteConnection.cursor()
     print("Connected to SQLite")
     cursor.execute('''CREATE TABLE IF NOT EXISTS reference_file (
-        UUID NOT NULL,
-        reference_pdf_name NOT NULL, 
-        reference_pdf text NOT NULL 
-    );''')
+                        UUID NOT NULL,
+                        reference_pdf_name NOT NULL, 
+                        reference_pdf text NOT NULL,
+                        description text NOT NULL 
+                    );''')
     query = """ INSERT INTO reference_file
-                                  (UUID,reference_pdf_name,reference_pdf) VALUES (?,?,?)"""
+                                  (UUID,reference_pdf_name,reference_pdf, description) VALUES (?,?,?,?)"""
+    #### POST REQUEST FOR UPLOAD, DELETE
     if request.method == 'POST':
+        #### UPLOAD
         if request.files:
+            print('sdddssd')
+            desc = request.form['description']
             file_ref = request.files['reference']
-            files_json = [{'file_ref':file_ref.filename,'uuid':str(uu_id.int)}]
+            files_json = [{'file_ref':file_ref.filename,'uuid':str(uu_id.int), 'desc':desc}]
             print(files_json)
             # print(allowed_file(file_orig.filename))
             try:
                 if  allowed_file(file_ref.filename):
                     blob_ref = base64.b64encode(file_ref.read())
-                    data_tuple = (str(uu_id.int),file_ref.filename,blob_ref)
+                    data_tuple = (str(uu_id.int),file_ref.filename,blob_ref,desc)
                     cursor.execute(query,data_tuple)
                     sqliteConnection.commit()
                     cursor.close()
@@ -55,6 +63,7 @@ def upload_reference_file():
                 print(exc_type, fname, exc_tb.tb_lineno)
                 print(e)
                 return Response("Error in uploading", status=400, mimetype='application/json')
+        #### DELETE
         else:
             uuid_value = request.json['uuid']
             print(str(uuid_value))
@@ -62,9 +71,11 @@ def upload_reference_file():
             print(sql)
             cursor.execute(sql)
             sqliteConnection.commit()
+            return jsonify('') #Response("Deleted", mimetype='application/json')
+    #### GET REQUEST FOR GET RESULTS
     else:
         try:
-            cursor.execute('Select UUID, reference_pdf_name from reference_file')
+            cursor.execute('Select UUID, reference_pdf_name, description from reference_file')
             db_data = [i for i in cursor.fetchall()]
             print(db_data)
             cursor.close()
@@ -72,7 +83,7 @@ def upload_reference_file():
             return jsonify(db_data)
         except:
             return jsonify('')
-    return render_template('index.html')
+    # return render_template('index.html')
 
 @app.route('/update_reference_ajax', methods=['GET', 'POST'])
 def update_reference_file():
@@ -82,37 +93,41 @@ def update_reference_file():
     print("Connected to SQLite")
     
     query = """ UPDATE reference_file
-                SET reference_pdf_name = :name , reference_pdf = :file
+                SET reference_pdf_name = :name , reference_pdf = :file , description = :desc
                 WHERE UUID = :uuid        
             """
+    #### POST REQUEST FOR UPDATE
     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())
-                    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')
-
-
+                uuid = request.form['uuid']
+                desc = request.form['desc']
+                file_ref = request.files['reference']
+                files_json = [{'file_ref':file_ref.filename,'uuid':str(uuid),'desc':desc}]
+                # print(files_json)
+                # print(allowed_file(file_orig.filename))
+                try:
+                    if  allowed_file(file_ref.filename):
+                        blob_ref = base64.b64encode(file_ref.read())
+                        data_tuple = (file_ref.filename,blob_ref,str(uuid))
+                        data = {'name' : file_ref.filename, 'file' : blob_ref, 'desc' : desc, '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')
+            except:
+                return Response("All fields must be selected", status=400, mimetype='application/json')
+    else:
+        return Response("Bad request", status=400, mimetype='application/json')    
+    # return render_template('index.html')
 
 @app.route('/upload_original_ajax', methods=['GET', 'POST'])
 def upload_original_file():
@@ -123,32 +138,37 @@ def upload_original_file():
     cursor.execute('''CREATE TABLE IF NOT EXISTS original_file (
         UUID NOT NULL,
         original_pdf_name NOT NULL, 
-        original_pdf text NOT NULL 
+        original_pdf text NOT NULL,
+        description text NOT NULL,
+        reference_uuid NOT NULL
     );''')
     query = """ INSERT INTO original_file
-                                  (UUID,original_pdf_name,original_pdf) VALUES (?,?,?)"""
+                                  (UUID,original_pdf_name,original_pdf, description, reference_uuid) 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:
+                desc = request.form['description']
+                ref_uuid = request.form['reference_uuid']
+                file_orig = request.files['original']
+                files_json = [{'file_orig':file_orig.filename,'uuid':str(uu_id.int), 'desc':desc, 'ref_uuid':ref_uuid}]
+                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)
+                    data_tuple = (str(uu_id.int),file_orig.filename,blob_orig, desc, ref_uuid)
                     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')
+                    return Response("All fields must be selected", status=422, 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 Response("All fields must be selected", status=422, mimetype='application/json')
         else:
             uuid_value = request.json['uuid']
             print(str(uuid_value))
@@ -156,9 +176,10 @@ def upload_original_file():
             print(sql)
             cursor.execute(sql)
             sqliteConnection.commit()
+            return jsonify('')
     else:
         try:
-            cursor.execute('Select UUID, original_pdf_name from original_file')
+            cursor.execute('Select UUID, original_pdf_name, description, reference_uuid from original_file')
             db_data = [i for i in cursor.fetchall()]
             print(db_data)
             cursor.close()
@@ -166,17 +187,13 @@ def upload_original_file():
             return jsonify(db_data)
         except:
             return jsonify('')
-    return render_template('index.html')
+    # 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:
+            root_dir = Path.cwd()
             uuid1 = request.args.get('uuid1', None)
             uuid2 = request.args.get('uuid2', None)
             print(uuid1,uuid2)
@@ -189,20 +206,24 @@ def comparison_():
             blob = cursor.fetchone()
             blob_orig = base64.b64decode(blob[0])
 
+            with open(root_dir.joinpath('temp', 'temp_orig.pdf'), 'wb') as f:
+                f.write(blob_orig)
+
             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:
+
+            with open(root_dir.joinpath('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'
+            input_file1 = root_dir.joinpath('temp', 'temp_orig.pdf')
+            input_file2 = root_dir.joinpath('temp', 'temp_ref.pdf')
+
+            output_file1 = Path() / 'output' / 'Original_file.pdf'
+            output_file2 = Path() / 'output' / 'Reference_file.pdf'
+
             print('Comparing files ', input_file1, ' and ', input_file2, '.....')
 
             fullText1 = ""
@@ -381,7 +402,7 @@ def comparison_():
             except:
                 pass
             doc2.save(output_file2, garbage=4, deflate=True, clean=True)
-            zipObj = ZipFile('output/output.zip', 'w')
+            zipObj = ZipFile(root_dir.joinpath('output', 'output.zip'), 'w')
             zipObj.write(output_file1)
             zipObj.write(output_file2)
             zipObj.close()
@@ -390,11 +411,19 @@ def comparison_():
 
             print('error in comparison')
             print(e)
-            return redirect(url_for('.index',message = 'error in comparison'))
+            return Response("Error in Comparison", status=400, mimetype='application/json')
         
         
-        return send_file('output\\output.zip', as_attachment=True)
+        return send_file(root_dir.joinpath('output', 'output.zip'), as_attachment=True)
     else:
-        return redirect(url_for('.index',message = 'Request type not matched.'))
+        print('sss')
+        return Response("Bad Request", status=400, mimetype='application/json')
+
+
+
+@app.route('/')
+def index():
+    return render_template('default.html')
+
 if __name__ == "__main__":
     app.run()

+ 1 - 0
requirements.txt

@@ -44,3 +44,4 @@ traits==6.0.0
 urllib3==1.25.8
 visitor==0.1.3
 Werkzeug==1.0.1
+flask-cors

+ 14 - 0
pdf_comaprison_flask_api/templates/default.html

@@ -0,0 +1,14 @@
+<h1>URLS</h1>
+<h3>
+  <ul>
+      <li>Upload Reference File(POST REQ along with data) : http://127.0.0.1:5000/upload_reference_ajax</li>
+      <li>View Reference Files(GET REQ) : http://127.0.0.1:5000/upload_reference_ajax</li>
+      <li>Update Reference File(POST REQ along with data) : http://127.0.0.1:5000/update_reference_ajax</li>
+      <li>Delete Reference File(POST REQ along with UUID) : http://127.0.0.1:5000/upload_reference_ajax</li>
+      <li>Upload Original File(POST REQ along with data) : http://127.0.0.1:5000/upload_original_ajax</li>
+      <li>View Original Files(GET REQ) : http://127.0.0.1:5000/upload_original_ajax</li>
+      <li>Delete Original File(POST REQ along with UUID) : http://127.0.0.1:5000/upload_original_ajax</li>
+      <li>Compare Files(GET REQ along with UUID) : http://127.0.0.1:5000/comparison?uuid1=&uuid2=</li>
+  </ul>
+</h3>
+

BIN
temp/temp_orig.pdf


BIN
temp/temp_ref.pdf


+ 0 - 446
templates/index.html

@@ -1,446 +0,0 @@
-{##}
-{# This simple template derives from ``base.html``. See ``base.html`` for
-{#   more information about template inheritance. #}
-{#{%- extends "bootstrap/base.html" %}#}
-{##}
-{# Loads some of the macros included with Flask-Bootstrap. We are using the
-{#   utils module here to automatically render Flask's flashed messages in a#}
-{#   bootstrap friendly manner #}
-{% 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>
-
-
-<!-- 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') }}">
-
-<!-- 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>
-    <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>
-<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);
-    });
-    $("#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);
-                }}
-    
-            });
-                    
-        });
-
-
-              
-        
-    } );
-
-    $('#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)
-                    
-                });
-    
-            }
-        });
-    } );
-
-    $(document).ready(function() {
-        $("#msg").hide();
-        $.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)
-                    
-                });
-                
-    
-            }
-        });
-    } );
-    
-    
-    $(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 %}