import os
from flask import Flask, flash, request, redirect, url_for, render_template, send_from_directory

from werkzeug.utils import secure_filename

from PIL import Image
import pytesseract
import cv2
import numpy as np
from pytesseract import Output

import numpy as np

from pathlib import Path

from pdf2image import convert_from_path

app = Flask(__name__)

UPLOAD_FOLDER = 'files/upload/'
OUTPUT_FOLDER = 'files/download/'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'bmp', 'webp', 'pdf'}

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def isPDF(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in {'pdf'}

@app.route('/', methods=['GET', 'POST'])
def index():
    cwd = os.getcwd()
    fd = os.path.join(cwd , 'files/download')
    print(fd)
    if(os.path.isdir(fd)==False):
        os.mkdir(fd)

    fu = os.path.join(cwd , 'files/upload')
    if(os.path.isdir(fu)==False):
        os.mkdir(fu)  

    if request.method == 'GET':
            return render_template('index.html', files=os.listdir(fd))
    else:
        return render_template('index.html', files=os.listdir(fu))



@app.route('/download/<filename>')
def download_file(filename):
    return send_from_directory(OUTPUT_FOLDER, filename, as_attachment=True)

@app.route('/delete/<filename>')
def delete_file(filename):
    try:
        os.remove(OUTPUT_FOLDER + filename)
        return render_template('index.html', files=os.listdir(OUTPUT_FOLDER))
    except:
        flash('There was a problem deleting that file')
        return redirect(request.url)

@app.route('/transform', methods=['POST'])
def transformFile():
    if 'file' not in request.files:
        flash('No file part', 'error')
        return redirect(request.url)

    file = request.files['file']

    if file.filename == '':
        flash('No selected file')
        return redirect(request.url)

    if allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        #file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        f = os.path.join(UPLOAD_FOLDER , filename)
        # checking if it is a file
        if isPDF(filename):
            print("je to pdf")
            image = convert_from_path(f)[0]
        else:
            image = Image.open(f)


        custom_config = r'-l ces --oem 1 --psm 6' 
        text = pytesseract.image_to_string(image,config=custom_config)


        text2 = text.encode(encoding = 'UTF-8', errors = 'strict')
        #print(text)

        fout = os.path.join(OUTPUT_FOLDER , Path(filename).stem) + ".txt"
        #print(fout)
        #fout = os.path.join(fout , ".txt")
       # os.makedirs(os.path.dirname(OUTPUT_FOLDER), exist_ok=True)
        #with open(fout, "w") as f:
         #   f.write(text)

        os.remove(os.path.join(UPLOAD_FOLDER , filename))
        return render_template('output.html', text=text, text2=text2)
    else:
        flash('Not suported file format')
        return redirect(request.url)
    

if __name__=="__main__":
    app.run(debug=True)