Adeel 4 years ago
parent
commit
579b986feb
5 changed files with 114 additions and 61 deletions
  1. 41 45
      api_frontend/index.html
  2. BIN
      images/a.png
  3. BIN
      images/b.png
  4. 61 10
      pdf_comaprison_flask_api/app.py
  5. 12 6
      pdf_comaprison_flask_api/models.py

+ 41 - 45
api_frontend/index.html

@@ -8,18 +8,9 @@
         <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://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
 
-        <!-- 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">
@@ -38,17 +29,12 @@
                             <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 inner-addon left-addon">
-                                <i class="glyphicon glyphicon-user"></i>
-                                <input id='taginput' type="text" class="form-control" name="regex", placeholder="Enter Regex" style="margin-top: 10px;">
-                            </div>
-        
+                                   
                         </div>
                         
                         <br>
                         <div>
-                            <button id="ref" class="btn btn-primary" style="margin-top: 30px;">Upload</button>
+                            <button id="ref" class="btn btn-primary" style="margin-top: 120px;">Upload</button>
                         </div>
                     </form>
                 </div>
@@ -73,15 +59,20 @@
                     <h1>Upload Original File</h1>
         
                     <form id="upload-original-file" method="post" enctype="multipart/form-data" onsubmit="return false">
-                        <div class="custom-file">
+                        <div class="custom-file"  id="orig-upload-form">
                             <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 class="input-group col-sm-3" style="margin-top: 10px; margin-left: -15px;">
+                                <input type="text" class="form-control" name="regex1" id="regex1" placeholder="Enter Regex" >
+                                <span class="input-group-addon"></span>
+                                <i id="add1" onClick="addField();" class="fa fa-plus-square fa-2x" aria-hidden="true" style="margin-top: 5px;margin-left: 10px;"></i>
+                            </div>
+
                         </div>
-                        <div class="form-group" style="margin-top: 105px;">
-                            <!-- <label for="sel1">Select Reference File UUID</label> -->
+                        <div class="form-group" style="margin-top: 15px;">
                             <select name="reference_uuid" class="form-control" id="sel1">
                               <option selected="true" disabled="disabled">Select Reference File UUID</option>   
                               
@@ -115,12 +106,23 @@
         <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="regex"]').amsifySuggestags({
-                    suggestions: [], //'Mercury', 'Venus', 'Earth', 'Mars', 'Jupitor', 'Uranus', 'Neptune', 'Pluto'
-                });
-            });
+            var count = 1;
+
+            function addField()
+            {   
+                var value = $('#regex' + count).val();
+                if(value != ""){
+                    $('#add' + count).hide();
+                    count += 1;
+                    var html = '<div class="input-group col-sm-3" style="margin-top: 10px; margin-left: -15px;"><input type="text" class="form-control" name="regex'  + count + '" id="regex'  + count + '" placeholder="Enter Regex" ><span class="input-group-addon"></span><i id="add'  + count + '" onClick="addField();" class="fa fa-plus-square fa-2x" aria-hidden="true" style="margin-top: 5px;margin-left: 10px;"></i></div>';
+                    $("#orig-upload-form" ).append( html );
+                }
+                else{
+                    $('#msg').text('Enter Regex Please');
+                    $('#msg').show();
+                    $("#msg").fadeOut(6000);
+                }
+            }
             // customFile1 ==> Original File
             // customFile2 ==> Reference File
             // Add the following code if you want the name of the file appear on select
@@ -360,8 +362,6 @@
                             
                             });
                             
-                            // console.log(uuid1, uuid2);
-
                             var jsondata = {
                                 'uuid1' : uuid1,
                                 'uuid2' : uuid2,
@@ -369,24 +369,20 @@
 
                             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);
-                                
+                            $.ajax({
+                                url: url,
+                                type:'GET',
+                                success: function(data) {
+                                    
+                                    console.log(data);
+                                    
+                                    link = URL + '/download_comparison';
+                                    
+                                    window.open(link, '_blank');
+                                    
+                                }
                             });
-                            $("#compare_link").trigger("click");
-
-                            // $.ajax({
-                            //     url: URL + '/comparison_results',
-                            //     type:'GET',
-                            //     success: function(data) {
-                            //         console.log(data.diff_file_1);
-                            //         console.log(data.diff_file_2);
-                            //     }
-                            // });
 
                         },
                         statusCode: {

BIN
images/a.png


BIN
images/b.png


+ 61 - 10
pdf_comaprison_flask_api/app.py

@@ -25,7 +25,7 @@ app.config.from_object(Config)
 db = SQLAlchemy(app)
 migrate = Migrate(app, db)
 
-from models import ReferenceFile, OriginalFile
+from models import ReferenceFile, OriginalFile, OriginalFileRegex
 
 CORS(app)
 Bootstrap(app)
@@ -44,7 +44,6 @@ def upload_reference_file():
         #### UPLOAD
         if request.files:
             desc = request.form['description']
-            regex = request.form['regex']
             file_ref = request.files['reference']
             files_json = [{'file_ref':file_ref.filename,'uuid':str(uu_id.int), 'desc':desc}]
             try:
@@ -54,8 +53,7 @@ def upload_reference_file():
                         uuid=str(uu_id.int), 
                         reference_pdf_name=file_ref.filename,
                         reference_pdf=blob_ref,
-                        description=desc,
-                        regex=regex)
+                        description=desc)
                     db.session.add(ref)
                     db.session.commit()
                     return jsonify(files_json)
@@ -130,6 +128,19 @@ def upload_original_file():
                 desc = request.form['description']
                 ref_uuid = request.form['reference_uuid']
                 file_orig = request.files['original']
+                count = 1
+                regex_list = []
+                while True:
+                    try:
+                        reg = request.form['regex' + str(count)]
+                        if reg == '':
+                            break 
+                        else:
+                            regex_list.append(reg)
+                    except Exception:
+                        break
+                    count += 1 
+                
                 files_json = [{'file_orig':file_orig.filename,'uuid':str(uu_id.int), 'desc':desc, 'ref_uuid':ref_uuid}]
                 if  allowed_file(file_orig.filename):
                     blob_orig = base64.b64encode(file_orig.read())
@@ -141,6 +152,13 @@ def upload_original_file():
                         uuid_ref=ref_uuid)
                     db.session.add(orig)
                     db.session.commit()
+
+                    for i, reg in enumerate(regex_list):
+                        orig_regex = OriginalFileRegex(
+                            regex=reg,
+                            uuid_orig=str(uu_id.int))
+                        db.session.add(orig_regex)
+                    db.session.commit()
                     return jsonify(files_json)
                 else:
                     return Response("All fields must be selected", status=422, mimetype='application/json')
@@ -152,9 +170,15 @@ def upload_original_file():
                 return Response("All fields must be selected", status=422, mimetype='application/json')
         else:
             uuid_value = request.json['uuid']
-            orig = OriginalFile.query.filter_by(uuid = uuid_value).one()
-            db.session.delete(orig)
-            db.session.commit()
+            try:
+                OriginalFileRegex.query.filter_by(uuid_orig = uuid_value).delete()
+                db.session.commit()
+
+                orig = OriginalFile.query.filter_by(uuid = uuid_value).one()
+                db.session.delete(orig)
+                db.session.commit()
+            except Exception:
+                pass
             return jsonify('')
     else:
         try:
@@ -231,6 +255,7 @@ def comparison_():
                     full_text1 = full_text1.replace(temp, '')
                 except Exception:
                     break
+            pdf_file_obj.close()
 
             pdf_file_obj = open(input_file2, 'rb')
 
@@ -265,6 +290,8 @@ def comparison_():
                 except Exception:
                     break
 
+            pdf_file_obj.close()
+
             str1 = full_text1
             str2 = full_text2
 
@@ -388,17 +415,41 @@ def comparison_():
         except Exception:
             logging.error("Exception occurred", exc_info=True)
             return Response("Error in Comparison", status=400, mimetype='application/json')
+
+        if one_final == "" and two_final == "":
+            resp = {'result' : 'OK'}
+            return jsonify(resp)
+
+        else:
+            resp = {'result' : {'orig_file_diff' : one_final, 'ref_file_diff': two_final}}
+            return jsonify(resp)
+
         
-        
-        return send_file(basedir.joinpath('output', 'output.zip'), as_attachment=True)
     else:
         return Response("Bad Request", status=400, mimetype='application/json')
 
-
+@app.route('/download_comparison',methods=['POST', 'GET'])
+def download_comparison_():
+    if request.method == 'GET':
+        basedir = Path.cwd()
+        return send_file(basedir.joinpath('output', 'output.zip'), as_attachment=True)
+        
 @app.route('/')
 def index():
     return render_template('default.html')
 
+@app.after_request
+def add_header(r):
+    """
+    Add headers to both force latest IE rendering engine or Chrome Frame,
+    and also to cache the rendered page for 10 minutes.
+    """
+    r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
+    r.headers["Pragma"] = "no-cache"
+    r.headers["Expires"] = "0"
+    r.headers['Cache-Control'] = 'public, max-age=0'
+    return r
+
 if __name__ == "__main__":
     logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)
     app.run(host='0.0.0.0')

+ 12 - 6
pdf_comaprison_flask_api/models.py

@@ -1,12 +1,11 @@
-from api import db
+from app import db
 import datetime
 class ReferenceFile(db.Model):
     uuid = db.Column(db.String(64), primary_key=True)
     reference_pdf_name = db.Column(db.String(64), nullable=False)
     reference_pdf = db.Column(db.LargeBinary, nullable=False)
     description = db.Column(db.String(250), nullable=False)
-    regex = db.Column(db.String(250), nullable=True) 
-    # original_files = db.relationship('Original_File', backref='reference_pdf', lazy=True)
+    
     def __repr__(self):
         return '<UUID {}>'.format(self.uuid)
 
@@ -16,7 +15,14 @@ class OriginalFile(db.Model):
     original_pdf = db.Column(db.LargeBinary, nullable=False)
     description = db.Column(db.String(250), nullable=False)
     uuid_ref = db.Column(db.String(64), nullable=False)
-    # timestamp = db.Column(db.DateTime, index=True, default=datetime.datetime.utcnow())
-    # UUID_F = db.Column(db.Integer, db.ForeignKey('reference_file.UUID'), nullable=False)
+    
     def __repr__(self):
-        return '<UUID {}>'.format(self.uuid)
+        return '<UUID {}>'.format(self.uuid)
+
+class OriginalFileRegex(db.Model):
+    id = db.Column(db.Integer, primary_key=True)
+    regex = db.Column(db.String(250), nullable=False)
+    uuid_orig = db.Column(db.String(64), nullable=False) 
+    
+    def __repr__(self):
+        return '<ID {}>'.format(self.id)