Conversion_Kitchen_Code/kitchen_counter/utils/scripts_functions.py

132 lines
3.2 KiB
Python
Executable File

from datetime import datetime
from django.core.files.base import ContentFile
from pandas import DataFrame
# import page_script.models as ps_models
from mnfapp.models import SampleScript,PitchVector,MNFScriptDatabase
def script_id_generator():
now = datetime.now()
rightNow = str(now)
dash_splited = rightNow.split("-")
str1 = ""
for i in dash_splited:
str1 += str(i)
dash_splited1 = str1.split(" ")
str2 = ""
for i in dash_splited1:
str2 += str(i)
dash_splited2 = str2.split(":")
str3 = ""
for i in dash_splited2:
str3 += str(i)
dash_splited3 = str3.split(".")
str4 = dash_splited3[0]
return str4
def name_exists(user, name_script) -> bool:
name_script = name_script.lower()
scripts = ps_models.script_version.objects.filter(user_id=user)
for i in scripts:
if i.script_name.lower() == name_script:
return True
return False
def script_upload(file, user, flag=0) -> dict:
script_name = str(file.name).rsplit(".", 1)[0]
if name_exists(user, script_name):
obj = ps_models.script_version.objects.filter(user_id=user).first()
return True
else:
return False
# if name_exists(user, script_name):
# raise FileExistsError("A script with this name already exists")
x = ps_models.MNFScriptDatabase_2()
x.user_id = user
x.script_id = "scr_" + script_id_generator()
x.generated_from = "script_editor_W"
x.script_file = file
x.script_name = script_name
y = ps_models.script_version()
y.script_name = script_name
y.user_id = user
y.versions_count = 1
x.version_no = 1
x.save()
y.save()
y.versions.add(x)
y.save()
return {"script_id": x.script_id}
def override_script(audited_csv: DataFrame, script_id: str) -> None:
f_path, f_name = ps_models.MNFScriptDatabase_2.get_file_path(script_id)
f_name = f_name.rsplit(".", 1)[0] + "_audited.csv"
audited_csv.to_csv(
f"{f_path}{f_name}",
index=False,
)
Time = datetime.now()
ps_models.MNFScriptDatabase_2.objects.filter(script_id=str(script_id)).update(
last_edited_on=Time
)
import subprocess
from PyPDF2 import PdfFileReader
def convert_to_pdf(input_docx, out_folder):
p = subprocess.Popen(
[
"libreoffice",
"--headless",
"--convert-to",
"pdf",
"--outdir",
out_folder,
input_docx,
]
)
print(["--convert-to", "pdf", input_docx])
p.communicate()
def countPages(docfile, pdfname):
convert_to_pdf(docfile, rf"{basePath}/media/PdfFiles/")
pdf = PdfFileReader(open(rf"{basePath}/media/PdfFiles/{pdfname}", "rb"))
number_of_pages = pdf.getNumPages()
return number_of_pages
from MNF.settings import BasePath
basePath = BasePath()
def get_scriptname(script_id) -> dict:
name = ps_models.MNFScriptDatabase_2.objects.get(
script_id=str(script_id)).script_name
return name
def simple_upload(csv: DataFrame, file_name: str, user) -> str:
file = ContentFile(
csv.to_csv(index=False, path_or_buf=None),
file_name,
)
return script_upload(file, user)