Conversion_Kitchen_Code/kitchen_counter/conversion/views.py

7357 lines
337 KiB
Python
Executable File

import datetime
# import json
# import os
import random
import math
# import asyncio
# from typing import List, Any, Union
# import requests
# import calendar
import ntpath
# from users.models import UserCredentialsForBlockchain,BlockchainUserInfo
from Blockchain2.decryption import decryptionOfPrivate, decryptionOfUrl, download_file_System,viewDecryptionOfUrl,hash_decrypation
from centralisedFileSystem.models import File, Script, ScreenPlay
from Blockchain2.DataStorage import uploadDataToIPFSNode
from Blockchain2.PPTConversion import UploadPPTConversionData, getPPTConversion, getUserprojectIds, deletePPTConversion
from Blockchain2.Conversion import UploadConversionData, getConversion, deleteConversion,scriptGetUserprojectIds
from Blockchain2.block_user_info import *
from lpp.certificate.createCertificate import certificateGenrate
from lpp.models import LPPTASKDatabase
from Blockchain2.blockchainsetting import OWNER_KEY
# from mnfapp.views import base, languages as lang ## import base,lang error commented 02032023
from .translation.translation_variables import code_2_language as languages, language_2_code
import re
# from .booktranslator.newConvertBook import convert_books
# import shutil
import subprocess
import sys
import threading
import time
from datetime import date
from pathlib import Path
# from subprocess import Popen
# from threading import Thread
from auto_email.views import sendmail
import docx
import pandas as pd
# import razorpay
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.files.base import ContentFile
from django.core.files.storage import FileSystemStorage
from django.core.mail import EmailMessage, EmailMultiAlternatives, get_connection
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse, HttpResponseBadRequest
from django.shortcuts import redirect, render
from django.template.loader import render_to_string
from django.utils.html import strip_tags
# from forex_python.converter import CurrencyRates
# from googletrans import Translator
# from langdetect import detect
# from pptx import Presentation
# from pymongo import MongoClient
from PyPDF2 import PdfFileReader, PdfFileWriter
# from pytz import timezone
from django.utils import timezone as tz
# from tqdm import tqdm
# from blockchain.submitIPFS import upload_multiFile_to_ipfs, upload_to_ipfs
from conversion.ppt_translation.final_srt_ppt import translate_presentation
from conversion.translation.translation_function import all_translator
# from conversion.translation.translation_variables import (
# get_doc_file, get_language_script_code, get_pdf_save_dir,
# is_in_translation_list)
# from conversion.translation import final_translation
from conversion.translation.fourstepconversion import translate_function
from lpp.models import LPPTASKDatabase
# from .storytranslator.trans import convert_story
from lpp.views import task_assigner
# from MNF.email import mnfnsendemail
from MNF.settings import (EMAIL_HOST_USER, RAZORPAY_KEY_ID, RAZORPAY_KEY_SECRET, STRIPE_PUBLISHABLE_KEY,
STRIPE_SECRET_KEY, T_RAZORPAY_KEY_ID,
T_RAZORPAY_KEY_SECRET, BasePath, pricing_data, discount_limit_handler)
from mnfapp.models import *
from mnfapp.models import (MNFScriptDatabase, PaymentData,
SampleScript, ScriptTranslations)
# from neutralAudit.tasks import NeutralAuditTask
# from ideamall.views import sendemail
# from page_script.models import (Conversion_link, Conversions,
# MNFScriptDatabase_2)
from payment.models import conversionPayment, privilegedUser1
from users.models import *
# from users.views import deduction_for_sep_wall
from utils import filesystem
from utils.scripts_functions import (name_exists, script_id_generator,
script_upload)
# from rest_framework.response import Response
from .booktranslator2.convertBookDocx import ConvertBook
from django.views.decorators.csrf import csrf_exempt
from .forms import AScript, CScript, SScript
from .models import (BookConversion, StoryConversion, UploadScript,
pptconversion)
from .translation.detection import getInputs, language_detector, script_det
# from .translation.final_transliteration_only import makeTransliteration_only
# from .translation.script_reading import (breaksen, getRefined, getScenes,
# getSlugAndNonSlug, getSpeakers)
# from .translation.script_writing import (addActionLine, addDialogue,
# addParenthetical, addSlugLine,
# addSpeaker, addTransition,
# dial_checker, dual_script,
# non_dial_checker)
# from .translation.translation_function import (translate_comparison,
# ui_option3_and_4)
# from .translation.translation_resources import google
from centralizePayment.views import callback, create_indent, centralPayment_get_discounts, auto_refund
from juggernaut.models import JuggernautConversion, JuggernautPackage
from centralizePayment.models import CentralPayment
from mnfapp.models import centralDatabase, SampleScript
# from institutional.views import get_discount
DISCOUNT = settings.DISCOUNT
from .translation.translation_variables import language_script
from juggernaut.views import update_juggernaut, check_juggernaut
# ppt convert
from centralisedFileSystem.models import Script
from scriptAudit.models import ScriptAuditModel
from .translation.external_conversion import Conversion
BASE_DIR = Path(__file__).resolve().parent.parent
basePath = BasePath()
# This is your real test secret API key.
# stripe.api_key = "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"
# stripe.api_key = "sk_test_51JT8ahSF9vzGWnggJT1M69LDT0Q8tCqvHzuWd9Fih5YO2guIpMpUd58swbDrJYocpQZAn3nY8k3Ymyw8QZ8dLeEF00VxfBmMWI"
# stripe.api_key = STRIPE_SECRET_KEY
# STRIPE_PUB_KEY ="pk_test_51JT8ahSF9vzGWngg9ik0jueTIilHhCQomixBFOiNzCuo4Wwc5oRm73d05vdcboMgNwhyNcNTa2si8idqbB5msvwe006q3S96tM"
# STRIPE_PUB_KEY ="pk_live_51JT8ahSF9vzGWngg4N8fwhTPk5jq8fqBFdokqSMe7AVaOvH6BdyTwAfAoY79qkeJTFA0OdT5qkAk2FCNWCu6W9l000STNnHa7H"
STRIPE_PUB_KEY = STRIPE_PUBLISHABLE_KEY
# keyID = RAZORPAY_KEY_ID
# keySecret = RAZORPAY_KEY_SECRET
import cProfile
@login_required(login_url="/PersonalLogin-2")
def adding_sample_scripts(request):
if request.user.is_superuser:
samplescripts = len(SampleScript.objects.all())
scripts = json.load(open("/home/mnfidea/mnf/MNF/app/conversion/mnfapp_samplescript_latest.json"))
print(scripts)
if samplescripts > 5:
pass
else:
for script in scripts:
SampleScript.objects.create(
user_id = User.objects.get(id=request.user.id),
script_title = script['script_title'],
author_name = "MNF",
script_file_path = script["script_file_path"],
script_file_path_pdf = script["script_file_path_pdf"],
dial_src_language = script['dial_src_language'],
dial_src_script = script['dial_src_script'],
nondial_src_script = script['nondial_src_script'],
nondial_src_language = script['nondial_src_language'],
languages = script['languages'],
approved = True
)
return redirect("sampleScriptC")
class sendemail(threading.Thread):
def __init__(self, whomtosend, titleofmail, dateofemail, context, EMAIL_HOST_USER):
self.whomtosend = whomtosend
self.titleofmail = titleofmail
self.dateofemail = dateofemail
self.context = context
self.EMAIL_HOST_USER = EMAIL_HOST_USER
threading.Thread.__init__(self)
def run(self):
print("run self class", self.context)
subject = str(self.titleofmail) + " " + str(self.dateofemail) + "."
from_email = self.EMAIL_HOST_USER
to = self.whomtosend
html_content = render_to_string(
rf"{basePath}/ideamall/templates/ideamall/email_templete.html",
self.context, # /home/user/mnf/project/MNF/ideamall/templates/ideamall/email_templete.html
) # render with dynamic value
# Strip the html tag. So people can see the pure text at least.
text_content = strip_tags(html_content)
# create the email, and attach the HTML version as well.
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
def set_payment_token(request):
if request.user.is_superuser:
request.session["keyID"] = T_RAZORPAY_KEY_ID
request.session["keySecret"] = T_RAZORPAY_KEY_SECRET
else:
request.session["keyID"] = RAZORPAY_KEY_ID
request.session["keySecret"] = RAZORPAY_KEY_SECRET
# languages = {
# "hi": "Hindi",
# "en": "English",
# "ur": "Urdu",
# "ar": "Arabic",
# "bn": "Bengali",
# "kn": "Kannada",
# "ta": "Tamil",
# "bg": "Bulgarian",
# "bn": "Bengali",
# "ml": "Malayalam",
# "ru": "Russian",
# "sr": "Serbian",
# "uk": "Ukranian",
# "hr": "Croatian",
# "ga": "Irish",
# "sq": "Albanian",
# "mr": "Marathi",
# "fa": "Persian",
# "te": "Telugu",
# "tr": "Turkish",
# "hu": "Hungarian",
# "it": "Italian",
# "ro": "Romanian",
# "pa": "Punjabi",
# "gu": "Gujarati",
# "or": "Oriya",
# "zh-CN": "Chinese-Simplified",
# "zh-TW": "Chinese-Traditional",
# "ne": "Nepali",
# "fr": "French",
# "es": "Spanish",
# "id": "Indonesian",
# "el": "Greek",
# "ja": "Japanese",
# "jv": "Javanese",
# "ko": "Korean",
# "be": "Belarusian",
# "uz": "Uzbek",
# "sd": "Sindhi",
# "af": "Afrikaans",
# "de": "German",
# "is": "Icelandic",
# "ig": "Igbo",
# "la": "Latin",
# "pt": "Portugese",
# "my": "Myanmar",
# "th": "Thai",
# "su": "Sundanese",
# "lo": "Lao",
# "am": "Amharic",
# "si": "Sinhala",
# "az": "Azerbaijani",
# "kk": "Kazakh",
# "mk": "Macedonian",
# "bs": "Bosnian",
# "ps": "Pashto",
# "mg": "Malagasy",
# "ms": "Malay",
# "yo": "Yoruba",
# "cs": "Czech",
# "da": "Danish",
# "nl": "Dutch",
# "tl": "Tagalog",
# "no": "Norwegian",
# "sl": "Slovenian",
# "sv": "Swedish",
# "vi": "Vietnamese",
# "cy": "Welsh",
# "he": "Hebrew",
# "hy": "Armenian",
# "km": "Khmer",
# "ka": "Georgian",
# "mn": "Mongolian",
# "ku": "Kurdish",
# "ky": "Kyrgyz",
# "tk": "Turkmen",
# "fi": "Finnish",
# "ht": "Haitian Creole",
# "haw": "Hawaiian",
# "lt": "Lithuanian",
# "lb": "Luxembourgish",
# "mt": "Maltese",
# "pl": "Polish",
# "eo": "Esperanto",
# "tt": "Tatar",
# "ug": "Uyghur",
# "ha": "Hausa",
# "so": "Somali",
# "sw": "Swahili",
# "yi": "Yiddish",
# "eu": "Basque",
# "ca": "Catalan",
# "ceb": "Cebuano",
# "co": "Corsican",
# "et": "Estonian",
# "fy": "Frisian",
# "gl": "Galician",
# "hmn": "Hmong",
# "rw": "Kinyarwanda",
# "lv": "Latvian",
# "mi": "Maori",
# "sm": "Samoan",
# "gd": "Scots Gaelic",
# "st": "Sesotho",
# "sn": "Shona",
# "sk": "Slovak",
# "xh": "Xhosa",
# "zu": "Zulu",
# "ny": "Nyanja",
# }
def conversionSHandler(script_id="scr_1652429491"):
script_info = MNFScriptDatabase.objects.get(script_id=script_id)
numPages = script_info.numPages
total_amount = 0
context = {}
if int(numPages) > 5:
context["subtotal"] = round(float(numPages * settings.CONVERSION_PER_PAGE), 2)
return context
def conversion_script_details(script_id="scr_1652429491"):
script_info = MNFScriptDatabase.objects.get(script_id=script_id)
context = {}
context["script_title"] = script_info.script_title
context["numPages"] = script_info.numPages
context["ndial_src"] = script_info.nondial_src_language
context["dial_src"] = script_info.dial_src_language
context["ndial_dest"] = script_info.nondial_dest_language
context["dial_dest"] = script_info.dial_dest_language
context["dial_dest_script"] = script_info.dial_dest_script
return context
def conversionScriptInvoice(request, script_id="scr_1652429491"):
context = {}
script_details = conversion_script_details(script_id)
context.update(script_details)
tempt = conversionSHandler(script_id=script_id)
context.update({"subtotal":tempt["subtotal"]})
return render(request, "conversion/conversion_checkout.html", context)
# -> For Testing of Conversion
def run_testing(request):
# from conversion.translation.testing_scripts import test_run
# from conversion.translation.testing_scripts_mini import test_run
from threading import Thread
# from conversion.translation.testing_languages import test_run
# from conversion.translation.testing_languages_working_translation import test_run
# from conversion.translation.getting_languages_Scripts import test_run
# from conversion.translation.getting_languages_Codes import test_run
from conversion.translation.testing_response_times import test_run
# create a thread
thread = Thread(target=test_run)
# run the thread
thread.start()
# wait for the thread to finish
print("Waiting for the thread...")
thread.join()
test_run()
return render(request, "conversion/testing.html")
def multi_lang(request):
f = open("/home/user/mnf/project/MNF/locale/hi/LC_MESSAGES/django.po", "r")
g = open("/home/user/mnf/project/MNF/locale/hi/LC_MESSAGES/django_.po", "w")
appender = ""
for line in f:
if line[0:5] == "msgid":
if line[7:-2] != "":
output = all_translator(
line[7:-2], "en", "hi").replace(""", "\"")
g.write(line)
appender = output
else:
g.write(line)
elif line[0:6] == "msgstr":
g.write(rf'msgstr "{appender}"')
g.write("\n")
appender = ""
else:
g.write(line)
g.close()
return render(request, "conversion/testing.html")
# -> Converting Docx to PDF
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()
# -> Counting Number of Pages
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
# -> Conversion Script Storing and redirecting to Script Page
def ps_conversion(request):
if request.method == "POST":
try:
script_id = script_upload(request.FILES["script"], request.user)[
"script_id"
]
except FileExistsError:
messages.error(
request, 'Script Already Exists ! Please choose a New Script')
#messages.success(request, f"Script Already Exists ! Please choose a New Script")
return redirect("conversion")
# NeutralAuditTask().delay(script_id=script_id, user=request.user)
# NeutralAudit(script_id=script_id).audit()
return redirect("ScriptPage", script_id=script_id)
def conversion_clone(request):
print("Entered Conversion Function")
sampleList = SampleScript.objects.all()
with open(f"{basePath}/MNF/json_keys/language_pairs.json") as c:
language_pairs = json.load(c)
with open(f"{basePath}/MNF/json_keys/default_script.json") as c:
default_script = json.load(c)
with open(f"{basePath}/MNF/json_keys/script_pairs.json") as c:
script_pairs = json.load(c)
if request.method == "POST":
print("i am here 0")
# try:
print("i am here 1")
M = MNFScriptDatabase()
UScript = CScript(request.POST, request.FILES)
if UScript.is_valid():
M.script = UScript.cleaned_data.get("script")
M.user_id = request.user
M.progress = 10
M.save()
author_name = str(request.user.username)
script_title = M.script.name
numPages = countPages(
str(BASE_DIR) + "/media/" +
script_title, script_title[8:-4] + "pdf"
)
request.session["numPages"] = numPages
MyURL = "/media/" + str(script_title)
formInput = getInputs(request, str(BASE_DIR) + MyURL, M.id)
dial_src_script = formInput[2]
dial_src_lang = formInput[1]
non_dial_src_lang = formInput[0]
non_dial_src_script = formInput[3]
option3 = formInput[4]
option4 = formInput[5]
option5 = formInput[6]
option6 = formInput[7]
M.progress = 20
M.save()
M.progress = 90
M.save()
print("i am here 2")
print("The Data of formInput is:", formInput)
context = {
"id": M.id,
"numPages": numPages,
"fileName": MyURL,
"non_dial_src_script": non_dial_src_script,
"author_name": author_name,
"script_title": script_title,
"UScript": UScript,
"dial_src_script": dial_src_script,
"dial_src_lang": dial_src_lang,
"dial_src_lang_full": languages.get(dial_src_lang),
"non_dial_src_lang_full": languages.get(non_dial_src_lang),
"non_dial_src_lang": non_dial_src_lang,
"list": sampleList,
"option3": option3,
"option4": option4,
"option5": option5,
"option6": option6,
"language_pairs": language_pairs,
"default_script": default_script,
"script_pairs": script_pairs,
}
print("i am here 3")
return render(request, "conversion/conversion_copy.html", context)
# except Exception as e:
# print("i am here 4")
# print("Error:", e)
# messages.warning(request, "The format of file is wrong")
# return redirect("conversion_clone")
# print("i am here 5")
return render(
request,
"conversion/conversion_clone.html",
{
"list": sampleList,
"language_pairs": language_pairs,
"default_script": default_script,
"script_pairs": script_pairs,
},
)
# -> Initital Saving of Script in database and extracting various languages present in that
@login_required(login_url="/PersonalLogin-2")
def conversion(request):
if request.method == "GET":
# from utils.utilities import fdx_to_txt
print("Entered Conversion Function")
existingscripts = MNFScriptDatabase.objects.filter(user_id=request.user.id).order_by("-date_at").values_list('script_id', 'script_title')
sampleList = SampleScript.objects.all()
with open(f"{basePath}/MNF/json_keys/language_pairs.json") as c:
language_pairs = json.load(c)
with open(f"{basePath}/MNF/json_keys/script_pairs.json") as c:
script_pairs = json.load(c)
return render(
request,
"conversion/conversion.html",
{
"list": sampleList,
"language_pairs": language_pairs,
"default_script": language_script,
"script_pairs": script_pairs,
"exsiting_scripts": existingscripts,
},
)
elif request.method == "POST":
original_stdout = sys.stdout
start_time = time.time()
# try:
M = MNFScriptDatabase()
UScript = CScript(request.POST, request.FILES)
if UScript.is_valid():
M.script = UScript.cleaned_data.get("script")
M.user_id = request.user
M.progress = 10
M.save()
author_name = str(request.user.username)
script_title = M.script.name
MyURL = "/media/" + str(script_title)
print("Here are data points ->", str(BASE_DIR) + MyURL, M.id)
formInput = getInputs(request, str(BASE_DIR) + MyURL, M.id)
sys.stdout = original_stdout
dial_src_script = formInput[2]
dial_src_lang = formInput[1]
non_dial_src_lang = formInput[0]
non_dial_src_script = formInput[3]
option3 = formInput[4]
option4 = formInput[5]
option5 = formInput[6]
option6 = formInput[7]
numPages = formInput[8]
request.session["numPages"] = numPages
M.progress = 20
M.option3 = option3
M.option4 = option4
M.option5 = option5
M.option6 = option6
M.save()
print("numpages", numPages)
# if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
# blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user)
# certificatepath = certificateGenrate(request.user.username,"original script",hash)
# hash = uploadDataToIPFSNode(UScript.cleaned_data.get("script"))
# userkey = decryptionOfPrivate(blockchain_obj.privateKey)
# to_email = [request.user.email]
# email_code = 'BL1'
# key_value = {
# "service":"original script",
# "hash": hash,
# "public key":blockchain_obj.publicKey,
# "private key":userkey.decode('utf-8'),
# }
# sendmail(to_email=to_email , email_code=email_code,key_value=key_value,filePath=certificatepath)
M.progress = 90
M.save()
print("The Data of formInput is:", formInput)
context = {
"id": M.id,
"numPages": numPages,
"fileName": MyURL,
"non_dial_src_script": non_dial_src_script,
"author_name": author_name,
"script_title": (((str(script_title).split("/"))[-1]).split("."))[0],
"UScript": UScript,
"dial_src_script": dial_src_script,
"dial_src_lang": dial_src_lang,
"dial_src_lang_full": languages.get(dial_src_lang),
"non_dial_src_lang_full": languages.get(non_dial_src_lang),
"non_dial_src_lang": non_dial_src_lang,
# "list": sampleList,
"option3": option3,
"option4": option4,
"option5": option5,
"option6": option6,
# "language_pairs": language_pairs,
"default_script": language_script,
# "script_pairs": script_pairs,
# "exsiting_scripts": existingscripts,
}
print("i am here 3")
# sys.stdout = original_stdout
print("Time Taken For Input Processing is ->", time.time() - start_time)
return render(request, "conversion/conversion.html", context)
# except Exception as e:
# print("Error:",e)
# print("i am here 4")
# messages.warning(request, "The format of file is wrong")
# return redirect("conversion")
@login_required(login_url="/PersonalLogin-2")
def conversion2(request):
from django.utils import timezone
if request.method == "GET":
print("Entered Conversion Function")
existingscripts2 = MNFScriptDatabase.objects.filter(user_id=request.user.id).order_by("-date_at")
for script in existingscripts2:
elapsed_time = (timezone.now() - script.date_at).total_seconds()
# 15min
if int(elapsed_time) > 900 and len(str(script.script_title)) == 0:
print("Script Deleted becuase 15 Mins has passed ->", script.script.name)
script.delete()
existingscripts = MNFScriptDatabase.objects.filter(user_id=request.user.id).order_by("-date_at").values_list('script_id', 'script_title')
# existingscripts = existingscripts2
sampleList = SampleScript.objects.all()
with open(f"{basePath}/MNF/json_keys/language_pairs.json") as c:
language_pairs = json.load(c)
with open(f"{basePath}/MNF/json_keys/script_pairs.json") as c:
script_pairs = json.load(c)
return render(
request,
"conversion2/conversion_new.html",
{
"list": sampleList,
"language_pairs": language_pairs,
"default_script": language_script,
"script_pairs": script_pairs,
"exsiting_scripts": existingscripts,
},
)
elif request.method == "POST":
original_stdout = sys.stdout
try:
M = MNFScriptDatabase()
UScript = CScript(request.POST, request.FILES)
if UScript.is_valid():
M.script = UScript.cleaned_data.get("script")
M.user_id = request.user
M.save()
author_name = str(request.user.username)
script_title = M.script.name
MyURL = "/media/" + str(script_title)
print("Here are data points ->", str(BASE_DIR) + MyURL, M.id)
formInput = getInputs(request, str(BASE_DIR) + MyURL, M.id)
sys.stdout = original_stdout
dial_src_script = formInput[2]
dial_src_lang = formInput[1]
non_dial_src_lang = formInput[0]
non_dial_src_script = formInput[3]
numPages = formInput[8]
request.session["numPages"] = numPages
M.save()
print("numpages", numPages)
M.save()
print("The Data of formInput is:", formInput)
context = {
"id": M.id,
"numPages": numPages,
"author_name": author_name,
"script_title": ((M.script.name.split("/"))[-1].split("."))[0],
"dial_src_script": dial_src_script,
"dial_src_lang_full": languages.get(dial_src_lang),
"non_dial_src_script": non_dial_src_script,
"non_dial_src_lang_full": languages.get(non_dial_src_lang),
}
print("i am here 3")
# sys.stdout = original_stdout
return render(request, "conversion2/conversion_processing.html", context)
except Exception as e:
print("Error:",e)
print("i am here 4")
messages.warning(request, "The format of file is wrong")
return redirect("conversion")
def tp(request):
context = {
"id": "0461b9d5-fe04-48cf-b07f-bea23d08de6d",
"numPages": 10,
"fileName": "MyURL",
"non_dial_src_script": "Latin",
"author_name": "author_name",
"script_title": "12",
"UScript": "UScript",
"dial_src_script": "Latin",
"dial_src_lang": "Hindi",
"dial_src_lang_full": "Hindi",
"non_dial_src_lang_full": "English",
"non_dial_src_lang": "English",
# "list": sampleList,
"option3": "option3",
"option4": "option4",
"option5": "option5",
"option6": "option6",
# "language_pairs": language_pairs,
"default_script": language_script,
# "script_pairs": script_pairs,
# "exsiting_scripts": existingscripts,
}
print("i am here 3")
# sys.stdout = original_stdout
# print("Time Taken For Input Processing is ->", time.time() - start_time)
return render(request, "conversion2/conversion_processing.html", context)
def logger_wrapper(func):
def _wrapper(request, *args, **kwargs):
original_stdout = sys.stdout
f = open("/home/mnfidea/project/MNF/conversion/translation/script_translation_log.txt","w")
sys.stdout = f
func(request)
f.close()
sys.stdout = original_stdout
return _wrapper
def background_execution(obj):
obj.convert()
@login_required(login_url="/PersonalLogin-2")
def start_conversion(request):
from .translation.newconversion import ScriptTranslation
from scriptAudit.mnf_script_audit import NeutralAudit
from scriptAudit.models import States
if request.method == "POST":
print("Conversion Process Started")
original_stdout = sys.stdout
"""Initializing Variables"""
script_id = request.session["script_id"]
original_script = MNFScriptDatabase.objects.get(script_id=script_id)
translated_script = ScriptTranslations.objects.get(translation_id=request.session.get("translation_id", None))
conversion_params = {
"user": translated_script.user_id,
"file_path": str(basePath) + "/media/" + translated_script.script_link_id.script.name,
"original_script_object": translated_script.script_link_id,
"translated_script_object": translated_script,
"sample_id": request.session.get('sample_id', None),
"existing_script": request.session.get('sample_id', None),
"iteration_no": request.session.get('iteration_no', None),
"juggernaut_pages_deduction": request.session.get("juggernaut_pages_deduction", None),
"language_set": request.session.get("language_set", None),
"amount_without_subscrption": request.session.get("amount_without_subscrption", None)
}
obj = Conversion(**conversion_params)
background_thread = threading.Thread(target=background_execution, args=(obj,))
background_thread.start()
# obj.convert()
keys_to_delete = []
for key, value in request.session.items():
if key not in ['_auth_user_id', '_auth_user_backend', '_auth_user_hash', '_session_init_timestamp_']:
keys_to_delete.append(key)
print("Keys to be deleted is ->", keys_to_delete)
for key in keys_to_delete:
del request.session[key]
return JsonResponse({"status": "Process Started"}, status=200)
# Getting all choices of user regarding Full Dialogues Translation
full_dialogue_option_choices = [True if value.strip() == "True" else False for value in
str(translated_script.full_dialogue_option_choices).split(",")]
# Getting all choices of user regarding Words of Dialogues Translation
sentence_dialogue_option_choices = [True if value.strip() == "True" else False for value in
str(translated_script.sentence_dialogue_option_choices).split(",")]
# Getting all choices of user regarding translation and transliteration choices of slug, speaker, etc.
other_option_choices = [True if value.strip() == "True" else False for value in
str(translated_script.other_option_choices).split(",")]
# Dual dialogue
# if dual_dialogue_option := request.POST.get('dual_dialogue_option') == "on":
# dual_left_language = request.POST.get('dual_left_language')
# dual_left_script = request.POST.get('dual_left_script')
# # lpp vetting
# if lpp_vetting := request.POST.get('lpp_vetting') == "on":
# lpp_vetting_type = request.POST.get('radioGroup')
# if lpp_vetting_type == "radioOption1":
# pass
# elif lpp_vetting_type == "radioOption1":
# pass
# - Audit Code
"""Audit Code starts here"""
print("Conversion Auditing is starting")
# x = MNFScriptDatabase.objects.get(script_id=request.POST['script_id'])
scripttt = basePath + "/media/" + original_script.script.name
exten = (str(original_script.script.name).split("."))[-1]
name_script = str(((((scripttt).split("/"))[-1]).split("."))[0])
print("name of script", name_script)
print("sample script", request.POST.get("sample_id"))
print("existing_script", request.session.get("existing_script"))
"""if file is not a sample script and not a existing script then only audit it"""
if not request.session.get('existing_script') and not original_script.sample_script:
print("----Auditing----")
script1 = str(scripttt)
doc = open(script1, 'rb').read()
file = ContentFile(
doc,
(script1.split("/"))[-1],
)
language_code = "en"
result = filesystem.new_screenplay_without_audit_in_background(
request.user,
request.user.username,
str(name_script),
file,
"script-original",
language_code,
)
audit_id = result.get("script", {}).get("id")
ScriptAuditModel.objects.update_or_create(
script=Script.objects.get(
id=audit_id
),
defaults={"status": States.STARTED}
)
audit = NeutralAudit(audit_id, False)
status = ScriptAuditModel.objects.get(
script=Script.objects.get(
id=audit_id
)
)
try:
if exten == "fdx":
audit.audit_fdx()
else:
audit.audit()
status.status = "SUCCESS"
status.save()
to_email = [request.user.email]
email_code = 'SB1'
sendmail(to_email=to_email, email_code=email_code)
except Exception as e:
print("Error of Audit is:", e)
status.status = "FAILURE"
status.save()
to_email = [request.user.email]
email_code = 'SB2'
sendmail(to_email=to_email, email_code=email_code)
print(
"Script Audit failed due to some internal error."
" If you have made any payment for conversion "
"that will be refunded")
# email for failure
to = request.user.email
key_value = {
"User": request.user.username,
}
sendmail(to_email=[to], email_code="PP21", key_value=key_value)
# auto refund code
try:
auto_refund(ScriptTranslations.objects.get(
translation_id=request.session.get('translation_id', None)).central_payment_id)
except Exception as e:
print("No Refund -> ",e)
return JsonResponse({}, status=505)
file_path_ = filesystem.get_file_path(audit_id, "script-csv")
script_data = MNFScriptDatabase.objects.get(script_id=script_id)
script_data.audit_id = str(audit_id)
script_data.save()
to_email = [request.user.email]
email_code = 'SB1'
sendmail(to_email=to_email, email_code=email_code)
try:
df = pd.read_csv(file_path_, encoding="utf-8")
except UnicodeError:
df = pd.read_csv(file_path_, encoding="utf-16")
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
list_of_lists = df.values.tolist()
print("Audit Done")
elif original_script.sample_script:
sample_script = SampleScript.objects.get(sample_id=original_script.sample_id.sample_id)
if sample_script.audit_id:
audit_id = sample_script.audit_id
file_path_ = filesystem.get_file_path(audit_id, "script-csv")
try:
df = pd.read_csv(file_path_, encoding="utf-8")
except UnicodeError:
df = pd.read_csv(file_path_, encoding="utf-16")
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
list_of_lists = df.values.tolist()
else:
print("----Auditing----")
script1 = str(scripttt)
doc = open(script1, 'rb').read()
file = ContentFile(
doc,
(script1.split("/"))[-1],
)
language_code = "en"
result = filesystem.new_screenplay_without_audit_in_background(
request.user,
request.user.username,
str(name_script),
file,
"script-original",
language_code,
)
audit_id = result.get("script", {}).get("id")
ScriptAuditModel.objects.update_or_create(
script=Script.objects.get(
id=audit_id
),
defaults={"status": States.STARTED}
)
audit = NeutralAudit(audit_id, False)
status = ScriptAuditModel.objects.get(
script=Script.objects.get(
id=audit_id
)
)
try:
if exten == "fdx":
audit.audit_fdx()
else:
audit.audit()
status.status = "SUCCESS"
status.save()
to_email = [request.user.email]
email_code = 'SB1'
sendmail(to_email=to_email, email_code=email_code)
except:
status.status = "FAILURE"
status.save()
to_email = [request.user.email]
email_code = 'SB2'
sendmail(to_email=to_email, email_code=email_code)
print(
"Script Audit failed due to some internal error."
" If you have made any payment for conversion "
"that will be refunded")
# email for failure
to = request.user.email
key_value = {
"User": request.user.username,
}
sendmail(to_email=[to], email_code="PP21", key_value=key_value)
# auto refund code
try:
auto_refund(ScriptTranslations.objects.get(
translation_id=request.session.get('translation_id', None)).central_payment_id)
except Exception as e:
print("No Refund -> ",e)
return JsonResponse({}, status=505)
file_path_ = filesystem.get_file_path(
audit_id, "script-csv")
sample_script.audit_id = str(audit_id)
sample_script.save()
try:
df = pd.read_csv(file_path_, encoding="utf-8")
except UnicodeError:
df = pd.read_csv(file_path_, encoding="utf-16")
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
dataframe = df
list_of_lists = dataframe.values.tolist()
elif request.session.get('existing_script'):
if MNFScriptDatabase.objects.get(script_id=script_id).audit_id:
audit_id = MNFScriptDatabase.objects.get(script_id=script_id).audit_id
file_path_ = filesystem.get_file_path(audit_id, "script-csv")
try:
df = pd.read_csv(file_path_, encoding="utf-8")
except UnicodeError:
df = pd.read_csv(file_path_, encoding="utf-16")
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
dataframe = df
list_of_lists = dataframe.values.tolist()
else:
print("----Auditing----")
script1 = str(scripttt)
doc = open(script1, 'rb').read()
file = ContentFile(
doc,
(script1.split("/"))[-1],
)
language_code = "en"
result = filesystem.new_screenplay_without_audit_in_background(
request.user,
request.user.username,
str(name_script),
file,
"script-original",
language_code,
)
audit_id = result.get("script", {}).get("id")
ScriptAuditModel.objects.update_or_create(
script=Script.objects.get(
id=audit_id
),
defaults={"status": States.STARTED}
)
audit = NeutralAudit(audit_id, False)
status = ScriptAuditModel.objects.get(
script=Script.objects.get(
id=audit_id
)
)
try:
if exten == "fdx":
audit.audit_fdx()
else:
audit.audit()
status.status = "SUCCESS"
status.save()
to_email = [request.user.email]
email_code = 'SB1'
sendmail(to_email=to_email, email_code=email_code)
except:
status.status = "FAILURE"
status.save()
to_email = [request.user.email]
email_code = 'SB2'
sendmail(to_email=to_email, email_code=email_code)
print(
"Script Audit failed due to some internal error."
" If you have made any payment for conversion "
"that will be refunded")
# email for failure
to = request.user.email
key_value = {
"User": request.user.username,
}
sendmail(to_email=[to], email_code="PP21", key_value=key_value)
# auto refund code
try:
auto_refund(ScriptTranslations.objects.get(
translation_id=request.session.get('translation_id', None)).central_payment_id)
except Exception as e:
print("No Refund -> ", e)
return JsonResponse({}, status=505)
file_path_ = filesystem.get_file_path(
audit_id, "script-csv")
script_data = MNFScriptDatabase.objects.get(script_id=script_id)
script_data.audit_id = str(audit_id)
script_data.save()
to_email = [request.user.email]
email_code = 'SB1'
sendmail(to_email=to_email, email_code=email_code)
try:
df = pd.read_csv(file_path_, encoding="utf-8")
except UnicodeError:
df = pd.read_csv(file_path_, encoding="utf-16")
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
dataframe = df
list_of_lists = dataframe.values.tolist()
sys.stdout = original_stdout
print("Audit Done")
translated_script.status = "Audited"
translated_script.save()
"""Translation Code Starts here"""
print("list of lists -> ", list_of_lists)
dataframe = list_of_lists
args = [full_dialogue_option_choices, sentence_dialogue_option_choices, other_option_choices]
kwargs = {
'dataframe': dataframe,
"non_dial_src_lang": original_script.nondial_src_language,
"non_dial_src_script": original_script.nondial_src_script,
"non_dial_dest_lang": translated_script.nondial_dest_language,
"non_dial_dest_script": translated_script.nondial_dest_script,
"dial_src_lang": original_script.dial_src_language,
"dial_src_script": original_script.dial_src_script,
"dial_dest_lang": translated_script.dial_dest_language,
"dial_dest_script": translated_script.dial_dest_script,
"translation_id": translated_script.translation_id,
"script_id": original_script.script_id
}
original_stdout = sys.stdout
try:
ScriptTranslation(request, *args, **kwargs)
except Exception as e:
translated_script.status = "Failed"
translated_script.error_desc = str(e)
translated_script.save()
print("Error in Conversion is:", e)
print("Script translation failed due to some code error. If you have made any payment for conversion"
" that will be refunded")
# email for failure
to = request.user.email
key_value = {
"User": request.user.username,
}
sendmail(to_email=[to], email_code="PP21", key_value=key_value)
# auto refund code
try:
auto_refund(ScriptTranslations.objects.get(
translation_id=request.session.get('translation_id', None)).central_payment_id)
except Exception as e:
print("No Refund due to error", e)
return JsonResponse({}, status=505)
"""Translation Code Ends Here"""
sys.stdout = original_stdout
"""Juggernaut Payment Updation"""
# sys.stdout = original_stdout
if request.session.get("juggernaut_pages_deduction"):
# script_translated = ScriptTranslations.objects.get(
# translation_id=request.session.get('translation_id', None))
update_juggernaut(request, user_id=request.user.id, service_name="conversion",
conversion_pages=request.session['juggernaut_pages_deduction'],
associated_project=original_script,
translation_language=request.session['language_set'])
original_script.is_juggernaut_used = True
# if script_original.languages_juggernaut != "":
# # script_original.languages_juggernaut = str(script_original.languages_juggernaut) + "," + str(
# # script_translated.dial_dest_language)
# else:
# script_original.languages_juggernaut = str(script_translated.dial_dest_language)
original_script.save()
"""Juggernaut Payment Updation Done"""
"""Blockchain Upload Starts here"""
# sys.stdout = original_stdout
scriptconversion = {}
try:
print("trying blockchain 1")
current_datetime = datetime.datetime.now()
if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
obj = ScriptTranslations.objects.get(translation_id=request.session.get('translation_id', None))
obj2 = MNFScriptDatabase.objects.get(script_id=script_id)
temp1 = str(obj2.script)
temp2 = str(obj.translated_script_path)
uploaded_script = f"{basePath}/media/{temp1}"
translated_scripttt = f"{basePath}{temp2}"
print("blockchain script conversion 3")
with open(uploaded_script, 'rb') as f:
hash = uploadDataToIPFSNode(f)
scriptconversion["original_scriptFile_hash"] = hash
scriptconversion["original_scriptFile_path"] = uploaded_script
scriptconversion["date_at"] = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print("blockchain script conversion 4")
with open(translated_scripttt, 'rb') as f1:
hash = uploadDataToIPFSNode(f1)
scriptconversion["translated_scriptFile_hash"] = hash
scriptconversion["translated_scriptFile_path"] = translated_scripttt
print("blockchain script conversion 5")
blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user)
UserId = blockchain_obj.user_id
Project = request.session.get('translation_id', None)
Data = str(scriptconversion)
userPrivateKey = blockchain_obj.privateKey
userkey = decryptionOfPrivate(userPrivateKey)
tx_id,tx_gas_fee= UploadConversionData(OWNER_KEY, blockchain_obj.publicKey, UserId, str(Project), Data)
print("Tx id -> ", tx_id)
# user_infos = user_info(tx_hash=tx_id, service="Conversion", gas_fee=2345432345123456)
# addition_result = user_infos.update_info(request)
try:
user_infos = user_info(tx_hash=tx_id, service="Conversion", gas_fee=tx_gas_fee)
addition_result = user_infos.update_info(request)
except Exception as e:
print("Error:",e)
print("blockchain script conversion 6")
certificatepath = certificateGenrate(request.user.username, "script conversion", hash)
hash = hash_decrypation(hash)
to_email = [request.user.email]
email_code = 'BL1'
key_value = {
"service": "script conversion",
"hash": hash,
"public key": blockchain_obj.publicKey,
"private key": userkey.decode('utf-8'),
"Transaction Hash": tx_id
}
sendmail(to_email=to_email, email_code=email_code, key_value=key_value, filePath=certificatepath)
except Exception as e:
print("Error in blockchain is", e)
"""Blockchain Upload Ends here"""
"""Translation Completion mail here"""
if not translated_script.lpp:
to = request.user.email
key_value = {
"User": request.user.username,
"title": original_script.script_title
}
sendmail(to_email=[to], email_code="PP18", key_value=key_value)
"""Translation Completion mail done"""
"""Vetting Process if Choosen"""
# sys.stdout = original_stdout
if translated_script.lpp:
# obj = ScriptTranslations.objects.get(translation_id=request.session.get('translation_id', None))
# obj.lpp = True
# obj.save()
X = LPPTASKDatabase()
X.user_id = translated_script.user_id
X.usernote = "Kindly check if the translated file is correct as per the Uploaded Document!"
X.translated_script = translated_script
X.generated_from = "conversion"
temp_amount = request.session["amount_without_subscrption"]
X.amoutgiventolpp_action = round((temp_amount / 2), 2)
X.amoutgiventolpp_dialogue = round((temp_amount / 2), 2)
X.save()
task_assigner(int(X.task_id), "conversion")
"""Vetting Process Done"""
translated_script = ScriptTranslations.objects.get(translation_id=request.session.get("translation_id", None))
translated_script.status = "Completed"
translated_script.save()
keys_to_delete = []
for key, value in request.session.items():
if key not in ['_auth_user_id', '_auth_user_backend', '_auth_user_hash', '_session_init_timestamp_']:
keys_to_delete.append(key)
print("Keys to be deleted is ->", keys_to_delete)
for key in keys_to_delete:
del request.session[key]
return JsonResponse({}, status=200)
# def is_processing_complete(request):
# # script_id = request.GET["script_id"]
# obj = MNFScriptDatabase.objects.filter(user_id=request.user.id).last()
# print("Processing Chal Rahi hai", obj.progress)
# if obj.progress == 100:
# return JsonResponse({"status": "success"}, status=200)
# else:
# return JsonResponse({"status": "pending", "progress": obj.progress}, status=202)
#
#
# # -> At 10sec intervals check if conversion completed
# def is_converted(request):
# script_id = request.GET["script_id"]
# if request.GET["centralised"] == "yes":
# z = Conversion_link.objects.get(
# script_name=MNFScriptDatabase_2.objects.get(script_id=script_id)
# )
# objs = z.conversions.all()
# for indx, obji in enumerate(objs):
# if indx == len(objs) - 1:
# obj = obji
# else:
# pass
# else:
# obj = MNFScriptDatabase.objects.get(script_id=script_id)
# print("obj.script convetred function", obj.translated_script_path)
# if not obj.translated_script_path:
# return JsonResponse({"status": "pending"}, status=202)
# else:
# return JsonResponse({"status": "success"}, status=200)
# def audit_checking(request):
# orignal_stdoout = sys.stdout
# now = datetime.datetime.now()
# current_time = now.strftime("%H:%M:%S")
# print("Time is ->", current_time)
#
# # with open(rf"{basePath}/conversion/translation/file_lines.txt", 'r') as file:
# # lines = file.readlines()
# name_script = f"data_{current_time}"
# script1 = rf"/home/user/mnf/project/MNF/media/scripts/fddfd_testing_112_7fEG7oq.docx"
# print("Here it is")
# doc = open(script1, 'rb').read()
# file = ContentFile(
# doc,
# (script1.split("/"))[-1],
# )
# language_code = "en"
# result = filesystem.new_screenplay(
# request.user,
# request.user.username,
# str(name_script),
# file,
# "script-original",
# language_code,
# )
# sys.stdout =orignal_stdoout
# audit_id = result.get("script", {}).get("id")
# while True:
# try:
# status = ScriptAuditModel.objects.get(
# script=Script.objects.get(id=audit_id)).status
# if status == "SUCCESS":
# to_email = [request.user.email]
# email_code = 'SB1'
# sendmail(to_email=to_email, email_code=email_code)
# break
# elif status == "FAILURE":
# to_email = [request.user.email]
# email_code = 'SB2'
# sendmail(to_email=to_email, email_code=email_code)
# print(
# "Script Audit failed due to some internal error."
# " If you have made any payment for conversion "
# "that will be refunded")
# # email for failure
# to = request.user.email
# key_value = {
# "User": request.user.username,
# }
# sendmail(to_email=[to], email_code="PP21", key_value=key_value)
# return JsonResponse({}, status=505)
# elif status == "STARTED" or status == "PENDING":
# pass
# except:
# pass
# time.sleep(1)
# file_path_ = filesystem.get_file_path(audit_id, "script-csv")
# # script_data = MNFScriptDatabase.objects.get(script_id=script_id)
# # script_data.audit_id = str(audit_id)
# # script_data.save()
# try:
# df = pd.read_csv(file_path_, encoding="utf-8")
# except UnicodeError:
# df = pd.read_csv(file_path_, encoding="utf-16")
# pd.set_option('display.max_rows', None)
# pd.set_option('display.max_columns', None)
# dataframe = df
# list_of_lists = " ".join(dataframe.values.tolist())
# # for list in list_of_lists:
# # final_list.append()
# return JsonResponse({"Data": json.loads(list_of_lists)})
# async def audit_func(request, script_file_path, script_id, list_of_lists):
#
#
#
#
# return audit_id
# return [list_of_lists, [audit_id]]
# -> Actually Running Translation and Transliteration of script
def make_conversion(request):
from django.db import transaction
for key,value in request.session.items():
print(f"{key} => {value}")
# original_stdout = sys.stdout
# Your view logic here
if request.method == "POST":
original_stdout = sys.stdout
# start_time = time.time()
# f = open(f"/home/user/mnf/project/MNF/log/debugconversion_{(((str(request.POST.get('script_file_path')).split('/'))[-1]).split('.'))[0]}.txt", "w")
# sys.stdout = f
print("Conversion Process Started")
# now = datetime.datetime.now()
# current_time = now.strftime("%H:%M:%S")
# print(current_time)
"""Initializing Variables"""
script_file_path = request.POST.get("script_file_path")
request_id = request.POST.get("request_id")
str1 = str(script_file_path)
if str1[41:45] == "user":
script_file_path = "/home/" + str(str1[41:])
script_id = request.POST.get("script_id")
dial_conv_script = request.POST.get("dial_conv_script")
dial_src_lang = request.POST.get("dial_src_lang")
non_dial_src_lang = request.POST.get("non_dial_src_lang")
dial_src_script = request.POST.get("dial_src_script")
restrict_to_five = request.POST.get("restrict_to_five")
option3 = request.POST.get("option3")
option4 = request.POST.get("option4")
option5 = request.POST.get("option5")
option6 = request.POST.get("option6")
# -> Saving options 3,4,5,6
script_data = MNFScriptDatabase.objects.get(script_id = script_id)
# script_data.option3 = option3
# script_data.option4 = option4
# script_data.option5 = option5
# script_data.option6 = option6
# script_data.save()
"""Audit Code starts here"""
print("Conversion Auditing is starting")
scripttt = script_file_path
name_script = str(((((scripttt).split("/"))[-1]).split("."))[0])
print("name of script", name_script)
print("sample script", request.POST.get("sample_id"))
print("existing_script", request.session.get("existing_script"))
"""if file is not a sample script and not a existing script then only audit it"""
if not request.session.get('existing_script') and not request.POST["sample_id"]:
print("----Auditing----")
script1 = str(scripttt)
doc = open(script1, 'rb').read()
file = ContentFile(
doc,
(script1.split("/"))[-1],
)
language_code = "en"
result = filesystem.new_screenplay(
request.user,
request.user.username,
str(name_script),
file,
"script-original",
language_code,
)
sys.stdout = original_stdout
print("Out of Audit Function")
audit_id = result.get("script", {}).get("id")
while True:
try:
with transaction.atomic():
status = ScriptAuditModel.objects.get(
script=Script.objects.get(id=audit_id)).status
if status == "SUCCESS":
to_email = [request.user.email]
email_code = 'SB1'
sendmail(to_email=to_email, email_code=email_code)
break
elif status == "FAILURE":
to_email = [request.user.email]
email_code = 'SB2'
sendmail(to_email=to_email, email_code=email_code)
print(
"Script Audit failed due to some internal error."
" If you have made any payment for conversion "
"that will be refunded")
# email for failure
to = request.user.email
key_value = {
"User": request.user.username,
}
sendmail(to_email=[to], email_code="PP21", key_value=key_value)
# auto refund code
auto_refund(ScriptTranslations.objects.get(
translation_id=request.session.get('translation_id', None)).central_payment_id)
return JsonResponse({}, status=505)
elif status == "STARTED" or status == "PENDING":
pass
except:
pass
time.sleep(1)
file_path_ = filesystem.get_file_path(audit_id, "script-csv")
script_data = MNFScriptDatabase.objects.get(script_id=script_id)
script_data.audit_id = str(audit_id)
script_data.save()
try:
df = pd.read_csv(file_path_, encoding="utf-8")
except UnicodeError:
df = pd.read_csv(file_path_, encoding="utf-16")
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
dataframe = df
list_of_lists = dataframe.values.tolist()
print("Audit Done")
elif request.POST.get("sample_id"):
sample_script = SampleScript.objects.get(sample_id=request.GET["sample_id"])
if sample_script.audit_id:
audit_id = sample_script.audit_id
file_path_ = filesystem.get_file_path(sample_script.audit_id, "script-csv")
try:
df = pd.read_csv(file_path_, encoding="utf-8")
except UnicodeError:
df = pd.read_csv(file_path_, encoding="utf-16")
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
# sys.stdout = original_stdout
dataframe = df
list_of_lists = dataframe.values.tolist()
else:
print("----Auditing----")
script1 = str(scripttt)
doc = open(script1, 'rb').read()
file = ContentFile(
doc,
(script1.split("/"))[-1],
)
language_code = "en"
result = filesystem.new_screenplay(
request.user,
request.user.username,
str(name_script),
file,
"script-original",
language_code,
)
audit_id = result.get("script", {}).get("id")
while True:
try:
status = ScriptAuditModel.objects.get(
script=Script.objects.get(id=audit_id)).status
if status == "SUCCESS":
to_email = [request.user.email]
email_code = 'SB1'
sendmail(to_email=to_email, email_code=email_code)
break
elif status == "FAILURE":
to_email = [request.user.email]
email_code = 'SB2'
sendmail(to_email=to_email, email_code=email_code)
# email for failure
to = request.user.email
key_value = {
"User": request.user.username,
}
sendmail(to_email=[to], email_code="PP21", key_value=key_value)
# auto refund code
auto_refund(ScriptTranslations.objects.get(
translation_id=request.session.get('translation_id', None)).central_payment_id)
return JsonResponse({}, status=505)
elif status == "STARTED" or status == "PENDING":
pass
except:
pass
time.sleep(1)
file_path_ = filesystem.get_file_path(
audit_id, "script-csv")
sample_script.audit_id = str(audit_id)
sample_script.save()
try:
df = pd.read_csv(file_path_, encoding="utf-8")
except UnicodeError:
df = pd.read_csv(file_path_, encoding="utf-16")
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
dataframe = df
list_of_lists = dataframe.values.tolist()
elif request.session.get('existing_script'):
if MNFScriptDatabase.objects.get(script_id=script_id).audit_id:
audit_id = MNFScriptDatabase.objects.get(script_id=script_id).audit_id
file_path_ = filesystem.get_file_path(audit_id, "script-csv")
try:
df = pd.read_csv(file_path_, encoding="utf-8")
except UnicodeError:
df = pd.read_csv(file_path_, encoding="utf-16")
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
dataframe = df
list_of_lists = dataframe.values.tolist()
else:
print("----Auditing----")
script1 = str(scripttt)
doc = open(script1, 'rb').read()
file = ContentFile(
doc,
(script1.split("/"))[-1],
)
language_code = "en"
result = filesystem.new_screenplay(
request.user,
request.user.username,
str(name_script),
file,
"script-original",
language_code,
)
audit_id = result.get("script", {}).get("id")
while True:
try:
status = ScriptAuditModel.objects.get(
script=Script.objects.get(id=audit_id)).status
if status == "SUCCESS":
to_email = [request.user.email]
email_code = 'SB1'
sendmail(to_email=to_email, email_code=email_code)
break
elif status == "FAILURE":
to_email = [request.user.email]
email_code = 'SB2'
sendmail(to_email=to_email, email_code=email_code)
# email for failure
to = request.user.email
key_value = {
"User": request.user.username,
}
sendmail(to_email=[to], email_code="PP21", key_value=key_value)
# auto refund code
auto_refund(ScriptTranslations.objects.get(
translation_id=request.session.get('translation_id', None)).central_payment_id)
return JsonResponse({}, status=505)
elif status == "STARTED" or status == "PENDING":
pass
except:
pass
time.sleep(1)
file_path_ = filesystem.get_file_path(
audit_id, "script-csv")
script_data = MNFScriptDatabase.objects.get(script_id=script_id)
script_data.audit_id = str(audit_id)
script_data.save()
try:
df = pd.read_csv(file_path_, encoding="utf-8")
except UnicodeError:
df = pd.read_csv(file_path_, encoding="utf-16")
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
dataframe = df
list_of_lists = dataframe.values.tolist()
print("Audit Done")
"""Translation Code Starts Here"""
sys.stdout = original_stdout
print("Conversion Translation is Starting")
# - Convert Process Start Mail
to = request.user.email
key_value = {"User": request.user.username}
sendmail(to_email=[to], email_code="PP17", key_value=key_value)
# subject = "All Good Email test1"
# from_email = settings.EMAIL_HOST_USER
# to = request.user.email
# context_2 = {
# "Name": request.user.email,
# "service_name": "Conversion",
# }
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR24.html", context_2, from_email)
try:
translate_function(
request,
audit_id,
list_of_lists,
script_file_path,
script_id,
request.session.get('translation_id', None),
dial_src_lang,
non_dial_src_lang,
dial_src_script,
restrict_to_five,
option3,
option4,
option5,
option6,
request.POST.get("centralised"),
request.POST.get("sample_id"),
request.POST.get("sample_title"),
request.session.get('existing_script', None)
)
except Exception as e:
print("Error in Conversion is:", e)
print("Script translation failed due to some code error. If you have made any payment for conversion"
" that will be refunded")
# email for failure
to = request.user.email
key_value = {
"User": request.user.username,
}
sendmail(to_email=[to], email_code="PP21", key_value=key_value)
# auto refund code
auto_refund(ScriptTranslations.objects.get(
translation_id=request.session.get('translation_id', None)).central_payment_id)
# f.close()
return JsonResponse({}, status=505)
"""Translation Code Ends Here"""
"""Juggernaut Payment Updation"""
# sys.stdout = original_stdout
if request.session.get("juggernaut_pages_deduction"):
script_original = MNFScriptDatabase.objects.get(script_id=script_id)
# script_translated = ScriptTranslations.objects.get(
# translation_id=request.session.get('translation_id', None))
update_juggernaut(request, user_id=request.user.id, service_name="conversion",
conversion_pages=request.session['juggernaut_pages_deduction'],
associated_project=script_original,
translation_language=request.session['language_set'])
script_original.is_juggernaut_used = True
# if script_original.languages_juggernaut != "":
# # script_original.languages_juggernaut = str(script_original.languages_juggernaut) + "," + str(
# # script_translated.dial_dest_language)
# else:
# script_original.languages_juggernaut = str(script_translated.dial_dest_language)
script_original.save()
"""Juggernaut Payment Updation Done"""
"""Blockchain Upload Starts here"""
# sys.stdout = original_stdout
scriptconversion = {}
try:
print("trying blockchain 1")
current_datetime = datetime.datetime.now()
if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
obj = ScriptTranslations.objects.get(translation_id=request.session.get('translation_id', None))
obj2 = MNFScriptDatabase.objects.get(script_id=script_id)
temp1 = (str(obj2.script_file_path).split("media/"))[1]
temp2 = str(obj.translated_script_path)
uploaded_script = f"{basePath}/media/{temp1}"
translated_script = f"{basePath}{temp2}"
print("blockchain script conversion 3")
with open(uploaded_script, 'rb') as f:
hash = uploadDataToIPFSNode(f)
scriptconversion["original_scriptFile_hash"] = hash
scriptconversion["original_scriptFile_path"] = uploaded_script
scriptconversion["date_at"] = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print("blockchain script conversion 4")
with open(translated_script, 'rb') as f1:
hash = uploadDataToIPFSNode(f1)
scriptconversion["translated_scriptFile_hash"] = hash
scriptconversion["translated_scriptFile_path"] = translated_script
print("blockchain script conversion 5")
blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user)
UserId = blockchain_obj.user_id
Project = request.session.get('translation_id', None)
Data = str(scriptconversion)
userPrivateKey = blockchain_obj.privateKey
userkey = decryptionOfPrivate(userPrivateKey)
tx_id = UploadConversionData(OWNER_KEY, blockchain_obj.publicKey, UserId, str(Project), Data)
user_infos = user_info(tx_hash=tx_id, service="Conversion", gas_fee=1234567888882)
addition_result = user_infos.update_info(request)
print("blockchain script conversion 6")
certificatepath = certificateGenrate(request.user.username, "script conversion", hash)
hash = hash_decrypation(hash)
to_email = [request.user.email]
email_code = 'BL1'
key_value = {
"service": "script conversion",
"hash": hash,
"public key": blockchain_obj.publicKey,
"private key": userkey.decode('utf-8'),
"Transaction Hash": tx_id
}
sendmail(to_email=to_email, email_code=email_code, key_value=key_value, filePath=certificatepath)
except Exception as e:
print("Error in blockchain is", e)
"""Blockchain Upload Ends here"""
"""Translation Completion mail here"""
# sys.stdout = original_stdout
to = request.user.email
key_value = {
"User": request.user.username,
"title": (((str(obj2.script_file_path).split("/"))[-1]).split("."))[0]
}
sendmail(to_email=[to], email_code="PP18", key_value=key_value)
"""Translation Completion mail done"""
"""Vetting Process if Choosen"""
# sys.stdout = original_stdout
if request.POST.get("to_be_vetted_by_lpp") == "on":
obj = ScriptTranslations.objects.get(translation_id=request.session.get('translation_id', None))
obj.lpp = True
obj.save()
X = LPPTASKDatabase()
X.user_id = obj.user_id
X.usernote = "Kindly check if the translated file is correct as per the Uploaded Document!"
X.translated_script = obj
X.generated_from = "conversion"
temp_amount = request.session["amount_without_subscrption"]
X.amoutgiventolpp_action = round((temp_amount / 2), 2)
X.amoutgiventolpp_dialogue = round((temp_amount / 2), 2)
X.save()
# task_assigner(int(X.task_id), "conversion")
"""Vetting Process Done"""
# Conversion(request).start()
keys_to_delete = []
for key, value in request.session.items():
if key not in ['_auth_user_id', '_auth_user_backend', '_auth_user_hash', '_session_init_timestamp_']:
keys_to_delete.append(key)
print("Keys to be deleted is ->", keys_to_delete)
for key in keys_to_delete:
del request.session[key]
# print("Script Translated successfully and Sent for Vetting if chosen")
# profile.disable()
# profile.print_stats(sort='cumulative')
# f.close()
sys.stdout = original_stdout
# print("Time Taken For Conversion Processing is ->", time.time() - start_time)
return JsonResponse({}, status=200)
# -> For Viewing Your Conversion
@login_required(login_url="/PersonalLogin-2")
def view_conversion_bkp(request):
start_time = time.time()
# get data from the blockchain for ppt
if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
try:
ppt = []
blockchain_obj = UserCredentialsForBlockchain.objects.get(
user=request.user)
projectIds = getUserprojectIds(blockchain_obj.user_id)
# Print array values from the last element to the first
ppt_all = len(projectIds)
for i in range(len(projectIds) - 1, -1, -1):
privatekey = blockchain_obj.privateKey
user_id = blockchain_obj.user_id
Project = projectIds[i]
private_Key = decryptionOfPrivate(privatekey)
status, getData = getPPTConversion(
private_Key.decode('utf-8'), user_id, Project)
if status == True:
data1 = getData[1]
converted_dict = eval(data1)
download_file_System(converted_dict.get(
"ppt_scriptFile_hash"), converted_dict.get("ppt_scriptFile_path"))
download_file_System(converted_dict.get(
"translated_ppt_hash"), converted_dict.get("translated_ppt_path"))
converted_dict["vetted_file_url"]=decryptionOfUrl(converted_dict.get("vetted_file_hash"))
converted_dict["orginal_file_url"]=decryptionOfUrl(converted_dict.get("ppt_scriptFile_hash"))
converted_dict["translate_file_url"]=decryptionOfUrl(converted_dict.get("translated_ppt_hash"))
ppt.append(converted_dict)
except:
ppt = pptconversion.objects.filter(
user_id=request.user.id).order_by("-date_at")
ppt_all = pptconversion.objects.filter(
user_id=request.user.id).count()
else:
ppt = pptconversion.objects.filter(
user_id=request.user.id).order_by("-date_at")
ppt_all = pptconversion.objects.filter(user_id=request.user.id).count()
if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
obj = []
blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user)
script_projectIds = scriptGetUserprojectIds(blockchain_obj.user_id)
number = len(script_projectIds)
for i in range(len(script_projectIds) - 1, -1, -1):
privatekey = blockchain_obj.privateKey
user_id =blockchain_obj.user_id
Project= script_projectIds[i]
private_Key = decryptionOfPrivate(privatekey)
status,getData = getConversion(private_Key.decode('utf-8'),user_id,Project)
if status == True:
data1 = getData[1]
converted_dict = eval(data1)
# download_file_System(converted_dict.get("original_scriptFile_hash"),converted_dict.get("original_scriptFile_path"))
# download_file_System(converted_dict.get("translated_scriptFile_hash"),converted_dict.get("translated_scriptFile_path"))
converted_dict["original_scriptFile_url"]=viewDecryptionOfUrl(converted_dict.get("original_scriptFile_hash"))
converted_dict["translated_scriptFile_url"]=viewDecryptionOfUrl(converted_dict.get("translated_scriptFile_hash"))
converted_dict["translated_docxscriptFile_url"]=decryptionOfUrl(converted_dict.get("translated_docxscriptFile_hash"))
obj.append(converted_dict)
else:
number = ReferUser.objects.filter(refferedBy=request.user).count()
obj = MNFScriptDatabase.objects.filter(
user_id=request.user).order_by("-date_at")
# number = ReferUser.objects.filter(refferedBy=request.user).count()
# obj = MNFScriptDatabase.objects.filter(
# user_id=request.user).order_by("-date_at")
script_path = []
pq = 0
for i in obj:
if i.get("translated_script_path")!= "":
script_path.append(i.get("translated_script_path"))
pq += 1
script_is_vetted = []
tasks = LPPTASKDatabase.objects.filter(user_id=request.user)
for script in obj:
script_is_vetted.append({"0": "0", "1": "", "2": script})
for task in tasks:
if task.translated_script:
if script.get("script_id") == task.translated_script.script_id:
script_is_vetted[-1]["0"] = "1"
if task.outputfile:
script_is_vetted[-1]["1"] = task.outputfile
else:
if task.lppacceptancetime_dialogue and task.completiontime_action:
script_is_vetted[-1]["1"] = f"Vetting of your file will complete in {math.ceil((((task.deadlinetolpp_dialogue - tz.now()).total_seconds()) / 60 / 60) / 24)}"
elif task.lppacceptancetime_action:
script_is_vetted[-1]["1"] = f"Vetting of your file will complete in {math.ceil((((task.deadlinetolpp_action - tz.now()).total_seconds()) / 60 / 60) / 24)}"
else:
script_is_vetted[-1]["1"] = "Vetting of your file has not yet started"
lenV = len(script_path)
countOfScript = len(script_is_vetted)
print(pq, script_is_vetted, script_path, "view conversion data99997")
# -> Getting all Books
# if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
# blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user)
# projectIds = getUserprojectIds(blockchain_obj.user_id)
# for i in range(len(projectIds) - 1, -1, -1):
# privatekey = blockchain_obj.privateKey
# user_id =blockchain_obj.user_id
# Project= projectIds[i]
# private_Key = decryptionOfPrivate(privatekey)
# status,getData = getConversion(private_Key.decode('utf-8'),user_id,Project)
# if status == True:
# data1 = getData[1]
# converted_dict = eval(data1)
# download_file_System(converted_dict.get("original_bookFile_hash"),converted_dict.get("original_bookFile_path"))
# download_file_System(converted_dict.get("translated_bookFile_hash"),converted_dict.get("translated_bookFile_path"))
# else:
all_books = BookConversion.objects.filter(
user_id=request.user).filter(translated_book_pdf__isnull=False).order_by("-date_at")
# no_books = 0
# for i in obj:
# if i.translated_book_pdf != "":
# no_books += 1
# return render(
# request,
# "conversion/viewConvertedBooks.html",
# {"script_path": obj22, "pqw": pq2},
# )
print("rhis is data 777", ppt, "//////////********////////", ppt_all)
end_time = time.time()
print("-------------Taken Time for input processing->", end_time - start_time)
return render(
request,
"conversion/stored_conversions.html",
{
"script_path": obj,
"pq": pq,
"number": number,
"vettdata": script_is_vetted,
"totalScript": countOfScript,
"ppt": ppt,
"ppt_all": ppt_all,
"books": all_books,
"number_books": len(all_books)
},
)
# def view_conversion2(request):
#
# if request.method == "GET":
# # number = ReferUser.objects.filter(refferedBy=request.user).count()
# obj = ScriptTranslations.objects.filter(
# user_id=request.user).order_by("-date_translated")
# # pq = 0
#
# # script_is_vetted = []
# # tasks = LPPTASKDatabase.objects.filter(user_id=request.user)
# # for script in obj:
# # script_is_vetted.append({"0": "0", "1": "", "2": script, "3": ""})
# # for task in tasks:
# # if task.translated_script:
# # if script.translation_id == task.translated_script.translation_id:
# # script_is_vetted[-1]["0"] = "1"
# # if task.outputfile:
# # script_is_vetted[-1]["1"] = task.outputfile
# # else:
# # if task.lppacceptancetime_dialogue and task.completiontime_action:
# # script_is_vetted[-1][
# # "3"] = f"Vetting of your file will complete in {math.ceil((((task.deadlinetolpp_dialogue - tz.now()).total_seconds()) / 60 / 60) / 24)} day"
# # elif task.lppacceptancetime_action:
# # script_is_vetted[-1][
# # "3"] = f"Vetting of your file will complete in {math.ceil((((task.deadlinetolpp_action - tz.now()).total_seconds()) / 60 / 60) / 24)} day"
# # else:
# # script_is_vetted[-1]["3"] = "Vetting of your file has not yet started"
#
# # lenV = len(script_path)
# countOfScript = len(obj)
#
# return render(
# request,
# "conversion2/stored_conversions.html",
# {
# "script_path": obj,
# "totalScript": countOfScript,
# },
# )
def view_conversion2(request):
if request.method == "GET":
# number = ReferUser.objects.filter(refferedBy=request.user).count()
obj = ScriptTranslations.objects.filter(
user_id=request.user).order_by("-date_translated")
pq = 0
for i in obj:
if str(i.status) in ["Completed", "Failed"]:
pq += 1
elif i.lpp == True:
pq += 1
# script_is_vetted = []
# tasks = LPPTASKDatabase.objects.filter(user_id=request.user)
# for script in obj:
# script_is_vetted.append({"0": "0", "1": "", "2": script, "3": ""})
# for task in tasks:
# if task.translated_script:
# if script.translation_id == task.translated_script.translation_id:
# script_is_vetted[-1]["0"] = "1"
# if task.outputfile:
# script_is_vetted[-1]["1"] = task.outputfile
# else:
# if task.lppacceptancetime_dialogue and task.completiontime_action:
# script_is_vetted[-1][
# "3"] = f"Vetting of your file will complete in {math.ceil((((task.deadlinetolpp_dialogue - tz.now()).total_seconds()) / 60 / 60) / 24)} day"
# elif task.lppacceptancetime_action:
# script_is_vetted[-1][
# "3"] = f"Vetting of your file will complete in {math.ceil((((task.deadlinetolpp_action - tz.now()).total_seconds()) / 60 / 60) / 24)} day"
# else:
# script_is_vetted[-1]["3"] = "Vetting of your file has not yet started"
# lenV = len(script_path)
countOfScript = len(obj)
return render(
request,
"conversion2/stored_conversions.html",
{
"script_path": obj,
"totalScript": pq,
},
)
@login_required(login_url="/PersonalLogin-2")
def view_conversion(request):
start_time = time.time()
# get data from the blockchain for ppt
# if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
# try:
# ppt = []
# blockchain_obj = UserCredentialsForBlockchain.objects.get(
# user=request.user)
# projectIds = getUserprojectIds(blockchain_obj.user_id)
# # Print array values from the last element to the first
# ppt_all = len(projectIds)
# for i in range(len(projectIds) - 1, -1, -1):
# privatekey = blockchain_obj.privateKey
# user_id = blockchain_obj.user_id
# Project = projectIds[i]
# private_Key = decryptionOfPrivate(privatekey)
# status, getData = getPPTConversion(
# private_Key.decode('utf-8'), user_id, Project)
# if status == True:
# data1 = getData[1]
# converted_dict = eval(data1)
# download_file_System(converted_dict.get(
# "ppt_scriptFile_hash"), converted_dict.get("ppt_scriptFile_path"))
# download_file_System(converted_dict.get(
# "translated_ppt_hash"), converted_dict.get("translated_ppt_path"))
# converted_dict["vetted_file_url"] = decryptionOfUrl(converted_dict.get("vetted_file_hash"))
# converted_dict["orginal_file_url"] = decryptionOfUrl(converted_dict.get("ppt_scriptFile_hash"))
# converted_dict["translate_file_url"] = decryptionOfUrl(converted_dict.get("translated_ppt_hash"))
#
# ppt.append(converted_dict)
#
# except:
# ppt = pptconversion.objects.filter(
# user_id=request.user.id).order_by("-date_at")
# ppt_all = pptconversion.objects.filter(
# user_id=request.user.id).count()
#
# else:
ppt = pptconversion.objects.filter(
user_id=request.user.id).order_by("-date_at")
ppt_all = pptconversion.objects.filter(user_id=request.user.id).filter(translated_ppt__isnull=False, translated_ppt__gt='').count()
# if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
# obj = []
# blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user)
# script_projectIds = scriptGetUserprojectIds(blockchain_obj.user_id)
# print("All Script Ids *********----->", script_projectIds)
# number = len(script_projectIds)
# for i in range(len(script_projectIds) - 1, -1, -1):
# privatekey = blockchain_obj.privateKey
# user_id = blockchain_obj.user_id
# Project = script_projectIds[i]
# private_Key = decryptionOfPrivate(privatekey)
# status, getData = getConversion(private_Key.decode('utf-8'), user_id, Project)
# if status == True:
# data1 = getData[1]
# converted_dict = eval(data1)
# # download_file_System(converted_dict.get("original_scriptFile_hash"),converted_dict.get("original_scriptFile_path"))
# # download_file_System(converted_dict.get("translated_scriptFile_hash"),converted_dict.get("translated_scriptFile_path"))
# converted_dict["original_scriptFile_url"] = viewDecryptionOfUrl(
# converted_dict.get("original_scriptFile_hash"))
# converted_dict["translated_scriptFile_url"] = viewDecryptionOfUrl(
# converted_dict.get("translated_scriptFile_hash"))
# converted_dict["translated_docxscriptFile_url"] = decryptionOfUrl(
# converted_dict.get("translated_docxscriptFile_hash"))
# obj.append(converted_dict)
# else:
number = ReferUser.objects.filter(refferedBy=request.user).count()
# obj = MNFScriptDatabase.objects.filter(
# user_id=request.user).order_by("-date_at")
obj = ScriptTranslations.objects.filter(
user_id=request.user).order_by("-date_translated")
# number = ReferUser.objects.filter(refferedBy=request.user).count()
# obj = MNFScriptDatabase.objects.filter(
# user_id=request.user).order_by("-date_at")
script_path = []
pq = 0
for i in obj:
if i.translated_script_path != "":
# script_path.append(i.get("translated_script_path"))
pq += 1
script_is_vetted = []
tasks = LPPTASKDatabase.objects.filter(user_id=request.user)
for script in obj:
script_is_vetted.append({"0": "0", "1": "", "2": script, "3":""})
for task in tasks:
if task.translated_script:
if script.translation_id == task.translated_script.translation_id:
script_is_vetted[-1]["0"] = "1"
if task.outputfile:
script_is_vetted[-1]["1"] = task.outputfile
else:
if task.lppacceptancetime_dialogue and task.completiontime_action:
script_is_vetted[-1][
"3"] = f"Vetting of your file will complete in {math.ceil((((task.deadlinetolpp_dialogue - tz.now()).total_seconds()) / 60 / 60) / 24)} day"
elif task.lppacceptancetime_action:
script_is_vetted[-1][
"3"] = f"Vetting of your file will complete in {math.ceil((((task.deadlinetolpp_action - tz.now()).total_seconds()) / 60 / 60) / 24)} day"
else:
script_is_vetted[-1]["3"] = "Vetting of your file has not yet started"
# lenV = len(script_path)
countOfScript = len(script_is_vetted)
# print(pq, script_is_vetted, script_path, "view conversion data99997")
# -> Getting all Books
# if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
# blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user)
# projectIds = getUserprojectIds(blockchain_obj.user_id)
# for i in range(len(projectIds) - 1, -1, -1):
# privatekey = blockchain_obj.privateKey
# user_id =blockchain_obj.user_id
# Project= projectIds[i]
# private_Key = decryptionOfPrivate(privatekey)
# status,getData = getConversion(private_Key.decode('utf-8'),user_id,Project)
# if status == True:
# data1 = getData[1]
# converted_dict = eval(data1)
# download_file_System(converted_dict.get("original_bookFile_hash"),converted_dict.get("original_bookFile_path"))
# download_file_System(converted_dict.get("translated_bookFile_hash"),converted_dict.get("translated_bookFile_path"))
# else:
all_books = BookConversion.objects.filter(
user_id=request.user).filter(translated_book_pdf__isnull=False).order_by("-date_at")
# no_books = 0
# for i in obj:
# if i.translated_book_pdf != "":
# no_books += 1
# return render(
# request,
# "conversion/viewConvertedBooks.html",
# {"script_path": obj22, "pqw": pq2},
# )
# print("rhis is data 777", ppt, "//////////********////////", ppt_all)
end_time = time.time()
print("-------------Taken Time for input processing->", end_time - start_time)
return render(
request,
"conversion/stored_conversions.html",
{
"script_path": obj,
"pq": pq,
"number": number,
"vettdata": script_is_vetted,
"totalScript": countOfScript,
"ppt": ppt,
"ppt_all": ppt_all,
"books": all_books,
"number_books": len(all_books)
},
)
def fetch_data_blockchain(request):
if request.method == "POST":
id = str(request.POST.get("id"))
service = str(request.POST.get("service"))
type_file = request.POST.get("type_file")
privatekey1 = request.POST.get("privateKey")
translated_script = ScriptTranslations.objects.get(translation_id=str(id))
decryptionFunc = decryptionOfUrl if request.POST.get("type_file") == "original" else viewDecryptionOfUrl
if service == "Script":
type_file = "original_scriptFile_hash" if type_file == "original" else \
"translated_scriptFile_hash"
try:
if request.user == translated_script.user_id:
blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user)
privatekey = blockchain_obj.privateKey
user_id = blockchain_obj.user_id
private_Key = decryptionOfPrivate(privatekey)
with open("/home/mnfidea/mnf/MNF/app/Blockchain2/file_stroge.txt","a") as file01:
file01.write("1.user private key-------------------" + str(private_Key) + str(request.user) +"\n")
status, getData = getConversion(privatekey1, user_id, str(id))
if status == True:
data1 = getData[1]
converted_dict = eval(data1)
print("Data Script ------------>",converted_dict)
# converted_dict["original_scriptFile_url"] = viewDecryptionOfUrl(
# converted_dict.get("original_scriptFile_hash"))
# converted_dict["translated_scriptFile_url"] = viewDecryptionOfUrl(
# converted_dict.get("translated_scriptFile_hash"))
# converted_dict["translated_docxscriptFile_url"] = decryptionOfUrl(
# converted_dict.get("translated_docxscriptFile_hash"))
# decryptionFunc = decryptionOfUrl if request.POST.get("type_file") == "original" else viewDecryptionOfUrl
# if request.POST.get("type_file") == "original":
# download_file_System(converted_dict.get(
# "original_scriptFile_hash"), converted_dict.get("original_scriptFile_path"))
file_name = None
if request.POST.get("type_file") == "original":
file_name = str((str(converted_dict['original_scriptFile_path']).split("/"))[-1])
file_link = str(decryptionFunc(converted_dict.get(str(type_file))))
else:
file_name = str((str(converted_dict['translated_scriptFile_path']).split("/"))[-1])
file_link = str(decryptionFunc(converted_dict.get(str(type_file))))
return JsonResponse({"status":True, "download_link": file_link, "file_name": str(file_name)})
else:
try:
current_datetime = datetime.datetime.now()
if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
print("blockchain script conversion 2")
obj = ScriptTranslations.objects.get(translation_id=id)
obj2 = MNFScriptDatabase.objects.get(script_id=obj.script_link_id)
temp1 = (str(obj2.script))
temp2 = str(obj.translated_script_path)
uploaded_script = f"{basePath}/media/{temp1}"
translated_script = f"{basePath}{temp2}"
scriptconversion = {}
print("blockchain script conversion 3")
with open(uploaded_script, 'rb') as f:
hash = uploadDataToIPFSNode(f)
scriptconversion["original_scriptFile_hash"] = hash
scriptconversion["original_scriptFile_path"] = uploaded_script
scriptconversion["date_at"] = current_datetime.strftime(
"%Y-%m-%d %H:%M:%S")
print("blockchain script conversion 4")
with open(translated_script, 'rb') as f1:
hash = uploadDataToIPFSNode(f1)
scriptconversion["translated_scriptFile_hash"] = hash
scriptconversion["translated_scriptFile_path"] = translated_script
# docx_file_path = translated_script.replace(".pdf", ".docx")
# docxfile_name = docx_file_path.split("/")[-1]
# docxfile_name ="translate_docx_file.docx"
#
# with open(docx_file_path, 'rb') as f2:
# hash1 = uploadDataToIPFSNode(f2)
# scriptconversion["translated_docxscriptFile_hash"] = hash1
# scriptconversion["docxfile_name"] = docxfile_name
print("blockchain script conversion 5")
blockchain_obj = UserCredentialsForBlockchain.objects.get(
user=request.user)
UserId = blockchain_obj.user_id
Project = request.session.get('translation_id', None)
Data = str(scriptconversion)
userPrivateKey = blockchain_obj.privateKey
userkey = decryptionOfPrivate(userPrivateKey)
# hash1 = UploadConversionData(OWNER_KEY,blockchain_obj.publicKey, UserId, str(Project), Data)
# transaction_hash = UploadConversionData(tx_id)
tx_id = UploadConversionData(OWNER_KEY, blockchain_obj.publicKey, UserId, str(Project),
Data)
print("blockchain script conversion 6")
print("scriptconversion hash >>>>>>>>>>>>>>>", hash)
certificatepath = certificateGenrate(request.user.username, "script conversion", hash)
hash = hash_decrypation(hash)
to_email = [request.user.email]
email_code = 'BL1'
key_value = {
"service": "script conversion",
"hash": hash,
"public key": blockchain_obj.publicKey,
"private key": userkey.decode('utf-8'),
"Transaction Hash": tx_id
}
sendmail(to_email=to_email, email_code=email_code, key_value=key_value,
filePath=certificatepath)
file_name = None
if request.POST.get("type_file") == "original":
file_name = str((str(scriptconversion['original_scriptFile_path']).split("/"))[-1])
file_link = str(decryptionFunc(scriptconversion.get(str(type_file)))) + "/" + str(
file_name)
else:
file_link = str(decryptionFunc(scriptconversion.get(str(type_file))))
return JsonResponse(
{"status": True, "download_link": file_link, "file_name": str(file_name)})
except Exception as e:
print("Error is----------------*******************:", e)
return JsonResponse({"status": False})
except Exception as e:
# try:
# current_datetime = datetime.datetime.now()
# if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
# print("blockchain script conversion 2")
# obj = ScriptTranslations.objects.get(translation_id=id)
# obj2 = MNFScriptDatabase.objects.get(script_id=obj.script_link_id)
# temp1 = (str(obj2.script_file_path).split("media/"))[1]
# temp2 = str(obj.translated_script_path)
# uploaded_script = f"{basePath}/media/{temp1}"
# translated_script = f"{basePath}{temp2}"
# scriptconversion = {}
# print("blockchain script conversion 3")
# with open(uploaded_script, 'rb') as f:
# hash = uploadDataToIPFSNode(f)
# scriptconversion["original_scriptFile_hash"] = hash
# scriptconversion["original_scriptFile_path"] = uploaded_script
# scriptconversion["date_at"] = current_datetime.strftime(
# "%Y-%m-%d %H:%M:%S")
# print("blockchain script conversion 4")
# with open(translated_script, 'rb') as f1:
# hash = uploadDataToIPFSNode(f1)
# scriptconversion["translated_scriptFile_hash"] = hash
# scriptconversion["translated_scriptFile_path"] = translated_script
# # docx_file_path = translated_script.replace(".pdf", ".docx")
# # docxfile_name = docx_file_path.split("/")[-1]
# # docxfile_name ="translate_docx_file.docx"
# #
# # with open(docx_file_path, 'rb') as f2:
# # hash1 = uploadDataToIPFSNode(f2)
# # scriptconversion["translated_docxscriptFile_hash"] = hash1
# # scriptconversion["docxfile_name"] = docxfile_name
# print("blockchain script conversion 5")
# # blockchain_obj = UserCredentialsForBlockchain.objects.get(
# # user=request.user)
# # UserId = blockchain_obj.user_id
# Project = request.session.get('translation_id', None)
# Data = str(scriptconversion)
# # userPrivateKey = blockchain_obj.privateKey
# userkey = decryptionOfPrivate(userPrivateKey)
# # hash1 = UploadConversionData(OWNER_KEY,blockchain_obj.publicKey, UserId, str(Project), Data)
# # transaction_hash = UploadConversionData(tx_id)
# tx_id = UploadConversionData(OWNER_KEY, blockchain_obj.publicKey, UserId, str(Project), Data)
# print("blockchain script conversion 6")
# print("scriptconversion hash >>>>>>>>>>>>>>>", hash)
# certificatepath = certificateGenrate(request.user.username, "script conversion", hash)
# hash = hash_decrypation(hash)
# to_email = [request.user.email]
# email_code = 'BL1'
# key_value = {
# "service": "script conversion",
# "hash": hash,
# "public key": blockchain_obj.publicKey,
# "private key": userkey.decode('utf-8'),
# "Transaction Hash": tx_id
# }
# sendmail(to_email=to_email, email_code=email_code, key_value=key_value,
# filePath=certificatepath)
#
# file_name = None
# if request.POST.get("type_file") == "original":
# file_name = str((str(scriptconversion['original_scriptFile_path']).split("/"))[-1])
# file_link = str(decryptionFunc(scriptconversion.get(str(type_file)))) + "/" + str(file_name)
# else:
# file_link = str(decryptionFunc(scriptconversion.get(str(type_file))))
#
# return JsonResponse({"status": True, "download_link": file_link, "file_name": str(file_name)})
# except Exception as e:
print("Error is----------------*******************:",e)
return JsonResponse({"status": False})
elif service == "PPT":
type_file = "ppt_scriptFile_hash" if type_file == "original" else \
"vetted_file_hash" if type_file == "vetted" else "translated_ppt_hash"
try:
if request.user == pptconversion.objects.get(ppt_id=str(id)).user_id:
blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user)
privatekey = blockchain_obj.privateKey
user_id = blockchain_obj.user_id
private_Key = decryptionOfPrivate(privatekey)
status, getData = getPPTConversion(private_Key.decode('utf-8'), user_id, str(id))
if status == True:
data1 = getData[1]
converted_dict = eval(data1)
file_link = str(decryptionOfUrl(converted_dict.get(str(type_file))))
file_name = file_name = str((str(converted_dict['ppt_scriptFile_path']).split("/"))[-1]) if request.POST.get("type_file") == "original" else str((str(converted_dict['translated_ppt_path']).split("/"))[-1])
return JsonResponse({"status": True, "download_link": file_link + "/" + str(file_name), "file_name":str(file_name)})
else:
return JsonResponse({"status": False})
except Exception as e:
print("Error is----------------*******************:", e)
return JsonResponse({"status": False})
return HttpResponse("Get Request Not Allowed")
# -> For Deleting your Conversion
def delete_script(request, id):
script_name = str(ScriptTranslations.objects.get(
translation_id=id).script_link_id.script_title)
obj = ScriptTranslations.objects.get(translation_id=id)
# if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
# blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user)
# userkey =decryptionOfPrivate(blockchain_obj.privateKey)
# print("function is calling.......",userkey.decode('utf-8'),blockchain_obj.user_id,obj.translation_id)
# deleteConversion(OWNER_KEY,blockchain_obj.publicKey,blockchain_obj.user_id,obj.translation_id)
obj.delete()
to = request.user.email
key_value = {
"User": request.user.username,
"script_name": str(script_name)
}
sendmail(to_email=[to], email_code="PP20", key_value=key_value)
return HttpResponseRedirect("/conversion/view_conversion")
# -> Feedback on Conversion by User
def feedback_user(request):
if request.method == "POST":
x = ScriptTranslations.objects.get(translation_id=request.POST.get("mnfscriptid"))
if str(request.POST.get("text")) == " " or str(request.POST.get("text")) == "":
x.attention_feedback = ""
else:
x.attention_feedback = str(request.POST.get("text"))
if str(request.POST.get("text2")) == " " or str(request.POST.get("text2")) == "":
x.error_faced_feedback = ""
else:
x.error_faced_feedback = str(request.POST.get("text2"))
if str(request.POST.get("text3")) == " " or str(request.POST.get("text3")) == "":
x.improvement_feedback = ""
else:
x.improvement_feedback = str(request.POST.get("text3"))
if request.POST.get("rating") == " " or request.POST.get("rating") == "":
x.exp_rate = 0
else:
x.exp_rate = int(request.POST.get("rating"))
if request.POST.get("rating2") == " " or request.POST.get("rating2") == "":
x.content_accuracy_rate = 0
else:
x.content_accuracy_rate = int(request.POST.get("rating3"))
if request.POST.get("rating3") == " " or request.POST.get("rating3") == "":
x.translation_accuracy_rate = 0
else:
x.translation_accuracy_rate = int(request.POST.get("rating2"))
x.save()
return redirect("view_conversion")
# -> For Demo of Conversion
def demo(request):
number = ReferUser.objects.filter(refferedBy=request.user).count()
return render(request, "conversion/demo.html", {"number": number})
# -> Some Random Function
def announce(request):
message = ""
user = User.objects.all()
cUser = request.user
if cUser.is_superuser == True:
if request.method == "POST":
notification = request.POST.get("message")
for i in user:
var = Notifications(user_id=i, notification=notification)
var.save()
messgae = "notification sent successfull."
return render(request, "conversion/announce.html", {"message": message})
else:
return render(request, "conversion/announce.html", {})
else:
message = " you need to be superuser"
return render(request, "conversion/announce.html", {"message": message})
def conversion_payment(request):
print("11111111111111111111199999999999999999999999999-----")
print(request.POST.get("centralised"))
print(request.POST.get("request_id"))
if request.method == "POST":
is_sample_script = False
# <--- UNUSED CODE --->
if request.POST.get("centralised") == "yes":
x = Conversions()
print(str(request.POST.get("script_id")))
x.version_no = int(
MNFScriptDatabase_2.objects.get(
script_id=str(request.POST.get("script_id"))
).version_no
)
# x.version_no =
x.nondial_dest_language = languages.get(
request.POST.get("nondial_dest_language")
)
x.dial_dest_language = languages.get(request.POST.get("dial_dest_language"))
x.dial_dest_script = request.POST.get("dial_dest_script")
x.dial_src_language = request.POST.get("dial_src_lang")
x.nondial_src_language = request.POST.get("non_dial_src_lang")
x.dial_src_script = request.POST.get("dial_src_script")
x.nondial_src_script = request.POST.get("non_dial_src_script")
print(
"Actionline Script Dest is:", request.POST.get("non_dial_dest_script")
)
x.nondial_dest_script = request.POST.get("non_dial_dest_script")
sampleScript = request.POST.get("SampleScript")
dial_conv_script = ""
x.languages = [
request.POST.get("nondial_dest_language"),
request.POST.get("dial_dest_language"),
]
dual_dial_script = request.POST.get("dual_dial_script")
if dual_dial_script == "on":
x.dual_dial_script = "Yes"
else:
x.dual_dial_script = "No"
dial_conv_script = request.POST.get("dial_src_script1")
opt3 = request.POST.get("opt3")
opt4 = request.POST.get("opt4")
opt5 = request.POST.get("opt5")
opt6 = request.POST.get("opt6")
x.numPages = request.session["numPages"]
x.save()
# try:
# print("line 81999")
if Conversion_link.objects.filter(
script_name=MNFScriptDatabase_2.objects.get(
script_id=str(request.POST.get("script_id"))
)
).exists():
z = Conversion_link.objects.get(
script_name=MNFScriptDatabase_2.objects.get(
script_id=str(request.POST.get("script_id"))
)
)
z.conversions.add(x)
z.save()
# except:
else:
print("line 812999")
z = Conversion_link()
z.script_name = MNFScriptDatabase_2.objects.get(
script_id=str(request.POST.get("script_id"))
)
z.user_id = request.user
z.save()
z.conversions.add(x)
z.save()
# z = Conversions()
# z.created_on = datetime.now()
# z.dial_src_language = request.POST.get("dial_src_lang")
# z.dial_dest_language = request.POST.get("dial_dest_language")
# z.dial_dest_script = request.POST.get("dial_dest_script")
# z.nondial_dest_language = request.POST.get("nondial_dest_language")
# z.nondial_src_script = request.POST.get("non_dial_src_script")
# z.dial_src_script = request.POST.get("dial_src_script")
# z.dual_dial_script = x.dual_dial_script
# z.save()
context = {
"script_id": str(request.POST.get("script_id")),
"script_file_path": request.POST.get("fileUpload"),
"dial_dest_language": x.dial_dest_language,
"dial_dest_script": x.dial_dest_script,
"nondial_dest_language": x.nondial_dest_language,
"dial_conv_script": dial_conv_script,
"dial_src_lang": x.dial_src_language,
"non_dial_src_lang": x.nondial_src_language,
"dial_src_script": x.dial_src_script,
"dual_dial_script": x.dual_dial_script,
"option3": opt3,
"option4": opt4,
"option5": opt5,
"option6": opt6,
"to_be_vetted_by_lpp": str(request.POST.get("to_be_vetted_by_lpp")),
"centralised": str(request.POST.get("centralised")),
"request_id": str(request.POST.get("request_id")),
}
else:
if request.POST.get("existing_script"):
print("Existing mein hu")
request.session['existing_script'] = True
script_uuid = request.POST["id"]
x = MNFScriptDatabase.objects.get(id=script_uuid)
numPages = x.numPages
is_sample_script = x.sample_script
if is_sample_script:
sample_instance = x.sample_id
fileurl = sample_instance.script_file_path.name
else:
print(request.POST.get("id"), "New Script")
script_uuid = request.POST["id"]
is_sample_script = request.POST.get("sample_id", False) and script_uuid == "1234567890"
if is_sample_script:
sample_instance = SampleScript.objects.get(sample_id=(request.POST.get("sample_id")))
fileurl = sample_instance.script_file_path.name
x = MNFScriptDatabase()
x.user_id = request.user
x.script = fileurl
x.sample_script = True
x.sample_id = sample_instance
elif MNFScriptDatabase.objects.filter(id=script_uuid).exists():
x = MNFScriptDatabase.objects.get(id=script_uuid)
script_title = request.POST["script_title"]
numPages = request.POST["numPages"]
context = {}
x.numPages = numPages
x.script_id = "scr_" + str(int(time.time()))
x.script_title = script_title.replace(" ", "_")
x.author_name = request.POST.get("author_name") if request.POST.get("author_name")\
else request.user.username
# For translation
x.nondial_src_language = language_2_code.get(request.POST.get("non_dial_src_lang"))
x.nondial_src_script = request.POST.get("non_dial_src_script")
x.dial_src_language = language_2_code.get(request.POST.get("dial_src_lang"))
x.dial_src_script = request.POST.get("dial_src_script")
print("here i am 9898")
""" Related to Sample Script Translations """
if is_sample_script:
print("inside if of sample_id")
# checking if the sample script has a folder or not for storing pre-created translations
if os.path.exists(
f"{basePath}/media/scripts/sample_script_translations/{sample_instance.script_title}"
):
pass
else:
os.mkdir(
f"{basePath}/media/scripts/sample_script_translations/{sample_instance.script_title}"
)
name = (
(str(ntpath.basename(str(BASE_DIR) + fileurl)).split("."))[0]
) + ".pdf"
print("checking file presence", name)
print(
f"{basePath}/media/scripts/sample_script_translations/{sample_instance.script_title}"
f"/{language_2_code.get(request.POST.get('dial_src_lang'))}_{language_2_code.get(request.POST.get('dial_dest_lang'))}_"
f"{language_2_code.get(request.POST.get('non_dial_src_lang'))}_{language_2_code.get(request.POST.get('non_dial_dest_lang'))}_"
f"{request.POST.get('dial_src_script')}_{request.POST.get('dial_dest_script')}_{request.POST.get('non_dial_src_script')}_{request.POST.get('non_dial_dest_script')}_{name}"
)
# check if translation already exists or not
if os.path.isfile(
f"{basePath}/media/scripts/sample_script_translations/{sample_instance.script_title}"
f"/{language_2_code.get(request.POST.get('dial_src_lang'))}_{language_2_code.get(request.POST.get('dial_dest_lang'))}_"
f"{language_2_code.get(request.POST.get('non_dial_src_lang'))}_{language_2_code.get(request.POST.get('non_dial_dest_lang'))}_"
f"{request.POST.get('dial_src_script')}_{request.POST.get('dial_dest_script')}_{request.POST.get('non_dial_src_script')}_{request.POST.get('non_dial_dest_script')}_{name}"
):
# fetch the pre stored_file
x.save()
translation_instance = ScriptTranslations()
translation_instance.user_id = request.user
translation_instance.script_link_id = x
translation_instance.nondial_dest_language = language_2_code.get(request.POST.get("non_dial_dest_lang"))
translation_instance.nondial_dest_script = request.POST.get("non_dial_dest_script")
translation_instance.dial_dest_language = language_2_code.get(request.POST.get("dial_dest_lang"))
translation_instance.dial_dest_script = request.POST.get("dial_dest_script")
# Getting all choices of user regarding Full Dialogues Translation
translation_instance.full_dialogue_option_choices = ",".join(
[str(request.POST.get(f'option{i}') == "on")
for i in range(1, 15)])
# Getting all choices of user regarding Words of Dialogues Translation
translation_instance.sentence_dialogue_option_choices = ",".join(
[str(request.POST.get(f'option{i}') == "on")
for i in range(15, 29)])
# Getting all choices of user regarding translation and transliteration choices of slug, speaker, etc.
translation_instance.other_option_choices = ",".join([str(request.POST.get(f'option{i}') == "on")
for i in range(29, 39)])
# if request.POST.get("dual_dialogue_option") == "on":
# translation_instance.dual_dial_script = True
# translation_instance.left_dual_dial_lang = request.POST.get("dual_left_language")
# translation_instance.left_dual_dial_script = request.POST.get("dual_left_script")
# if request.POST.get("lpp_vetting") == "on":
# translation_instance.lpp = True
translation_instance.translated_script_path = (
f"/media/scripts/sample_script_translations/{sample_instance.script_title}"
f"/{request.POST.get('dial_src_lang')}_{language_2_code.get(request.POST.get('dial_dest_lang'))}_"
f"{request.POST.get('non_dial_src_lang')}_{language_2_code.get(request.POST.get('non_dial_dest_lang'))}_"
f"{request.POST.get('dial_src_script')}_{request.POST.get('dial_dest_script')}_{request.POST.get('non_dial_src_script')}_{request.POST.get('non_dial_dest_script')}_{name}"
)
translation_instance.save()
# messages.success(request, 'You can now Check your Conversion in View Your Conversions !!!')
# request.session['data_alert'] = 'You can now Check your Conversion in View Your Conversions !!!'
return redirect("view_conversion2")
# return render_to_response('conversion/conversion.html', message='You can now Check your Conversion in View Your Conversions !!!')
# Adding Script id to be saved
request.session["script_id"] = x.script_id
""" less than 5 pages condition """
if is_sample_script or int(numPages) <= 5:
print("Sample Script or Free Script")
x.save()
translation_instance = ScriptTranslations()
translation_instance.user_id = request.user
translation_instance.script_link_id = x
translation_instance.nondial_dest_language = language_2_code.get(request.POST.get("non_dial_dest_lang"))
translation_instance.nondial_dest_script = request.POST.get("non_dial_dest_script")
translation_instance.dial_dest_language = language_2_code.get(request.POST.get("dial_dest_lang"))
translation_instance.dial_dest_script = request.POST.get("dial_dest_script")
# Getting all choices of user regarding Full Dialogues Translation
translation_instance.full_dialogue_option_choices = ",".join([str(request.POST.get(f'option{i}') == "on")
for i in range(1, 15)])
# Getting all choices of user regarding Words of Dialogues Translation
translation_instance.sentence_dialogue_option_choices = ",".join([str(request.POST.get(f'option{i}') == "on")
for i in range(15, 29)])
# Getting all choices of user regarding translation and transliteration choices of slug, speaker, etc.
translation_instance.other_option_choices = ",".join([str(request.POST.get(f'option{i}') == "on")
for i in range(29, 39)])
if request.POST.get("dual_dialogue_option") == "on":
translation_instance.dual_dial_script = True
translation_instance.left_dual_dial_lang = request.POST.get("dual_left_language")
translation_instance.left_dual_dial_script = request.POST.get("dual_left_script")
translation_instance.save()
request.session['translation_id'] = str(translation_instance.translation_id)
return render(request, "conversion/thanksconversion.html", {})
# -> Juggernaut Package Handling of existing script
elif request.POST.get("existing_script"):
""" existing script handling """
print("inside existing script code block")
request.session['existing_script'] = request.POST.get("existing_script")
if x.is_juggernaut_used:
print("sopop 3")
# juggernaut_instance = JuggernautPackage.objects.get(user_id = request.user.id)
# langs_list_jugg = [item.strip() for item in list(str(x.languages_juggernaut).split(","))]
# print("List of Juggernaut Languages", langs_list_jugg, dial_dest_language)
response_jugg = check_juggernaut(request, user_id=request.user.id, service_name="conversion",
conversion_pages=int(numPages), associated_project=x,
translation_language=[language_2_code.get(request.POST.get("non_dial_dest_lang")),
request.POST.get("non_dial_dest_script"),
language_2_code.get(request.POST.get("dial_dest_lang")),
request.POST.get("dial_dest_script")])
# -> it is an iteration or new lang which is within limits
if response_jugg["conversion_pages"] == 0:
print("sopop 12", response_jugg)
request.session['is_juggernaut_used'] = True
request.session['language_set'] = [language_2_code.get(request.POST.get("non_dial_dest_lang")),
request.POST.get("non_dial_dest_script"),
language_2_code.get(request.POST.get("dial_dest_lang")),
request.POST.get("dial_dest_script")]
request.session['juggernaut_pages_deduction'] = int(
request.POST["numPages"]) - int(response_jugg[
"conversion_pages"])
translation_instance_id = ScriptTranslations.objects.get(
script_link_id=x,
nondial_dest_language=language_2_code.get(request.POST.get("non_dial_dest_lang")),
nondial_dest_script=request.POST.get("non_dial_dest_script"),
dial_dest_language=language_2_code.get(request.POST.get("dial_dest_lang")),
dial_dest_script=request.POST.get("dial_dest_script")
).translation_id
request.session['translation_id'] = str(translation_instance_id)
request.session["iteration_no"] = int(
JuggernautConversion.objects.get(associated_project=x).iterations) + 1
return render(request, "conversion/thanksconversion.html", {})
# some limit reached
else:
if response_jugg["language_alert"] == True:
print("limit of juggernaut reached")
# -> language limit reached now the ADDON part comes on
numPages = response_jugg["conversion_pages"]
# if str(language_2_code[str(dial_dest_language)]) in langs_list_jugg:
# print("sopop 4")
# # -> getting the scripttranslation instance
# translation_instance = ScriptTranslations.objects.get(
# script_link_id = x,
# dial_dest_language = str(languages.get(dial_dest_language))
# )
# # -> if iteration limit reached
# if translation_instance.iteration >= juggernaut_instance.conversion_iteration:
# print("sopop 5")
# # -> to be done in future
#
# # -> if limit not reached
# print("sopop 6")
# pass
# else:
# print("sopop 7")
# translation_instance.iteration += 1
# translation_instance.save()
# request.session['translation_id'] = str(translation_instance.translation_id)
# return render(request, "conversion/thanksconversion.html", context)
# -> new language
# else:
# print("sopop 8")
# if len(langs_list_jugg) < juggernaut_instance.conversion_languages:
# # -> carry on it is new language
# # try:
# if not request.POST.get("sample_id"):
# print("sopop 9")
# output1 = check_juggernaut(request, user_id=request.user.id, service_name="conversion",
# conversion_pages=int(numPages), associated_project=x, translation_language=str(dial_dest_language))
#
# if len(output1) > 0:
# print("sopop 10")
# if output1["conversion_pages"] == 0:
# print("sopop 11")
# # update_juggernaut(request, user_id=request.user.id, service_name="conversion",
# # conversion_pages=int(request.POST["numPages"]),
# # associated_project=x, translation_language=str(dial_dest_language))
# # x.is_juggernaut_used = True
# # x.languages_juggernaut = str(x.languages_juggernaut) + "," + str(dial_dest_language)
# request.session['juggernaut_pages_deduction'] = int(request.POST["numPages"])
# x.save()
# else:
# print("sopop 12")
# request.session['is_juggernaut_used'] = True
# request.session['languages_juggernaut'] = str(x.languages_juggernaut) + "," + str(dial_dest_language)
# request.session['juggernaut_pages_deduction'] = int(
# request.POST["numPages"]) - int(output1[
# "conversion_pages"])
# numPages = output1["conversion_pages"]
#
# # except Exception as e:
# # print("Error is: ", e)
# else:
# # -> language limit reached now the ADDON part comes on
# pass
else:
print("sopop 13")
# -> check if user has juggernaut or not
if JuggernautPackage.objects.filter(user_id=request.user.id).exists():
print("sopop 14")
juggernaut_instance = JuggernautPackage.objects.get(user_id=request.user.id)
if juggernaut_instance.validity_days and juggernaut_instance.conversion_pages:
print("sopop 15")
if not request.POST.get("sample_id"):
response_jugg = check_juggernaut(request, user_id=request.user.id, service_name="conversion",
conversion_pages=int(numPages), associated_project=x,
translation_language=[language_2_code.get(request.POST.get("non_dial_dest_lang")),
request.POST.get("non_dial_dest_script"),
language_2_code.get(request.POST.get("dial_dest_lang")),
request.POST.get("dial_dest_script")])
print(response_jugg)
if len(response_jugg) > 0:
request.session['language_set'] = [language_2_code.get(request.POST.get("non_dial_dest_lang")),
request.POST.get("non_dial_dest_script"),
language_2_code.get(request.POST.get("dial_dest_lang")),
request.POST.get("dial_dest_script")]
print("sopop 16")
if response_jugg["conversion_pages"] == 0:
request.session['is_juggernaut_used'] = True
request.session['juggernaut_pages_deduction'] = int(request.POST["numPages"])
x.save()
else:
print("sopop 17")
request.session['is_juggernaut_used'] = True
request.session['juggernaut_pages_deduction'] = int(
request.POST["numPages"]) - int(
response_jugg[
"conversion_pages"])
numPages = response_jugg["conversion_pages"]
# -> Juggernaut Package Handling of new script
else:
""" new script handling """
print("Inside Juggernaut New Script Block")
try:
if not request.POST.get("sample_id"):
print("Inside New Script Juggernaut Block -> Not Sample Script")
response_jugg = check_juggernaut(request, user_id=request.user.id, service_name="conversion",
conversion_pages=int(numPages), associated_project=x,
translation_language=[language_2_code.get(request.POST.get("non_dial_dest_lang")),
request.POST.get("non_dial_dest_script"),
language_2_code.get(request.POST.get("dial_dest_lang")),
request.POST.get("dial_dest_script")])
print("Juggernaut Response -> ", response_jugg)
if len(response_jugg) > 0:
print("sopop 20: Juggernaut Permitted New Script")
request.session["language_set"] = [language_2_code.get(request.POST.get("non_dial_dest_lang")),
request.POST.get("non_dial_dest_script"),
language_2_code.get(request.POST.get("dial_dest_lang")),
request.POST.get("dial_dest_script")]
if response_jugg["conversion_pages"] == 0:
print("sopop 21: Juggernaut Zero Payment Scheme")
request.session['is_juggernaut_used'] = True
request.session['juggernaut_pages_deduction'] = int(request.POST["numPages"])
x.save()
else:
print("sopop 22: Juggernaut Non-Zero Payment Scheme")
request.session['is_juggernaut_used'] = True
request.session['juggernaut_pages_deduction'] = int(request.POST["numPages"]) - int(
response_jugg[
"conversion_pages"])
numPages = response_jugg["conversion_pages"]
except Exception as e:
print("Error is: ", e)
print("sopop 23", numPages)
# juggernaut and lpp on
if int(numPages) == 0 and request.POST.get("lpp_vetting") == "on":
try:
context.clear()
except:
context = {}
request.session["lpp"] = True
# context["nondial_dest_language"] = language_2_code.get(request.POST.get("non_dial_dest_lang"))
# context["nondial_dest_script"] = request.POST.get("non_dial_dest_script")
# context["dial_dest_language"] = language_2_code.get(request.POST.get("dial_dest_lang"))
# context["dial_dest_script"] = request.POST.get("dial_dest_script")
# Getting all choices of user regarding Full Dialogues Translation
# context["full_dialogue_option_choices"] = ",".join([request.POST.get(f'option{i}') == "on"
# for i in range(1, 15)])
#
# # Getting all choices of user regarding Words of Dialogues Translation
# context["sentence_dialogue_option_choices"] = ",".join([request.POST.get(f'option{i}') == "on"
# for i in range(15, 29)])
#
# # Getting all choices of user regarding translation and transliteration choices of slug, speaker, etc.
# context["other_option_choices"] = ",".join([request.POST.get(f'option{i}') == "on"
# for i in range(29, 39)])
#
# if request.POST.get("dual_dialogue_option") == "on":
# context["dual_dial_script"] = True
# context["left_dual_dial_lang"] = request.POST.get("dual_left_language")
# context["left_dual_dial_script"] = request.POST.get("dual_left_script")
# if request.POST.get('lpp_vetting') == "on":
# context["lpp_vetting"] = True
# lpp_vetting_type = request.POST.get('radioGroup')
#
# if lpp_vetting_type == "radioOption1":
# context["vetting_type"] = "Dialogues"
#
# elif lpp_vetting_type == "radioOption2":
# context["vetting_type"] = "Entire"
# -> Case of LPP Vetting and Juggernaut Reduced all pages to zero
lpp_available = "yes"
total_amount = round(
(int(float(pricing_data('Script Conversion', 4))) -
int(float(pricing_data('Script Conversion', 2)))) *
request.session['juggernaut_pages_deduction'], 2
)
# request.session["amount_without_subscrption"] = total_amount
pricelist = centralPayment_get_discounts(request, total_amount)
print("pricelist", pricelist)
# context["early_bird_discount"] = discount_limit_handler(DISCOUNT["early_bird"])
context["subtotal"] = round(total_amount, 2)
context["early_bird_calculate"] = pricelist["early_bird_calculate"]
context["staff_discount_calculate"] = pricelist["staff_discount_calculate"]
context["membership_discount_calculate"] = pricelist["membership_discount_calculate"]
context["student_discount_calculate"] = pricelist["student_discount_calculate"]
if int(pricelist['student_discount_calculate']) > 0:
request.session['student_discount_calculate'] = "Yes"
else:
request.session['student_discount_calculate'] = "No"
context['Total_discount'] = pricelist['total_discount']
context['remaining_amount'] = pricelist['total_payable']
context["net_service_charge"] = pricelist["net_service_charge"]
context["gst_calculate"] = pricelist["gst_calculate"]
context["net_payable"] = pricelist["gross_payable"]
if not privilegedUser1.objects.filter(user=request.user, is_active="yes").exists():
context["monthly_membership"] = 1
context["lpp_available"] = lpp_available.upper()
context["script_title"] = x.script_title
context["numPages"] = x.numPages
context["ndial_src"] = x.nondial_src_language
context["dial_src"] = x.dial_src_language
context["ndial_dest"] = request.POST.get("non_dial_dest_lang")
context["dial_dest"] = request.POST.get("dial_dest_lang")
context["dial_dest_script"] = request.POST.get("dial_dest_script")
request.session["nondial_dest_language"] = language_2_code.get(request.POST.get("non_dial_dest_lang"))
request.session["nondial_dest_script"] = request.POST.get("non_dial_dest_script")
request.session["dial_dest_language"] = language_2_code.get(request.POST.get("dial_dest_lang"))
request.session["dial_dest_script"] = request.POST.get("dial_dest_script")
# Getting all choices of user regarding Full Dialogues Translation
request.session["full_dialogue_option_choices"] = ",".join(
[str(request.POST.get(f'option{i}') == "on")
for i in range(1, 15)])
# Getting all choices of user regarding Words of Dialogues Translation
request.session["sentence_dialogue_option_choices"] = ",".join(
[str(request.POST.get(f'option{i}') == "on")
for i in range(15, 29)])
# Getting all choices of user regarding translation and transliteration choices of slug, speaker, etc.
request.session["other_option_choices"] = ",".join([str(request.POST.get(f'option{i}') == "on")
for i in range(29, 39)])
if request.POST.get("dual_dialogue_option") == "on":
request.session["dual_dial_script"] = True
request.session["left_dual_dial_lang"] = request.POST.get("dual_left_language")
request.session["left_dual_dial_script"] = request.POST.get("dual_left_script")
if request.POST.get("lpp_vetting") == "on":
request.session["lpp"] = True
# context["numPages"] = numPages
# context["script_title"] = x.script_title
request.session["amount"] = context["net_payable"]
request.session["amount_without_subscrption"] = context["net_service_charge"]
request.session["discount"] = context["Total_discount"]
request.session["subtotal"] = context["subtotal"]
# request.session["script_id"] = x.script_id
# request.session["script_file_path"] = x.script_file_path
# request.session["script_title"] = context["script_title"]
# request.session["dial_dest_language"] = dial_dest_language
# request.session["dial_dest_script"] = request.POST.get("dial_dest_script")
# request.session["nondial_dest_language"] = languages.get(nondial_dest_language)
# request.session["dial_conv_script"] = dial_conv_script
# request.session["dial_src_lang"] = x.dial_src_language
# request.session["non_dial_src_lang"] = x.nondial_src_language
# request.session["dial_src_script"] = x.dial_src_script
# request.session["non_dial_src_script"] = x.nondial_src_script
# request.session["dual_dial_script"] = xdual_dial_script
# request.session["option3"] = opt3
# request.session["option4"] = opt4
# request.session["option5"] = opt5
# request.session["option6"] = opt6
# request.session["numPages"] = numPages
# request.session["nondial_dest_script"] = request.POST.get("non_dial_dest_script")
user = User.objects.get(id=request.user.id)
try:
wall = Wallet.objects.get(user=request.user)
context["balance"] = round(wall.balance, 2)
except:
context["balance"] = -1
with open(f"{basePath}/MNF/json_keys/conversionRates.json") as c:
curr = json.load(c)
try:
rate = curr["rates"]["INR"]
except Exception as e:
print("checkout error", e)
rate = 80
context["rate"] = rate
# for i in ["early_bird","monthly_member","gst","employ_discount","yearly_member","yearly_member_additional","life_member_additional","life_member_year","life_member"]:
#
# print(rf"7878 discounts are {i}", DISCOUNT[i])
str1 = str(datetime.datetime.now()).split("-")
date_at = f'{str1[2][0:2]} - {str1[1]} - {str1[0]}'
context['date_at'] = date_at
try:
cd = centralDatabase.objects.get(user_id=request.user)
name = cd.firstName if cd.firstName else user.username
email_id = cd.email if cd.email else user.email
phone_number = str(cd.countryCode) + str(cd.contact) if cd.contact else "N/A"
address = cd.address if cd.address else "N/A"
except:
name = user.username
email_id = user.email
phone_number = "N/A"
address = "N/A"
context["name"] = name
context["email_id"] = email_id
context["phone_number"] = phone_number
context["address"] = address
print("7878Context is :", context)
return render(request, "conversion/invoice_conversion.html", context)
# OLD OLD OLD OLD
# context["ndial_dest"] = request.POST.get("nondial_dest_language")
# context["dial_dest"] = request.POST.get("dial_dest_language")
# context["dial_dest_script"] = request.POST.get("dial_dest_script")
# context["nondial_dest_script"] = request.POST.get("non_dial_dest_script")
# context["restrict_to_five"] = "no"
# context["lpp_available"] = lpp_available.upper()
# context["numPages"] = request.session['juggernaut_pages_deduction']
# context["script_title"] = x.script_title
# request.session["amount"] = context["net_payable"]
# request.session["amount_without_subscrption"] = context["net_service_charge"]
# request.session["discount"] = context["Total_discount"]
# request.session["subtotal"] = context["subtotal"]
# request.session["script_id"] = x.script_id
# request.session["script_file_path"] = x.script_file_path
# request.session["script_title"] = context["script_title"]
# request.session["dial_dest_language"] = dial_dest_language
# request.session["dial_dest_script"] = request.POST.get("dial_dest_script")
# request.session["nondial_dest_language"] = languages.get(nondial_dest_language)
# request.session["dial_conv_script"] = dial_conv_script
# request.session["dial_src_lang"] = x.dial_src_language
# request.session["non_dial_src_lang"] = x.nondial_src_language
# request.session["dial_src_script"] = x.dial_src_script
# request.session["non_dial_src_script"] = x.nondial_src_script
# request.session["dual_dial_script"] = xdual_dial_script
# request.session["option3"] = opt3
# request.session["option4"] = opt4
# request.session["option5"] = opt5
# request.session["option6"] = opt6
# request.session["numPages"] = numPages
# request.session["nondial_dest_script"] = request.POST.get("non_dial_dest_script")
# try:
# wall = Wallet.objects.get(user=request.user)
# context["balance"] = round(wall.balance, 2)
# except:
# context["balance"] = -1
# with open(f"{basePath}/MNF/json_keys/conversionRates.json") as c:
# curr = json.load(c)
# try:
# rate = curr["rates"]["INR"]
# except Exception as e:
# print("checkout error", e)
# rate = 80
# context["rate"] = rate
# # for i in ["early_bird","monthly_member","gst","employ_discount","yearly_member","yearly_member_additional","life_member_additional","life_member_year","life_member"]:
# #
# # print(rf"7878 discounts are {i}", DISCOUNT[i])
# str1 = str(datetime.datetime.now()).split("-")
# date_at = f'{str1[2][0:2]} - {str1[1]} - {str1[0]}'
# context['date_at'] = date_at
# user = User.objects.get(id=request.user.id)
# try:
# cd = centralDatabase.objects.get(user_id=request.user)
# name = cd.firstName if cd.firstName else user.username
# email_id = cd.email if cd.email else user.email
# phone_number = str(cd.countryCode) + str(cd.contact) if cd.contact else "N/A"
# address = cd.address if cd.address else "N/A"
# except:
# name = user.username
# email_id = user.email
# phone_number = "N/A"
# address = "N/A"
#
# context["name"] = name
# context["email_id"] = email_id
# context["phone_number"] = phone_number
# context["address"] = address
#
# print("7878Context is :", context)
# return render(request, "conversion/invoice_conversion.html", context)
# juggernaut and lpp off or free case
elif int(numPages) == 0 and not request.POST.get("lpp_vetting") == "on":
print("New Script and Juggernaut and NO LPP")
x.save()
translation_instance = ScriptTranslations()
translation_instance.user_id = request.user
translation_instance.script_link_id = x
translation_instance.nondial_dest_language = language_2_code.get(request.POST.get("non_dial_dest_lang"))
translation_instance.nondial_dest_script = request.POST.get("non_dial_dest_script")
translation_instance.dial_dest_language = language_2_code.get(request.POST.get("dial_dest_lang"))
translation_instance.dial_dest_script = request.POST.get("dial_dest_script")
# Getting all choices of user regarding Full Dialogues Translation
translation_instance.full_dialogue_option_choices = ",".join(
[str(request.POST.get(f'option{i}') == "on")
for i in range(1, 15)])
# Getting all choices of user regarding Words of Dialogues Translation
translation_instance.sentence_dialogue_option_choices = ",".join(
[str(request.POST.get(f'option{i}') == "on")
for i in range(15, 29)])
# Getting all choices of user regarding translation and transliteration choices of slug, speaker, etc.
translation_instance.other_option_choices = ",".join([str(request.POST.get(f'option{i}') == "on")
for i in range(29, 39)])
if request.POST.get("dual_dialogue_option") == "on":
translation_instance.dual_dial_script = True
translation_instance.left_dual_dial_lang = request.POST.get("dual_left_language")
translation_instance.left_dual_dial_script = request.POST.get("dual_left_script")
translation_instance.save()
request.session['translation_id'] = str(translation_instance.translation_id)
return render(request, "conversion/thanksconversion.html", {})
# paid or free 5 scene output
else:
# free 5 scene output
if request.POST.get('5freesample') == "on":
print("free 5 scene sample script")
x.save()
translation_instance = ScriptTranslations()
translation_instance.user_id = request.user
translation_instance.script_link_id = x
translation_instance.nondial_dest_language = language_2_code.get(request.POST.get("non_dial_dest_lang"))
translation_instance.nondial_dest_script = request.POST.get("non_dial_dest_script")
translation_instance.dial_dest_language = language_2_code.get(request.POST.get("dial_dest_lang"))
translation_instance.dial_dest_script = request.POST.get("dial_dest_script")
translation_instance.free_output = True
# Getting all choices of user regarding Full Dialogues Translation
translation_instance.full_dialogue_option_choices = ",".join(
[str(request.POST.get(f'option{i}') == "on")
for i in range(1, 15)])
# Getting all choices of user regarding Words of Dialogues Translation
translation_instance.sentence_dialogue_option_choices = ",".join(
[str(request.POST.get(f'option{i}') == "on")
for i in range(15, 29)])
# Getting all choices of user regarding translation and transliteration choices of slug, speaker, etc.
translation_instance.other_option_choices = ",".join([str(request.POST.get(f'option{i}') == "on")
for i in range(29, 39)])
if request.POST.get("dual_dialogue_option") == "on":
translation_instance.dual_dial_script = True
translation_instance.left_dual_dial_lang = request.POST.get("dual_left_language")
translation_instance.left_dual_dial_script = request.POST.get("dual_left_script")
translation_instance.save()
print("saving")
request.session['translation_id'] = str(translation_instance.translation_id)
return render(request, "conversion/thanksconversion.html", {})
# paid script
else:
print("paid script")
x.save()
try:
context.clear()
except:
context = {}
numPages = int(numPages)
# Price Calculation
# if LPP is Selected and numpages are more than zero(i.e. juggernaut pages are empty)
if request.POST.get("lpp_vetting") == "on" and request.session.get("is_juggernaut_used"):
request.session["lpp"] = True
lpp_available = "yes"
total_amount = round(
int(float(pricing_data('Script Conversion', 2))) * numPages + (
int(float(pricing_data('Script Conversion', 4))) -
int(float(pricing_data('Script Conversion', 2)))
) * (request.session['juggernaut_pages_deduction'] + numPages), 2
)
# normally lpp vetting is selected by user so calculate total amount acc. to it
elif request.POST.get("lpp_vetting") == "on":
lpp_available = "yes"
request.session["lpp"] = True
total_amount = round(
int(float(pricing_data('Script Conversion', 4))) * numPages, 2
)
# total_amount_lpp = round(
# int(float(pricing_data('Script Conversion', 2))) * numPages + (
# int(float(pricing_data('Script Conversion', 4))) -
# int(float(pricing_data('Script Conversion', 2)))
# ) * (request.session['juggernaut_pages_deduction'] + numPages), 2
# )
total_amount_lpp = round(
int(float(total_amount * 0.4)), 2
)
# context["subtotal"] = round(
# numPages * settings.CONVERSION_PER_PAGE, 2
# )
# amt = numPages * settings.CONVERSION_PER_PAGE
# context["subtotal"] = round(amt, 2)
# lppamt = (numPages * settings.CONVERSION_PER_PAGE) + (
# numPages * settings.LPP_PER_PAGE
# )
# context["onlylppfee"] = round((numPages * settings.LPP_PER_PAGE), 2)
# normal non-juggernaut translation with full price
else:
lpp_available = "no"
total_amount = round(
int(float(pricing_data('Script Conversion', 2))) * numPages, 2
)
# all_discounts = get_discounts(request, total_amount, combo_discount=None,combo_discount_calculate=None, service="conversion")
# print("-------------------Total Amount----------------- -> ", total_amount)
# # print("-------------------All Discounts----------------- -> ", all_discounts)
# context["subtotal"] = round(total_amount, 2)
# context["early_bird_discount"] = discount_limit_handler(DISCOUNT["early_bird"])
# context["early_bird_calculate"] = round(
# float((total_amount) * context["early_bird_discount"] / 100), 2)
#
# # staff discount
# if User.objects.get(id=request.user.id).is_staff: # changes done by manoj
# context["sdiscount"] = discount_limit_handler(DISCOUNT["employ_discount"])
# context["staff_discount_calculate"] = round(float(
# (total_amount - context["early_bird_calculate"]) * context[
# "sdiscount"] / 100), 2)
# else:
# context["sdiscount"] = 0
# context["staff_discount_calculate"] = 0
#
# user = User.objects.get(id=request.user.id)
#
# try:
# memberType = privilegedUser1.objects.filter(user=user, is_active="yes")
# if memberType:
# memberType = memberType.first().memberType
#
# if memberType == "normal":
# context["pdiscount"] = 0
# context["membership_discount_calculate"] = 0
#
# elif memberType == "yearly":
# context["pdiscount"] = discount_limit_handler(DISCOUNT["yearly_member_additional"])
# context["membership_discount_calculate"] = round(float((
# total_amount -
# context[
# "early_bird_calculate"] -
# context[
# "staff_discount_calculate"]) *
# context["pdiscount"] / 100), 2)
#
# elif memberType == "Life Member":
# context["pdiscount"] = discount_limit_handler(DISCOUNT["life_member_additional"])
# context["membership_discount_calculate"] = round(float((
# total_amount -
# context[
# "early_bird_calculate"] -
# context[
# "staff_discount_calculate"]) *
# context["pdiscount"] / 100), 2)
# if not privilegedUser1.objects.filter(user=request.user, is_active="yes").exists():
# context["monthly_membership"] = 1
# # context["membershipNarration"] = discount_limit_handler(DISCOUNT["monthly_member"])
# context["pdiscount"] = 0
# context["membership_discount_calculate"] = 0
# except:
# context["monthly_membership"] = 1
# context["pdiscount"] = 0
# context["membership_discount_calculate"] = 0
#
# get_student_discount = get_discount(request.user.id, total_amount)
# if get_student_discount == 0:
# context["student_discount"] = 0
# context["student_discount_calculate"] = 0
# else:
# context["student_discount"] = get_student_discount
# context["student_discount_calculate"] = round(float((total_amount -
# context["early_bird_calculate"] -
# context["staff_discount_calculate"] -
# context["membership_discount_calculate"]) *
# context["student_discount"] / 100), 2)
#
# context["Total_discount"] = round(float(
# context["early_bird_calculate"] + context["staff_discount_calculate"] +
# context["membership_discount_calculate"] + context["student_discount_calculate"]), 2)
# context["remaining_amount"] = round(float(total_amount - context["Total_discount"]), 2)
# context["net_service_charge"] = round(
# float(context["remaining_amount"]), 2)
# # GST
# context["gst"] = discount_limit_handler(DISCOUNT["gst"])
# context["gst_calculate"] = round(float(context["remaining_amount"] * context["gst"] / 100), 2)
# context["net_payable"] = round(float(context["remaining_amount"] + context["gst_calculate"]), 2)
# print(context)
pricelist = centralPayment_get_discounts(request, total_amount)
print("pricelist", pricelist)
# context["early_bird_discount"] = discount_limit_handler(DISCOUNT["early_bird"])
context["subtotal"] = round(total_amount, 2)
context["early_bird_calculate"] = pricelist["early_bird_calculate"]
context["staff_discount_calculate"] = pricelist["staff_discount_calculate"]
context["membership_discount_calculate"] = pricelist["membership_discount_calculate"]
context["student_discount_calculate"] = pricelist["student_discount_calculate"]
if int(pricelist['student_discount_calculate']) > 0:
request.session['student_discount_calculate'] = "Yes"
else:
request.session['student_discount_calculate'] = "No"
context['Total_discount'] = pricelist['total_discount']
context['remaining_amount'] = pricelist['total_payable']
context["net_service_charge"] = pricelist["net_service_charge"]
context["gst_calculate"] = pricelist["gst_calculate"]
context["net_payable"] = pricelist["gross_payable"]
userrr = User.objects.get(id=request.user.id)
# print("Request is ->", request)
print('privilege users -->',privilegedUser1)
p_users = privilegedUser1.objects.all()
print("All Privilileged users ->", p_users)
print(privilegedUser1.objects.filter(user=47, is_active="yes"),request.user,request.user.id, "->data15555")
print(privilegedUser1.objects.filter(user=47, is_active="yes"), "->data25555")
if not privilegedUser1.objects.filter(user=userrr.id, is_active="yes").exists():
print("dont have monthly membership")
context["monthly_membership"] = 1
# context["membership_discount"] = pricelist["membership_discount_calculate"]
# context["staff_discount"] = pricelist["staff_discount_calculate"]
# context["student_discount"] = pricelist["student_discount_calculate"]
# context["early_bird_discount"] = pricelist["early_bird_calculate"]
#
# context['net_service_charge'] = pricelist['net_service_charge']
# context["total_payable"] = pricelist["total_payable"]
# context["gst_calculate"] = pricelist["gst_calculate"]
# context["gross_payable"] = pricelist["gross_payable"]
# if request.POST.get("centralised") == "yes":
# context["script_title"] = request.POST.get("fileUpload")
# request.session["script_id"] = str(request.POST.get("script_id"))
# # request.session["script_file_path"] = x.script_file
# else:
# context["ndial_src"] = languages2.get(x.nondial_src_language)
# context["dial_src"] = languages2.get(x.dial_src_language)
# context["ndial_dest"] = request.POST.get("nondial_dest_language")
# context["dial_dest"] = request.POST.get("dial_dest_language")
# context["dial_dest_script"] = request.POST.get("dial_dest_script")
# context["nondial_dest_script"] = request.POST.get("non_dial_dest_script")
# context["restrict_to_five"] = "no"
context["lpp_available"] = lpp_available.upper()
context["script_title"] = x.script_title
context["numPages"] = x.numPages
context["ndial_src"] = x.nondial_src_language
context["dial_src"] = x.dial_src_language
context["ndial_dest"] = request.POST.get("non_dial_dest_lang")
context["dial_dest"] = request.POST.get("dial_dest_lang")
context["dial_dest_script"] = request.POST.get("dial_dest_script")
request.session["nondial_dest_language"] = language_2_code.get(request.POST.get("non_dial_dest_lang"))
request.session["nondial_dest_script"] = request.POST.get("non_dial_dest_script")
request.session["dial_dest_language"] = language_2_code.get(request.POST.get("dial_dest_lang"))
request.session["dial_dest_script"] = request.POST.get("dial_dest_script")
# Getting all choices of user regarding Full Dialogues Translation
request.session["full_dialogue_option_choices"] = ",".join(
[str(request.POST.get(f'option{i}') == "on")
for i in range(1, 15)])
# Getting all choices of user regarding Words of Dialogues Translation
request.session["sentence_dialogue_option_choices"] = ",".join(
[str(request.POST.get(f'option{i}') == "on")
for i in range(15, 29)])
# Getting all choices of user regarding translation and transliteration choices of slug, speaker, etc.
request.session["other_option_choices"] = ",".join([str(request.POST.get(f'option{i}') == "on")
for i in range(29, 39)])
if request.POST.get("dual_dialogue_option") == "on":
request.session["dual_dial_script"] = True
request.session["left_dual_dial_lang"] = request.POST.get("dual_left_language")
request.session["left_dual_dial_script"] = request.POST.get("dual_left_script")
if request.POST.get("lpp_vetting") == "on":
request.session["lpp"] = True
# context["numPages"] = numPages
# context["script_title"] = x.script_title
request.session["amount"] = context["net_payable"]
request.session["amount_without_subscrption"] = context["net_service_charge"]
request.session["discount"] = context["Total_discount"]
request.session["subtotal"] = context["subtotal"]
# request.session["script_id"] = x.script_id
# request.session["script_file_path"] = x.script_file_path
# request.session["script_title"] = context["script_title"]
# request.session["dial_dest_language"] = dial_dest_language
# request.session["dial_dest_script"] = request.POST.get("dial_dest_script")
# request.session["nondial_dest_language"] = languages.get(nondial_dest_language)
# request.session["dial_conv_script"] = dial_conv_script
# request.session["dial_src_lang"] = x.dial_src_language
# request.session["non_dial_src_lang"] = x.nondial_src_language
# request.session["dial_src_script"] = x.dial_src_script
# request.session["non_dial_src_script"] = x.nondial_src_script
# request.session["dual_dial_script"] = xdual_dial_script
# request.session["option3"] = opt3
# request.session["option4"] = opt4
# request.session["option5"] = opt5
# request.session["option6"] = opt6
# request.session["numPages"] = numPages
# request.session["nondial_dest_script"] = request.POST.get("non_dial_dest_script")
user = User.objects.get(id=request.user.id)
try:
wall = Wallet.objects.get(user=request.user)
context["balance"] = round(wall.balance, 2)
except:
context["balance"] = -1
with open(f"{basePath}/MNF/json_keys/conversionRates.json") as c:
curr = json.load(c)
try:
rate = curr["rates"]["INR"]
except Exception as e:
print("checkout error", e)
rate = 80
context["rate"] = rate
# for i in ["early_bird","monthly_member","gst","employ_discount","yearly_member","yearly_member_additional","life_member_additional","life_member_year","life_member"]:
#
# print(rf"7878 discounts are {i}", DISCOUNT[i])
str1 = str(datetime.datetime.now()).split("-")
date_at = f'{str1[2][0:2]} - {str1[1]} - {str1[0]}'
context['date_at'] = date_at
try:
cd = centralDatabase.objects.get(user_id=request.user)
name = cd.firstName if cd.firstName else user.username
email_id = cd.email if cd.email else user.email
phone_number = str(cd.countryCode) + str(cd.contact) if cd.contact else "N/A"
address = cd.address if cd.address else "N/A"
except:
name = user.username
email_id = user.email
phone_number = "N/A"
address = "N/A"
context["name"] = name
context["email_id"] = email_id
context["phone_number"] = phone_number
context["address"] = address
print("7878Context is :", context)
return render(request, "conversion/invoice_conversion.html", context)
else:
print("File didn't receive.")
context = {"status": "Failed"}
return JsonResponse(context)
# -> Conversion Checkout
def conversionCheckout(request):
# new payment 8000
set_payment_token(request)
keyID = request.session["keyID"]
keySecret = request.session["keySecret"]
if request.method == "POST":
for key, value in request.session.items():
print('{} => {}'.format(key, value))
if request.POST.get("want_to_be_vetted") == "YES":
request.session["want_to_be_vetted"] = "on"
else:
request.session["want_to_be_vetted"] = request.POST.get(
"want_to_be_vetted")
total_amount = request.session["amount"]
total_amount1 = request.session["subtotal"]
# amount_charged = request.session["amount"]
amount_discount = request.session["discount"]
request.session["pay_with_wallet"] = "no"
request.session["amount_before_pay_wallet"] = total_amount
# is he instituitional student or not
if request.session.get("student_discount_calculate") == "Yes":
from institutional.models import AffiliatedStudent, UnaffiliatedStudent, WaitForInstituteStudent
user = User.objects.get(pk=request.user.id)
if UnaffiliatedStudent.objects.filter(user=user).exists():
user = UnaffiliatedStudent.objects.get(user=user)
if user.free_credits >= total_amount:
user.free_credits -= total_amount
user.save()
context = {
"mode": "Institutional User",
}
return JsonResponse(context)
elif user.free_credits < total_amount:
total_amount -= user.free_credits
user.free_credits = 0
user.save()
elif WaitForInstituteStudent.objects.filter(user=user).exists():
user = WaitForInstituteStudent.objects.get(user=user)
if user.free_credits >= total_amount:
user.free_credits -= total_amount
user.save()
context = {
"mode": "Institutional User",
}
return JsonResponse(context)
elif user.free_credits < total_amount:
total_amount -= user.free_credits
user.free_credits = 0
user.save()
return True
elif AffiliatedStudent.objects.filter(user=user).exists():
user = AffiliatedStudent.objects.get(user=user)
if user.free_credits >= total_amount:
user.free_credits -= total_amount
user.save()
context = {
"mode": "Institutional User",
}
return JsonResponse(context)
elif user.free_credits < total_amount:
total_amount -= user.free_credits
user.free_credits = 0
user.save()
try:
print("pay_wallet it is", request.POST.get("pay_wallet"))
if request.POST.get("pay_wallet") == "true":
request.session["pay_with_wallet"] = "yes"
with open(f"{basePath}/MNF/json_keys/conversionRates.json") as c:
curr = json.load(c)
print(curr["rates"]["INR"])
try:
rate = curr["rates"]["INR"]
except Exception as e:
print("checkout error", e)
rate = 80
print("Checking Wallet")
wall = Wallet.objects.get(user=request.user)
print("this is walet", wall.balance)
print(wall.balance)
if wall.balance >= (total_amount * rate):
print("wallet if hai")
# wall.balance = wall.balance - (total_amount * rate)
# wall.save()
request.session["pay_wallet_deduction"] = round(total_amount * rate, 2)
total_amount = 0
else:
print("wallet else hai")
# wall.balance = 0
# wall.save()
request.session["pay_wallet_deduction"] = round(wall.balance, 2)
total_amount = round((round(total_amount * rate, 2) - round(wall.balance, 2)) / rate, 2)
# request.session["fbalance"] = float(
# wall.balance) - float(balance*rate)
# request.session["amount"] = total_amount
# total_amount = request.session["amount"]
except Exception as e:
print("Error is:",e)
pass
request.session["amount"] = total_amount
services_used = 2 if request.session["want_to_be_vetted"] == "on" else 1
context = create_indent(request, 'Conversion', str(
request.session["script_id"]), services_used, '', total_amount1, total_amount, amount_discount)
print("Create indent 9987", context)
for key, value in request.session.items():
print('{} => {}'.format(key, value))
print(str(request.session["script_id"]))
# instance = MNFScriptDatabase.objects.get(script_id=str(request.session["script_id"]))
with open(f"{basePath}/MNF/json_keys/conversionRates.json") as c:
curr = json.load(c)
try:
rate = curr["rates"]["INR"]
except Exception as e:
rate = 80
request.session["CurrencyRate"] = rate
centralPayment_instance = CentralPayment.objects.get(
id=context["central_pay_id"])
# handle razor pay gateway →
if "orderId" in context:
# instance.payment_order_id = context["orderId"]
# instance.central_payment_id = context["central_pay_id"]
# instance.save() # save central payment details in your database
request.session["payment_order_id"] = context["orderId"]
request.session["central_payment_id"] = context["central_pay_id"]
pid = centralPayment_instance.order_id
amtINR = round(centralPayment_instance.amount_charged * rate, 2)
context = {
"mode": "RazorPay",
"pk": keyID,
"amtINR": amtINR,
"pid": pid,
"amount": centralPayment_instance.amount_charged,
}
return JsonResponse(context)
# return render(request, "conversion/checkoutC_RazorPay.html", context)
# handle stripe gateway →
elif "client_secret" in context:
# save central payment details in your database
request.session["payment_order_id"] = context["client_secret"]
request.session["central_payment_id"] = context["central_pay_id"]
amtINR = round(centralPayment_instance.amount_charged * rate, 2)
context = {
"mode": "Stripe",
"pk": context["pub_key"],
"total_amount": centralPayment_instance.amount_charged,
"secret_key": context["client_secret"],
"amtINR": amtINR,
}
return JsonResponse(context)
# handle corporate profile →
elif "monthly_user" in context:
# instance.payment_order_id = "corporate profile"
# instance.central_payment_id = "corporate profile"
# instance.save()
# script_id = request.session["script_id"]
# script_title = request.session["script_title"]
# script_file_path = request.session["script_file_path"]
# dial_conv_script = request.session["dial_conv_script"]
# nondial_dest_language = request.session["nondial_dest_language"]
# dial_dest_language = request.session["dial_dest_language"]
# dial_dest_script = request.session["dial_dest_script"]
# dial_src_lang = request.session["dial_src_lang"]
# non_dial_src_lang = request.session["non_dial_src_lang"]
# dial_src_script = request.session["dial_src_script"]
# non_dial_src_script = request.session["non_dial_src_script"]
# dual_dial_script = request.session["dual_dial_script"]
# nondial_dest_script = request.session["nondial_dest_script"]
# if request.session.get("want_to_be_vetted") != "NO":
# total_amount = request.session["lppamount"]
# else:
# total_amount = request.session["amount"]
# to_be_vetted_by_lpp = request.session["want_to_be_vetted"]
# option3 = request.session["option3"]
# option4 = request.session["option4"]
# option5 = request.session["option5"]
# option6 = request.session["option6"]
# # payment_intent_id = request.session["payment_intent_id"]
# # pi = stripe.PaymentIntent.retrieve(payment_intent_id)
# try:
# s = MNFScriptDatabase.objects.get(user_id = request.user, script_id = script_id)
# except:
# s = MNFScriptDatabase()
# s.user_id = request.user
# s.script_id = script_id
# s.script_title = script_title
# s.author_name = request.user.first_name
# # s.dial_dest_language = dial_dest_language
# # s.dial_dest_script = dial_dest_script
# # s.nondial_dest_language = nondial_dest_language
# # s.dual_dial_script = dual_dial_script
# s.script_file_path = script_file_path
# # save central payment details in your database
# # s.payment_order_id = "monthly_user"
# # s.central_payment_id = context["central_pay_id"]
# # s.payment_intent_id = payment_intent_id
# s.nondial_src_script = non_dial_src_script
# s.dial_src_script = dial_src_script
# s.dial_src_language = dial_src_lang
# s.nondial_src_language = non_dial_src_lang
# # s.nondial_dest_script = nondial_dest_script
# s.save()
#
# translation_instance = ScriptTranslations()
# translation_instance.user_id = request.user
# translation_instance.script_link_id = s
# translation_instance.nondial_dest_language = nondial_dest_language
# translation_instance.nondial_dest_script = nondial_dest_script
# translation_instance.dial_dest_language = language_2_code[str(dial_dest_language)]
# translation_instance.dial_dest_script = dial_dest_script
# translation_instance.dual_dial_script = dual_dial_script
# translation_instance.payment_order_id = "monthly_user"
request.session['central_pay_id'] = context["central_pay_id"]
context = {
"mode": "Corporate User",
}
# return redirect('conversion')
return JsonResponse(context)
# return render(request, "conversion/thanksconversion.html", context)
# if request.POST.get("country") == "IN":
#
# # try: -> Old WAy of Getting Conversion Rates between Currencies
# # c = CurrencyRates()
# # rate = c.get_rate("USD", "INR")
# # except:
# # rate = 80
# with open(f"{basePath}/MNF/json_keys/conversionRates.json") as c:
# curr = json.load(c)
# print(curr["rates"]["INR"])
# try:
# rate = curr["rates"]["INR"]
# print(rate, " : Latest rates 30sep")
# # c = CurrencyRates()
# # rate = c.get_rate("USD", str(currency.upper()))
# except Exception as e:
# print("checkout error", e)
# rate = 80
#
# amtINR = round(float(float(total_amount) * rate), 2)
# client = razorpay.Client(auth=(keyID, keySecret))
# payment_intent = client.order.create(
# {
# "amount": int(float(total_amount) * 100 * rate),
# "currency": "INR",
# "payment": {
# "capture": "automatic",
# "capture_options": {"refund_speed": "normal"},
# },
# }
# )
# else:
# try: -> Old WAy of Getting Conversion Rates between Currencies
# c = CurrencyRates()
# rate = c.get_rate("USD", "INR")
# except:
# rate = 80
# with open(f"{basePath}/MNF/json_keys/conversionRates.json") as c:
# curr = json.load(c)
# print(curr["rates"]["INR"])
# try:
# rate = curr["rates"]["INR"]
# print(rate, " : Latest rates 30sep")
# # c = CurrencyRates()
# # rate = c.get_rate("USD", str(currency.upper()))
# except Exception as e:
# print("checkout error", e)
# rate = 80
#
# amtINR = round(float(float(total_amount) * rate), 2)
# payment_intent = stripe.PaymentIntent.create(
# amount=int(float(total_amount) * 100 * rate),
# currency="INR",
# payment_method_types=["card"],
# )
# request.session["CurrencyRate"] = rate
# request.session["payment_intent_id"] = payment_intent.id
# context = {
# "pk": STRIPE_PUB_KEY,
# "total_amount": total_amount,
# "amtINR": amtINR,
# }
# return render(request, "conversion/checkoutC.html", context)
# ppt checkout
# -> Conversion Checkout
def pptCheckout(request):
set_payment_token(request)
keyID = request.session["keyID"]
keySecret = request.session["keySecret"]
if request.method == "POST":
if request.POST.get("want_to_be_vetted") == "yes":
# total_amount = request.session["pptamount"]
request.session["want_to_be_vetted"] = "on"
else:
request.session["want_to_be_vetted"] = "off"
total_amount = request.session['amount']
total_amount1 = request.session['subtotal']
amount_discount = request.session["discount"]
request.session["pay_with_wallet"] = "no"
request.session["amount_before_pay_wallet"] = total_amount
try:
if request.POST.get("pay_wallet") == "on":
request.session["pay_with_wallet"] = "yes"
with open(f"{basePath}/MNF/json_keys/conversionRates.json") as c:
curr = json.load(c)
print(curr["rates"]["INR"])
try:
rate = curr["rates"]["INR"]
except Exception as e:
print("checkout error", e)
rate = 80
wall = Wallet.objects.get(user=request.user)
print("this is walet", wall.balance)
print(wall.balance)
if wall.balance >= (total_amount * rate):
print("wallet if hai")
request.session["pay_wallet_deduction"] = round(total_amount * rate, 2)
total_amount = 0
else:
print("wallet else hai")
request.session["pay_wallet_deduction"] = round(wall.balance, 2)
total_amount = round((round(total_amount * rate, 2) - round(wall.balance, 2)) / rate, 2)
# balance = float(request.POST["balance"])
# payable = float(request.POST["payable"])
# wall = Wallet.objects.get(user=request.user)
# request.session["fbalance"] = float(
# wall.balance) - float(balance*rate)
# wall.save()
# request.session["amount"] = payable
# total_amount = request.session["amount"]
except Exception as e:
print("checkout error", e)
pass
# call central payment function --> create indent
# Next follow central payment docs...
# if indian --> orderID --> razorpay gateway
# non-indian --> client secret --> stripe
request.session["amount"] = total_amount
# total_amount1 = request.session["total_amount1"]
# amount_charged = request.session["amount1"]
# amount_discount = request.session["discount1"]
services_used = 2 if request.session["want_to_be_vetted"] == "on" else 1
context = create_indent(request, 'Conversion', str(request.session["ppt_id"]), services_used, '',
total_amount1, total_amount, amount_discount)
print("Create indent bhaalu aa rhaha hai 7878", context)
# instance = MNFScriptDatabase.objects.get(script_id=str(request.session["script_id"]))
with open(f"{basePath}/MNF/json_keys/conversionRates.json") as c:
curr = json.load(c)
try:
rate = curr["rates"]["INR"]
except Exception as e:
rate = 80
request.session["CurrencyRate"] = rate
centralPayment_instance = CentralPayment.objects.get(
id=context["central_pay_id"])
# handle razor pay gateway →
if "orderId" in context:
# instance.payment_order_id = context["orderId"]
# instance.central_payment_id = context["central_pay_id"]
# instance.save() # save central payment details in your database
request.session["payment_order_id"] = context["orderId"]
request.session["central_payment_id"] = context["central_pay_id"]
pid = centralPayment_instance.order_id
amtINR = centralPayment_instance.amount_charged * rate
context = {
"mode": "RazorPay",
"pk": keyID,
"amtINR": amtINR,
"pid": pid,
"amount": centralPayment_instance.amount_charged,
}
return JsonResponse(context)
# return render(request, "conversion/checkoutPPT_RazorPay.html", context)
# handle stripe gateway →
elif "client_secret" in context:
request.session["payment_order_id"] = context[
"client_secret"] # save central payment details in your database
request.session["central_payment_id"] = context["central_pay_id"]
amtINR = centralPayment_instance.amount_charged * rate
context = {
"mode": "Stripe",
"pk": context["pub_key"],
"total_amount": centralPayment_instance.amount_charged,
"secret_key": context["client_secret"],
"amtINR": amtINR,
}
return JsonResponse(context)
# return render(request, "conversion/checkoutPPT_Stripe.html", context)
# handle corporate profile →
elif "monthly_user" in context:
ppt_instance = pptconversion.objects.get(
ppt_id=request.session["ppt_id"])
ppt_instance.central_payment_id = context["central_pay_id"]
ppt_instance.payment_order_id = "monthly_user"
ppt_instance.save()
sendmail(to_email=[ppt_instance.user_id.email], email_code='CP4')
sendmail(to_email=[ppt_instance.user_id.email], email_code='CP10')
ppt_conversion(request.session["ppt_id"], request).start()
sendmail(to_email=[ppt_instance.user_id.email], email_code='CP9')
print('line---(1527)')
print('is the email working for ppt')
context = {
"mode": "Corporate User"
}
return JsonResponse(context)
# return render(request, "conversion/thanksppt.html")
# instance.payment_order_id = "corporate profile"
# instance.central_payment_id = "corporate profile"
# instance.save()
# return render(request, "conversion/thanksbook.html", {"book_id": request.session["book_id"]})
# context = create_indent(request, 'Convert a ppt', sr.data["ppt_id"], 1, '', amount, sr.data["amount"], sr.data["discount"])
# instance
# # if request.POST.get("country") == "IN":
# if "orderId" in context:
# return render(request, "conversion/checkoutPPT_RazorPay.html", context)
# elif "client_secret" in context:
# return render(request, "conversion/checkoutPPT_Stripe.html", context)
# elif "monthly_user" in context:
# pass
# else:
# return Response({"message": "invalid request!"}, status=status.HTTP_400_BAD_REQUEST)
# if request.POST.get("country") == "IN":
# # try: -> Old WAy of Getting Conversion Rates between Currencies
# # c = CurrencyRates()
# # rate = c.get_rate("USD", "INR")
# # except:
# # rate = 80
# with open(f"{basePath}/MNF/json_keys/conversionRates.json") as c:
# curr = json.load(c)
# print(curr["rates"]["INR"])
# try:
# rate = curr["rates"]["INR"]
# print(rate, " : Latest rates 30sep")
# # c = CurrencyRates()
# # rate = c.get_rate("USD", str(currency.upper()))
# except Exception as e:
# print("checkout error", e)
# rate = 80
# amtINR = round(float(float(total_amount) * rate), 2)
# client = razorpay.Client(auth=(keyID, keySecret))
# payment_intent = client.order.create(
# {
# "amount": int(float(total_amount) * 100 * rate),
# "currency": "INR",
# "payment": {
# "capture": "automatic",
# "capture_options": {"refund_speed": "normal"},
# },
# }
# )
# request.session["CurrencyRate"] = rate
# pid = payment_intent["id"]
# context = {
# "pk": keyID,
# "amtINR": amtINR,
# "pid": pid,
# "amount": total_amount,
# }
# return render(request, "conversion/checkoutPPT_RazorPay.html", context)
# else:
# # try: -> Old WAy of Getting Conversion Rates between Currencies
# # c = CurrencyRates()
# # rate = c.get_rate("USD", "INR")
# # except:
# # rate = 80
# with open(f"{basePath}/MNF/json_keys/conversionRates.json") as c:
# curr = json.load(c)
# print(curr["rates"]["INR"])
# try:
# rate = curr["rates"]["INR"]
# print(rate, " : Latest rates 30sep")
# # c = CurrencyRates()
# # rate = c.get_rate("USD", str(currency.upper()))
# except Exception as e:
# print("checkout error", e)
# rate = 80
# amtINR = round(float(float(total_amount) * rate), 2)
# payment_intent = stripe.PaymentIntent.create(
# amount=int(float(total_amount) * 100 * rate),
# currency="INR",
# payment_method_types=["card"],
# )
# request.session["CurrencyRate"] = rate
# request.session["payment_intent_id"] = payment_intent.id
# context = {
# "pk": STRIPE_PUB_KEY,
# "total_amount": total_amount,
# "amtINR": amtINR,
# }
# return render(request, "conversion/checkoutPPT_Stripe.html", context)
# return render(request, "conversion/conversion.html")
# "16 Nov file path", output_dir
# "16 Nov part 2 inside if"
# Path DNE inside if
# "Path 16 Nov", output_dir
# Class object instantiated
# -> Conversion Checkout
@login_required(login_url="/PersonalLogin-2")
def conversioncard(request):
if request.method == "POST":
# payment_method_id = request.POST["payment_method_id"]
# payment_intent_id = request.session["payment_intent_id"]
#
# customer = stripe.Customer.create(
# email=request.user.email,
# payment_method=payment_method_id,
# invoice_settings={"default_payment_method": payment_method_id},
# )
#
# stripe.PaymentIntent.modify(
# payment_intent_id, payment_method=payment_method_id, customer=customer.id
# )
# ret = stripe.PaymentIntent.confirm(payment_intent_id)
# pi = stripe.PaymentIntent.retrieve(payment_intent_id)
# if ret.status == "requires_action":
customer = stripe.Customer.create(
email=request.user.email,
)
payment_intent = stripe.PaymentIntent.create(
amount=int(float(total_amount) * 100 * rate),
currency="INR",
automatic_payment_methods={"enabled": True},
customer=customer.id,
)
pid = payment_intent.id
request.session["payment_intent_id"] = pid
context = {
"pid": pid,
"amtINR": amtINR,
"secret_key": payment_intent.client_secret,
"total_amount": total_amount,
"STRIPE_PUBLISHABLE_KEY": STRIPE_PUB_KEY,
"pk": STRIPE_PUB_KEY,
}
# context = {
# "pk": STRIPE_PUB_KEY,
# "pid":,
# "payment_intent_secret": request.session["payment_order_id"],
# }
return render(request, "conversion/3dsecuredConversion.html", context)
# return render(request, "payments/paymentdone.html")
@login_required(login_url="/PersonalLogin-2")
def Bookcard(request):
if request.method == "POST":
payment_method_id = request.POST["payment_method_id"]
payment_intent_id = request.session["payment_intent_id"]
customer = stripe.Customer.create(
email=request.user.email,
payment_method=payment_method_id,
invoice_settings={"default_payment_method": payment_method_id},
)
stripe.PaymentIntent.modify(
payment_intent_id, payment_method=payment_method_id, customer=customer.id
)
ret = stripe.PaymentIntent.confirm(payment_intent_id)
pi = stripe.PaymentIntent.retrieve(payment_intent_id)
if ret.status == "requires_action":
context = {
"pk": STRIPE_PUB_KEY,
"payment_intent_secret": pi.client_secret,
}
return render(request, "conversion/3dsecuredBook.html", context)
return render(request, "payments/paymentdone.html")
def paymentDoneC_corporate(request):
if request.method == "GET":
script_id = request.session["script_id"]
s = MNFScriptDatabase.objects.get(user_id=request.user, script_id=script_id)
translation_instance = ScriptTranslations()
translation_instance.user_id = request.user
translation_instance.script_link_id = s
translation_instance.nondial_dest_language = request.session["nondial_dest_language"]
translation_instance.nondial_dest_script = request.session["nondial_dest_script"]
translation_instance.dial_dest_language = request.session["dial_dest_language"]
translation_instance.dial_dest_script = request.session["dial_dest_script"]
# save central payment details in your database
translation_instance.payment_order_id = "monthly_user"
translation_instance.central_payment_id = request.session["central_pay_id"]
# Getting all choices of user regarding Full Dialogues Translation
translation_instance.full_dialogue_option_choices = request.session["full_dialogue_option_choices"]
# Getting all choices of user regarding Words of Dialogues Translation
translation_instance.sentence_dialogue_option_choices = request.session["sentence_dialogue_option_choices"]
# Getting all choices of user regarding translation and transliteration choices of slug, speaker, etc.
translation_instance.other_option_choices = request.session["other_option_choices"]
if request.session.get("dual_dial_script"):
translation_instance.dual_dial_script = request.session["dual_dial_script"]
translation_instance.left_dual_dial_lang = request.session["left_dual_dial_lang"]
translation_instance.left_dual_dial_script = request.session["left_dual_dial_script"]
if request.session.get("lpp"):
translation_instance.lpp = request.session["lpp"]
translation_instance.save()
print("saving")
request.session['translation_id'] = str(translation_instance.translation_id)
return render(request, "conversion/thanksconversion.html", {})
def paymentDoneC_Institutional(request):
if request.method == "GET":
script_id = request.session["script_id"]
s = MNFScriptDatabase.objects.get(user_id=request.user, script_id=script_id)
translation_instance = ScriptTranslations()
translation_instance.user_id = request.user
translation_instance.script_link_id = s
translation_instance.nondial_dest_language = request.session["nondial_dest_language"]
translation_instance.nondial_dest_script = request.session["nondial_dest_script"]
translation_instance.dial_dest_language = request.session["dial_dest_language"]
translation_instance.dial_dest_script = request.session["dial_dest_script"]
# save central payment details in your database
translation_instance.payment_order_id = "Institutional User"
# translation_instance.central_payment_id = request.session["central_pay_id"]
# Getting all choices of user regarding Full Dialogues Translation
translation_instance.full_dialogue_option_choices = request.session["full_dialogue_option_choices"]
# Getting all choices of user regarding Words of Dialogues Translation
translation_instance.sentence_dialogue_option_choices = request.session["sentence_dialogue_option_choices"]
# Getting all choices of user regarding translation and transliteration choices of slug, speaker, etc.
translation_instance.other_option_choices = request.session["other_option_choices"]
if request.session.get("dual_dial_script"):
translation_instance.dual_dial_script = request.session["dual_dial_script"]
translation_instance.left_dual_dial_lang = request.session["left_dual_dial_lang"]
translation_instance.left_dual_dial_script = request.session["left_dual_dial_script"]
if request.session.get("lpp"):
translation_instance.lpp = request.session["lpp"]
translation_instance.save()
print("saving")
request.session['translation_id'] = str(translation_instance.translation_id)
return render(request, "conversion/thanksconversion.html", {})
# -> Conversion Stripe Payment Done Message
def paymentDoneC(request):
if request.method == "GET":
script_id = request.session["script_id"]
# script_title = request.session["script_title"]
# script_file_path = request.session["script_file_path"]
# dial_conv_script = request.session["dial_conv_script"]
# nondial_dest_language = request.session["nondial_dest_language"]
# dial_dest_language = request.session["dial_dest_language"]
# dial_dest_script = request.session["dial_dest_script"]
# dial_src_lang = request.session["dial_src_lang"]
# non_dial_src_lang = request.session["non_dial_src_lang"]
# dial_src_script = request.session["dial_src_script"]
# non_dial_src_script = request.session["non_dial_src_script"]
# dual_dial_script = request.session["dual_dial_script"]
# nondial_dest_script = request.session["nondial_dest_script"]
# if request.session.get("want_to_be_vetted"):
# total_amount = request.session["amount"]
# else:
# total_amount = request.session["amount"]
# to_be_vetted_by_lpp = request.session["want_to_be_vetted"]
# option3 = request.session["option3"]
# option4 = request.session["option4"]
# option5 = request.session["option5"]
# option6 = request.session["option6"]
# payment_intent_id = request.session["payment_intent_id"]
# pi = stripe.PaymentIntent.retrieve(payment_intent_id)
print("all get 8989 variables", request.GET.items())
for key, value in request.GET.items():
print(rf'{key}: {value}')
response = {
"id": request.GET.get("payment_intent"),
"client_secret": request.GET.get("payment_intent_client_secret"),
"status": request.GET.get("redirect_status"),
}
callback_content = callback(response, request)
if callback_content['payment_status'] == "success":
if request.session["pay_with_wallet"] == "yes":
# deduction_for_sep_wall(request)
wall = Wallet.objects.get(user=request.user)
# for key, value in request.session.items():
# print('{} => {}'.format(key, value))
print("----------------amount", request.session["pay_wallet_deduction"])
print("----------------rate", request.session["CurrencyRate"])
print("final balance", round(wall.balance, 2) - (
round(request.session["pay_wallet_deduction"], 2)))
wall.balance = round(wall.balance, 2) - (
round(request.session["pay_wallet_deduction"], 2))
wall.save()
# c = conversionPayment()
# try:
s = MNFScriptDatabase.objects.get(user_id=request.user, script_id=script_id)
# except:
# s = MNFScriptDatabase()
# s.user_id = request.user
# s.script_id = script_id
# s.user_id = request.user
# s.script_id = script_id
# s.script_title = script_title
# s.author_name = request.user.first_name
# s.dial_dest_language = dial_dest_language
# s.dial_dest_script = dial_dest_script
# s.nondial_dest_language = nondial_dest_language
# s.dual_dial_script = dual_dial_script
# s.script_file_path = script_file_path
# save central payment details in your database
# s.payment_order_id = request.session["payment_order_id"]
# s.central_payment_id = request.session["central_payment_id"]
# s.payment_intent_id = payment_intent_id
# s.nondial_src_script = non_dial_src_script
# s.dial_src_script = dial_src_script
# s.dial_src_language = dial_src_lang
# s.nondial_src_language = non_dial_src_lang
# s.nondial_dest_script = nondial_dest_script
# try:
# if request.session["is_juggernaut_used"]:
# s.is_juggernaut_used = True
# s.languages_juggernaut = request.session['languages_juggernaut']
# except:
# pass
# s.save()
# try:
# if request.session["juggernaut_pages_deduction"]:
# update_juggernaut(request, user_id=request.user.id, service_name="conversion",
# conversion_pages=int(request.session["juggernaut_pages_deduction"]), associated_project=s, translation_language=str(dial_dest_language))
# except Exception as e:
# print("Error is: ", e)
translation_instance = ScriptTranslations()
translation_instance.user_id = request.user
translation_instance.script_link_id = s
translation_instance.nondial_dest_language = request.session["nondial_dest_language"]
translation_instance.nondial_dest_script = request.session["nondial_dest_script"]
translation_instance.dial_dest_language = request.session["dial_dest_language"]
translation_instance.dial_dest_script = request.session["dial_dest_script"]
# Getting all choices of user regarding Full Dialogues Translation
translation_instance.full_dialogue_option_choices = request.session["full_dialogue_option_choices"]
# Getting all choices of user regarding Words of Dialogues Translation
translation_instance.sentence_dialogue_option_choices = request.session["sentence_dialogue_option_choices"]
# Getting all choices of user regarding translation and transliteration choices of slug, speaker, etc.
translation_instance.other_option_choices = request.session["other_option_choices"]
if request.session.get("dual_dial_script"):
translation_instance.dual_dial_script = request.session["dual_dial_script"]
translation_instance.left_dual_dial_lang = request.session["left_dual_dial_lang"]
translation_instance.left_dual_dial_script = request.session["left_dual_dial_script"]
if request.session.get("lpp"):
translation_instance.lpp = request.session["lpp"]
# save central payment details in your database
translation_instance.payment_order_id = request.session["payment_order_id"]
translation_instance.central_payment_id = request.session["central_payment_id"]
translation_instance.save()
print("saving")
request.session['translation_id'] = str(translation_instance.translation_id)
# -----------Adding Details to payment Details--------------------------
# currencyrate = request.session["CurrencyRate"]
# user_id = request.user
# payment_id = payment_intent_id
# services_used = "Conversion"
# script_info = s
# number_of_pages = request.session["numPages"]
# total_amounts = round(
# (request.session["numPages"] *
# CONVERSION_PER_PAGE * currencyrate),
# 2,
# )
# discount = round((request.session["discount"] * currencyrate), 2)
# amount_charged = round((total_amount * currencyrate), 2)
# gateway_fee = round(
# ((STRIPE_PLATFORM_FEE / 100) * amount_charged), 2)
# currency = "INR"
# pay_method = "Card"
# payment_status = "Success"
# payment_gateway = "Stripe"
# PaymentData.objects.create(
# user_id=user_id,
# services_used=services_used,
# payment_id=payment_id,
# script_info=script_info,
# amount_charged=amount_charged,
# total_amount=total_amounts,
# number_of_pages=number_of_pages,
# gateway_fee=gateway_fee,
# discount=discount,
# currency=currency,
# pay_method=pay_method,
# payment_status=payment_status,
# payment_gateway=payment_gateway,
# )
# c.pid = privilegedUser1.objects.get(user= request.user)
# c.script_title = script_title
# c.script_id = script_id
# c.to_be_vetted_by_lpp = to_be_vetted_by_lpp
# c.payment_intent_id = payment_intent_id
# c.total_amount = str(total_amount)
# c.script_file_path = script_file_path
# c.has_paid = 'yes'
# c.save()
context = {
"script_id": script_id,
}
to = request.user.email
key_value = {
"User": request.user.username,
}
sendmail(to_email=[to], email_code="PP19", key_value=key_value)
return render(request, "conversion/thanksconversion.html", context)
else:
subject = "Something really went wrong"
# from_email = settings.EMAIL_HOST_USER
# to = request.user.email
# context_2 = {
# "Name": request.user.email,
# "service_name": "Conversion",
# }
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR24.html", context_2, from_email)
to = request.user.email
key_value = {
"service_name": "Conversion",
}
sendmail(to_email=[to], email_code="CP11", key_value=key_value)
# message = render_to_string('payment/templates/payments/MR24.html', context_2)
#
#
# # password = emails_creadentials.objects.get(email="noreply@mynextfilm.ai")
# connection = get_connection(host="smtp.gmail.com", port=587, username="noreply@mynextfilm.ai",
# password="iiby yciy jdux fslv", use_tls=True)
# to_email = request.user.email
# email = EmailMessage(subject, message, to=[to_email], connection=connection)
# email.send()
return render(request, "payments/failed.html")
# -> Conversion Razorpay Payment Done Message
def paymentDoneC_RazorPay(request):
print("po")
print("PAyment Done Razorpay -> ", request.POST)
# print("PAyment Done Razorpay -> ", request.POST.data, "444")
# keyID = request.session["keyID"]
# keySecret = request.session["keySecret"]
if request.method == "POST":
script_id = request.session["script_id"]
# script_title = request.session["script_title"]
# script_file_path = request.session["script_file_path"]
# dial_conv_script = request.session["dial_conv_script"]
# nondial_dest_language = request.session["nondial_dest_language"]
# dial_dest_language = request.session["dial_dest_language"]
# dial_dest_script = request.session["dial_dest_script"]
# dial_src_lang = request.session["dial_src_lang"]
# non_dial_src_lang = request.session["non_dial_src_lang"]
# dial_src_script = request.session["dial_src_script"]
# dual_dial_script = request.session["dual_dial_script"]
# non_dial_src_script = request.session["non_dial_src_script"]
# nondial_dest_script = request.session["nondial_dest_script"]
# if request.session.get("want_to_be_vetted"):
# total_amount = request.session["amount"]
# else:
# total_amount = request.session["amount"]
# to_be_vetted_by_lpp = request.session["want_to_be_vetted"]
# option3 = request.session["option3"]
# option4 = request.session["option4"]
# option5 = request.session["option5"]
# option6 = request.session["option6"]
# razorpay_order_id = request.POST["razorpay_order_id"]
# razorpay_payment_id = request.POST["razorpay_payment_id"]
# razorpay_signature = request.POST["razorpay_signature"]
# client = razorpay.Client(auth=(keyID, keySecret))
# params_dict = {
# "razorpay_order_id": razorpay_order_id,
# "razorpay_payment_id": razorpay_payment_id,
# "razorpay_signature": razorpay_signature,
# }
# try:
# client.utility.verify_payment_signature(params_dict)
callback_context = callback(request.POST, request)
if callback_context['payment_status'] != 'success':
subject = "Something really went wrong"
# from_email = settings.EMAIL_HOST_USER
# to_ema = request.user.email
# context_2 = {
# "Name": request.user.email,
# "service_name": "Conversion",
# }
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR24.html", context_2, from_email)
# message = render_to_string('payment/templates/payments/MR24.html', context_2)
#
#
# # password = emails_creadentials.objects.get(email="noreply@mynextfilm.ai")
# connection = get_connection(host="smtp.gmail.com", port=587, username="noreply@mynextfilm.ai",
# password="iiby yciy jdux fslv", use_tls=True)
# to_email = email
# email = EmailMessage(subject, message, to=[to_email], connection=connection)
# email.send()
to = request.user.email
key_value = {
"service_name": "Conversion",
}
sendmail(to_email=[to], email_code="CP11", key_value=key_value)
return render(request, "payments/failed.html")
if request.session["pay_with_wallet"] == "yes":
# deduction_for_sep_wall(request)
wall = Wallet.objects.get(user=request.user)
# for key, value in request.session.items():
# print('{} => {}'.format(key, value))
print("----------------amount", request.session["pay_wallet_deduction"])
print("----------------rate", request.session["CurrencyRate"])
print("final balance", round(wall.balance, 2) - (round(request.session["pay_wallet_deduction"], 2)))
wall.balance = round(wall.balance, 2) - (round(request.session["pay_wallet_deduction"], 2))
wall.save()
# c = conversionPayment()
s = MNFScriptDatabase.objects.get(user_id=request.user, script_id=script_id)
# save central payment details in your database
# s.payment_order_id = request.session["payment_order_id"]
# # save central payment details in your database
# s.central_payment_id = request.session["central_payment_id"]
# try:
# if request.session["is_juggernaut_used"]:
# s.is_juggernaut_used = True
# s.languages_juggernaut = request.session['languages_juggernaut']
# except:
# pass
translation_instance = ScriptTranslations()
translation_instance.user_id = request.user
translation_instance.script_link_id = s
translation_instance.nondial_dest_language = request.session["nondial_dest_language"]
translation_instance.nondial_dest_script = request.session["nondial_dest_script"]
translation_instance.dial_dest_language = request.session["dial_dest_language"]
translation_instance.dial_dest_script = request.session["dial_dest_script"]
# Getting all choices of user regarding Full Dialogues Translation
translation_instance.full_dialogue_option_choices = request.session["full_dialogue_option_choices"]
# Getting all choices of user regarding Words of Dialogues Translation
translation_instance.sentence_dialogue_option_choices = request.session["sentence_dialogue_option_choices"]
# Getting all choices of user regarding translation and transliteration choices of slug, speaker, etc.
translation_instance.other_option_choices = request.session["other_option_choices"]
if request.session.get("dual_dial_script"):
translation_instance.dual_dial_script = request.session["dual_dial_script"]
translation_instance.left_dual_dial_lang = request.session["left_dual_dial_lang"]
translation_instance.left_dual_dial_script = request.session["left_dual_dial_script"]
if request.session.get("lpp"):
translation_instance.lpp = request.session["lpp"]
# save central payment details in your database
translation_instance.payment_order_id = request.session["payment_order_id"]
translation_instance.central_payment_id = request.session["central_payment_id"]
translation_instance.save()
print("saving")
request.session['translation_id'] = str(translation_instance.translation_id)
# c.pid = privilegedUser1.objects.get(user= request.user)
# c.script_title = script_title
# c.script_id = script_id
# c.to_be_vetted_by_lpp = to_be_vetted_by_lpp
# c.payment_intent_id = razorpay_payment_id
# c.total_amount = str(total_amount)
# c.script_file_path = script_file_path
# c.has_paid = 'yes'
# c.save()
# request.session["payment_order_id"] = context["orderId"]
# request.session["central_payment_id"]
# payFetch = client.payment.fetch(razorpay_payment_id,({'expand[]':'card'}))
# if client.payment.fetch(razorpay_payment_id, {"expand[]": "card"}):
# pay_method = "CARD"
# else:
# pay_method = "NOTCard"
# # -----------Adding Details to payment Details--------------------------
# currencyrate = request.session["CurrencyRate"]
# user_id = request.user
# payment_id = razorpay_payment_id
# services_used = "Conversion"
# script_info = s
# total_amounts = round(
# (request.session["numPages"] * CONVERSION_PER_PAGE * currencyrate),
# 2,
# )
# discount = round((request.session["discount"] * currencyrate), 2)
# amount_charged = round((total_amount * currencyrate), 2)
# gateway_fee = round(
# ((RAZORPAY_PLATFORM_FEE / 100) * amount_charged), 2)
# currency = "INR"
# # pay_method = 'NOTCard'
# payment_status = "Success"
# payment_gateway = "RazorPay"
# number_of_pages = request.session["numPages"]
# print("totalamount:", total_amounts)
# print("amountcharge:", amount_charged)
# print("discount:", discount)
# PaymentData.objects.create(
# user_id=user_id,
# payment_id=payment_id,
# total_amount=total_amounts,
# services_used=services_used,
# script_info=script_info,
# discount=discount,
# amount_charged=amount_charged,
# gateway_fee=gateway_fee,
# currency=currency,
# number_of_pages=number_of_pages,
# pay_method=pay_method,
# payment_status=payment_status,
# payment_gateway=payment_gateway,
# )
# try:
# if request.session["directly_pay_monthly"]:
# lasto = privilegedUser1.objects.last()
# privilegedUser1.objects.create(
# id=int(lasto.id) + 1,
# user=user_id,
# is_active="yes",
# transactionId=payment_id,
# memberType="normal",
# months=1
# )
# del request.session['directly_pay_monthly']
# except:
# pass
# try:
# if request.session["juggernaut_pages_deduction"]:
# update_juggernaut(request, user_id=request.user.id, service_name="conversion",
# conversion_pages=int(request.session["juggernaut_pages_deduction"]),
# associated_project=s, translation_language=str(dial_dest_language))
# except Exception as e:
# print("Error is: ", e)
context = {
"script_id": script_id,
}
to = request.user.email
key_value = {
"User": request.user.username,
}
sendmail(to_email=[to], email_code="PP19", key_value=key_value)
return render(request, "conversion/thanksconversion.html", context)
else:
# print("Get Request after payment is done razorpay1515")
# subject = "Something really went wrong"
# from_email = settings.EMAIL_HOST_USER
# to = request.user.email
# context_2 = {
# "Name": request.user.email,
# "service_name": "Conversion",
# }
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR24.html", context_2, from_email)
# return render(request, "payments/failed.html")
to = request.user.email
key_value = {
"User": request.user.username,
}
sendmail(to_email=[to], email_code="PP21", key_value=key_value)
return render(request, "payments/failed.html")
# -> Conversion Razorpay Payment Done Message
def paymentDoneppt_RazorPay(request):
keyID = request.session["keyID"]
keySecret = request.session["keySecret"]
if request.method == "POST":
# x = pptconversion.objects.get(ppt_string=request.session["pptstring"])
# if request.session.get("want_to_be_vetted") == "on":
# total_amount = x.amount
# else:
# total_amount = x.amount
# razorpay_order_id = request.POST["razorpay_order_id"]
# razorpay_payment_id = request.POST["razorpay_payment_id"]
# razorpay_signature = request.POST["razorpay_signature"]
# client = razorpay.Client(auth=(keyID, keySecret))
# params_dict = {
# "razorpay_order_id": razorpay_order_id,
# "razorpay_payment_id": razorpay_payment_id,
# "razorpay_signature": razorpay_signature,
# }
# try:
# client.utility.verify_payment_signature(params_dict)
# except:
# x.delete()
# subject = "Something really went wrong"
# from_email = settings.EMAIL_HOST_USER
# to = request.user.email
# context_2 = {
# "Name": request.user.email,
# "service_name": "Conversion",
# }
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR24.html", context_2, from_email)
# return render(request, "payments/failed.html")
#
# if request.session["pay_with_wallet"] == "yes":
# deduction_for_sep_wall(request)
# wall = Wallet.objects.get(user=request.user)
# wall.balance = request.session["fbalance"]
# wall.save()
#
# # payFetch = client.payment.fetch(razorpay_payment_id,({'expand[]':'card'}))
# if client.payment.fetch(razorpay_payment_id, {"expand[]": "card"}):
# pay_method = "CARD"
# else:
# pay_method = "NOTCard"
# # -----------Adding Details to payment Details--------------------------
# currencyrate = request.session["CurrencyRate"]
# user_id = request.user
# payment_id = razorpay_payment_id
# services_used = "Conversion"
# total_amounts = round(
# (x.slide_count * CONVERSION_PER_PAGE * currencyrate),
# 2,
# )
# discount = round((request.session["pptdiscount"] * currencyrate), 2)
# amount_charged = round((total_amount * currencyrate), 2)
# gateway_fee = round(
# ((RAZORPAY_PLATFORM_FEE / 100) * amount_charged), 2)
# currency = "INR"
# # pay_method = 'NOTCard'
# payment_status = "Success"
# payment_gateway = "RazorPay"
# number_of_pages = x.slide_count
# print("totalamount:", total_amounts)
# print("amountcharge:", amount_charged)
# print("discount:", discount)
# PaymentData.objects.create(
# user_id=user_id,
# payment_id=payment_id,
# total_amount=total_amounts,
# services_used=services_used,
# discount=discount,
# amount_charged=amount_charged,
# gateway_fee=gateway_fee,
# currency=currency,
# number_of_pages=number_of_pages,
# pay_method=pay_method,
# payment_status=payment_status,
# payment_gateway=payment_gateway,
# )
#
# with open(rf"{basePath}/ideamall/templates/ideamall/body.txt") as f:
# body = f.read()
#
# context_email = {
# "Date": date.today(),
# "Name": x.user_id.email,
# "emailcode": "",
# "heading1": "Thank you!",
# "heading2": " for using ppt conversion service "
# + " you will get notification whenever the conversation completes",
# "body": body,
# }
# # whomtosend, titleofmail, dateofemail, context\
# sendemail(
# x.user_id.email,
# "Thankyou for using service",
# date.today(),
# context_email,
# EMAIL_HOST_USER,
# ).start()
# # sdsdsadsadsdsadsadsdsdasdsaaaaaaassss
callback_context = callback(request.POST, request)
ppt_id = request.session["ppt_id"]
if callback_context['payment_status'] != 'success':
pptconversion.objects.get(ppt_id=ppt_id).delete()
subject = "Something really went wrong"
from_email = settings.EMAIL_HOST_USER
to = request.user.email
context_2 = {
"Name": request.user.email,
"service_name": "Conversion",
}
mnfnsendemail(
to, subject, "payment/templates/payments/MR24.html", context_2, from_email)
# sendmail(to_email=[ppt_instance.user_id.email,email_code='CP5')
return render(request, "payments/failed.html")
else:
total_amount = request.session["amount"]
if request.session["pay_with_wallet"] == "yes":
# deduction_for_sep_wall(request)
wall = Wallet.objects.get(user=request.user)
# for key, value in request.session.items():
# print('{} => {}'.format(key, value))
print("----------------amount", request.session["pay_wallet_deduction"])
print("----------------rate", request.session["CurrencyRate"])
print("final balance", round(wall.balance, 2) - (round(request.session["pay_wallet_deduction"], 2)))
wall.balance = round(wall.balance, 2) - (round(request.session["pay_wallet_deduction"], 2))
wall.save()
ppt_instance = pptconversion.objects.get(ppt_id=ppt_id)
# save central payment details in your database
ppt_instance.central_payment_id = request.session["central_payment_id"]
ppt_instance.payment_order_id = request.session["payment_order_id"]
ppt_instance.save()
sendmail(to_email=[ppt_instance.user_id.email], email_code='CP4')
sendmail(to_email=[ppt_instance.user_id.email], email_code='CP10')
ppt_conversion(ppt_id, request).start()
sendmail(to_email=[ppt_instance.user_id.email], email_code='CP9')
print('line---(2161)')
print('is the email working for ppt')
print('ppt_instance.user_id.email', ppt_instance.user_id.email)
del request.session["pptstring"]
return render(request, "conversion/thanksppt.html")
# -> Conversion Stripe Payment Done Message
def paymentDoneppt_stripe(request):
if request.method == "GET":
ppt_id = request.session["ppt_id"]
# x = pptconversion.objects.filter(
# ppt_string=request.session["pptstring"])
#
# total_amount = x.amount
# payment_intent_id = request.session["payment_intent_id"]
# try:
# pi = stripe.PaymentIntent.retrieve(payment_intent_id)
# except:
# x.delete()
# subject = "Something really went wrong"
# from_email = settings.EMAIL_HOST_USER
# to = request.user.email
# context_2 = {
# "Name": request.user.email,
# "service_name": "Conversion",
# }
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR24.html", context_2, from_email)
# return render(request, "payments/failed.html")
#
# if pi.status == "succeeded":
#
# if request.session["pay_with_wallet"] == "yes":
# deduction_for_sep_wall(request)
# wall = Wallet.objects.get(user=request.user)
# wall.balance = request.session["fbalance"]
# wall.save()
#
# # -----------Adding Details to payment Details--------------------------
# currencyrate = request.session["CurrencyRate"]
# user_id = request.user
# payment_id = payment_intent_id
# services_used = "Conversion"
# number_of_pages = x.slide_count
# total_amounts = round(
# (x.slide_count * CONVERSION_PER_PAGE * currencyrate),
# 2,
# )
# discount = round(
# (request.session["pptdiscount"] * currencyrate), 2)
# amount_charged = round((total_amount * currencyrate), 2)
# gateway_fee = round(
# ((STRIPE_PLATFORM_FEE / 100) * amount_charged), 2)
# currency = "INR"
# pay_method = "Card"
# payment_status = "Success"
# payment_gateway = "Stripe"
# PaymentData.objects.create(
# user_id=user_id,
# services_used=services_used,
# payment_id=payment_id,
# amount_charged=amount_charged,
# total_amount=total_amounts,
# number_of_pages=number_of_pages,
# gateway_fee=gateway_fee,
# discount=discount,
# currency=currency,
# pay_method=pay_method,
# payment_status=payment_status,
# payment_gateway=payment_gateway,
# )
#
# with open(rf"{basePath}/ideamall/templates/ideamall/body.txt") as f:
# body = f.read()
#
# context_email = {
# "Date": date.today(),
# "Name": x.user_id.email,
# "emailcode": "",
# "heading1": "Thank you!",
# "heading2": " for using ppt conversion service "
# + " you will get notification whenever the conversation completes",
# "body": body,
# }
# # whomtosend, titleofmail, dateofemail, context\
# sendemail(
# x.user_id.email,
# "Thankyou for using service",
# date.today(),
# context_email,
# EMAIL_HOST_USER,
# ).start()
# # sdsdsadsadsdsadsadsdsdasdsaaaaaaassss
# ppt_conversion(x.ppt_id, request).start()
# return render(request, "conversion/thanksppt.html")
# else:
# x.delete()
# subject = "Something really went wrong"
# from_email = settings.EMAIL_HOST_USER
# to = request.user.email
# context_2 = {
# "Name": request.user.email,
# "service_name": "Conversion",
# }
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR24.html", context_2, from_email)
# return render(request, "payments/failed.html")
response = {
"id": request.GET.get("payment_intent"),
"client_secret": request.GET.get("payment_intent_client_secret"),
"status": request.GET.get("redirect_status"),
}
callback_content = callback(response, request)
if callback_content['payment_status'] == "success":
if request.session["pay_with_wallet"] == "yes":
# deduction_for_sep_wall(request)
wall = Wallet.objects.get(user=request.user)
# for key, value in request.session.items():
# print('{} => {}'.format(key, value))
print("----------------amount", request.session["pay_wallet_deduction"])
print("----------------rate", request.session["CurrencyRate"])
print("final balance", round(wall.balance, 2) - (
round(request.session["pay_wallet_deduction"], 2)))
wall.balance = round(wall.balance, 2) - (
round(request.session["pay_wallet_deduction"], 2))
wall.save()
ppt_instance = pptconversion.objects.get(ppt_id=ppt_id)
ppt_instance.central_payment_id = request.session[
"central_payment_id"] # save central payment details in your database
ppt_instance.payment_order_id = request.session["payment_order_id"]
ppt_instance.save()
sendmail(to_email=[ppt_instance.user_id.email], email_code='CP4')
sendmail(to_email=[ppt_instance.user_id.email], email_code='CP10')
ppt_conversion(ppt_id, request).start()
sendmail(to_email=[ppt_instance.user_id.email], email_code='CP9')
print('line---(2282)')
print('is the email working for ppt')
del request.session["pptstring"]
return render(request, "conversion/thanksppt.html")
else:
sendmail(to_email=[ppt_instance.user_id.email], email_code='CP')
pptconversion.objects.get(ppt_id=ppt_id).delete()
subject = "Something really went wrong"
from_email = settings.EMAIL_HOST_USER
to = request.user.email
context_2 = {
"Name": request.user.email,
"service_name": "Conversion",
}
mnfnsendemail(
to, subject, "payment/templates/payments/MR24.html", context_2, from_email)
return render(request, "payments/failed.html")
# -> Actually Running Translation of book
def my_book(request):
print("Entering My_Book Conversion Function")
# -> PArsing the file location from database
y = BookConversion.objects.get(book_id=str(request.GET["book_id"]))
# -> Creating the directory for storing the extracted contents of docx
path = str(y.upload_book)
folder_name = (((path.split("/"))[-1]).split("."))[0]
if not os.path.exists(f"{basePath}/media/scripts/book/{folder_name}"):
os.mkdir(f"{basePath}/media/scripts/book/{folder_name}", mode=0o777)
# -> Creating the convert a book instance
convertBook_instance = ConvertBook()
# -> Alerting User that transaltion has started
to = request.user.email
key_value = {
"User": request.user.username,
}
sendmail(to_email=[to], email_code="PP22", key_value=key_value)
# -> Extracting the Docx contents as XML
data_docx_list = convertBook_instance.extract_docx_contents(
basePath + "/media/" + str(y.upload_book), f"{basePath}/media/scripts/book/{folder_name}")
print("I am done till here 7878", data_docx_list)
# -> Translating the contents and Recreating the docx book using the translated text
convertBook_instance.recreate_translated_book(
data_docx_list, f"{basePath}/media/scripts/book/{folder_name}/{str(folder_name)}_translated.docx", y.source_language, y.target_language)
# orig_path = ""
# for i in range(len(path)):
# if i == len(path) - 1:
# orig_path = orig_path + str(path[i])
# else:
# orig_path = orig_path + str(path[i]) + "/"
y.translated_book_docx = f"/media/scripts/book/{folder_name}/{str(folder_name)}_translated.docx"
convert_to_pdf(f"{basePath}/media/scripts/book/{folder_name}/{str(folder_name)}_translated.docx",
rf"{basePath}/media/scripts/book/{folder_name}/")
y.translated_book_pdf = rf"/media/scripts/book/{folder_name}/{str(folder_name)}_translated.pdf"
translated_book_pdf = rf"/media/scripts/book/{folder_name}/{str(folder_name)}_translated.pdf"
y.save()
# bookconversion = {}
# if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
# contex =request.session["original_book"]
# hash = uploadDataToIPFSNode(contex)
# print("my_hash1",hash)
# bookconversion["original_bookFile_hash"] = hash
# if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
# contex =translated_book_pdf
# hash = uploadDataToIPFSNode(contex)
# print("my_hash2",hash)
# bookconversion["translated_bookFile_hash"] = hash
# if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
# blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user)
# UserId = blockchain_obj.user_id
# Project = script_id
# Data = str(bookconversion)
# userPrivateKey =blockchain_obj.privateKey
# userkey =decryptionOfPrivate(userPrivateKey)
# hash =UploadConversionData(userkey.decode('utf-8'),UserId,Project,Data)
to = request.user.email
key_value = {
"User": request.user.username,
}
sendmail(to_email=[to], email_code="PP23", key_value=key_value)
print("Exiting My_Book Conversion Function")
return JsonResponse({"status": "success"}, status=200)
def book_payment(request):
# new payment 8000
set_payment_token(request)
keyID = request.session["keyID"]
keySecret = request.session["keySecret"]
if request.method == "POST":
if request.POST.get("want_to_be_vetted") == "yes":
# print("amount to be paid", request.session["amount"])
# total_amount = request.session["amount"]
# amount_lpp_without_discount = request.session["onlylppfee"]
# print(request.session["amount"], " : Final Amount")
request.session["want_to_be_vetted"] = "on"
else:
# print("amount to be paid", request.session["amount"])
# total_amount = request.session["amount"]
request.session["want_to_be_vetted"] = request.POST.get(
"want_to_be_vetted")
# print("amount to be paid", request.session["amount"])
total_amount = request.session["amount"]
# request.session["want_to_be_vetted"] = request.POST.get(
# "want_to_be_vetted")
# request.session["interested_to_be_lpp"] = request.POST.get(
# "interested_to_be_lpp"
# )
request.session["amount_before_pay_wallet"] = total_amount
request.session["pay_with_wallet"] = "no"
try:
if request.POST.get("pay_wallet") == "on":
request.session["pay_with_wallet"] = "yes"
with open(f"{basePath}/MNF/json_keys/conversionRates.json") as c:
curr = json.load(c)
print(curr["rates"]["INR"])
try:
rate = curr["rates"]["INR"]
except Exception as e:
print("checkout error", e)
rate = 80
# balance = float(request.POST["balance"])
# payable = float(request.POST["payable"])
# wall = Wallet.objects.get(user=request.user)
# request.session["fbalance"] = float(
# wall.balance) - float(balance * rate)
# wall.save()
# request.session["amount"] = payable
# total_amount = request.session["amount"]
print("Checking Wallet")
wall = Wallet.objects.get(user=request.user)
print("this is walet", wall.balance)
print(wall.balance)
if wall.balance >= (total_amount * rate):
print("wallet if hai")
request.session["pay_wallet_deduction"] = round(total_amount * rate, 2)
total_amount = 0
else:
print("wallet else hai")
request.session["pay_wallet_deduction"] = round(wall.balance, 2)
total_amount = round((round(total_amount * rate, 2) - round(wall.balance, 2)) / rate, 2)
except Exception as e:
print("Error is ",e)
# total_amount = request.session["amount"]
total_amount1 = request.session["subtotal"]
# amount_charged = request.session["amount"]
# amount_discount = request.session["discount"]
# total_amount1 = request.session["subtotal"]
# amount_charged = request.session["amount"]
amount_discount = request.session["discount"]
services_used = 2 if request.POST.get("want_to_be_vetted") == "yes" else 1
context = create_indent(request, 'Conversion', str(request.session["book_id"]), services_used, '',
total_amount1, total_amount, amount_discount)
print("Create indent 9987", context)
for key, value in request.session.items():
print('{} => {}'.format(key, value))
print(str(request.session["book_id"]))
# instance = MNFScriptDatabase.objects.get(script_id=str(request.session["script_id"]))
with open(f"{basePath}/MNF/json_keys/conversionRates.json") as c:
curr = json.load(c)
try:
rate = curr["rates"]["INR"]
except Exception as e:
rate = 80
request.session["CurrencyRate"] = rate
centralPayment_instance = CentralPayment.objects.get(
id=context["central_pay_id"])
# handle razor pay gateway →
if "orderId" in context:
# instance.payment_order_id = context["orderId"]
# instance.central_payment_id = context["central_pay_id"]
# instance.save() # save central payment details in your database
request.session["payment_order_id"] = context["orderId"]
request.session["central_payment_id"] = context["central_pay_id"]
pid = centralPayment_instance.order_id
amtINR = round(centralPayment_instance.amount_charged * rate, 2)
context = {
"pk": keyID,
"amtINR": amtINR,
"pid": pid,
"amount": round(centralPayment_instance.amount_charged,2),
}
return render(request, "conversion/checkoutBook_RazorPay.html", context)
# handle stripe gateway →
elif "client_secret" in context:
# save central payment details in your database
request.session["payment_order_id"] = context["client_secret"]
request.session["central_payment_id"] = context["central_pay_id"]
amtINR = round(centralPayment_instance.amount_charged * rate,2)
context = {
"pk": STRIPE_PUB_KEY,
"total_amount": round(centralPayment_instance.amount_charged, 2),
"secret_key": context["client_secret"],
"amtINR": amtINR,
"STRIPE_PUBLISHABLE_KEY": STRIPE_PUB_KEY,
}
return render(request, "conversion/checkoutBook_Stripe.html", context)
# handle corporate profile →
elif "monthly_user" in context:
book_instance = BookConversion.objects.get(
book_id=request.session["book_id"])
book_instance.central_payment_id = context["central_pay_id"]
book_instance.payment_order_id = "monthly_user"
book_instance.save()
# instance.payment_order_id = "corporate profile"
# instance.central_payment_id = "corporate profile"
# instance.save()
return render(request, "conversion/thanksbook.html", {"book_id": request.session["book_id"]})
# -> At 10sec intervals check if book conversion completed
def is_book_converted(request):
book_id = request.GET["book_id"]
obj = StoryConversion.objects.get(story_id=book_id)
print("book still converting", obj.translated_book_docx)
if obj.translated_book_docx:
return JsonResponse({"status": "success"}, status=200)
else:
return JsonResponse({"status": "pending"}, status=202)
# -> Fetching the Source Language and Number of Pages of book
def check_book_lang(request):
y = BookConversion()
y.user_id = request.user
now = datetime.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]
# -> Checking Book Source Language
y.book_id = "book_" + str(str4)
y.upload_book = request.FILES['my_book']
# request.session["original_book"] = request.FILES['my_book']
y.save()
try:
number_pages = countPages(
str(BASE_DIR) + "/media/" +
str(y.upload_book), str(y.upload_book)[13:-4] + "pdf"
)
docxx = docx.Document(str(BASE_DIR) + "/media/" +
str(y.upload_book))
text = ""
for paragraph in docxx.paragraphs:
text += paragraph.text
if text.strip() == "" or text.strip() == " " or len(text.strip()) < 5:
pass
else:
break
print("text is",text)
src_language = language_detector(text)
BookConversion.objects.get(id=y.id).delete()
return JsonResponse({"Detected Language": languages[src_language], "number_pages": number_pages})
except Exception as e:
print("Exception for language not getting detected is:", e)
BookConversion.objects.get(id=y.id).delete()
return JsonResponse({}, status=505)
# -> Initital Saving of Book in database and extracting various languages present in that
def convert_book(request):
print("Request i", request.method)
if request.method == "POST":
print("Yes i am in here")
y = BookConversion()
y.user_id = request.user
now = datetime.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]
y.book_id = "book_" + str(str4)
if request.POST.get("book_id"):
print("Inside sample book if case")
# book_sample = SampleBook.objects.get(book_id=request.POST.get("book_id"))
# y.upload_book = book_sample.book_path
# # print(request.POST.get("header_footer_addition"), "<- checkbox value")
# # y.source_language = src_language
# y.numPages = book_sample.number_pages
# y.source_language = ((list(languages.keys()))[list(
# languages.values()).index(book_sample.source_lang)])
# y.target_language = ((list(languages.keys()))[list(
# languages.values()).index(request.POST.get("target_lang"))])
# y.header_footer_present = True if request.POST.get(
# "header_footer_addition") else False
# y.save()
else:
Book = AScript(request.POST, request.FILES)
if Book.is_valid():
y.upload_book = Book.cleaned_data.get("myfile")
# print(request.POST.get("header_footer_addition"), "<- checkbox value")
# y.source_language = src_language
y.numPages = request.POST.get("number_pages_var")
y.source_language = ((list(languages.keys()))[list(
languages.values()).index(request.POST.get("src_lang"))])
y.target_language = ((list(languages.keys()))[list(
languages.values()).index(request.POST.get("target_lang"))])
y.header_footer_present = True if request.POST.get(
"header_footer_addition") else False
y.save()
if int(y.numPages) <= 5 or request.POST.get("book_id"):
return render(request, "conversion/thanksbook.html", {"book_id": y.book_id})
else:
context = {}
if request.POST.get("sample_free") == "on":
return render(request, "conversion/thanksbook.html", {"book_id": y.book_id, "restrict_to_five":"yes"})
numPages = int(y.numPages)
if request.POST.get("to_be_vetted_by_lpp") == "on":
lpp_available = "yes"
total_amount = round(int(float(pricing_data('Book Conversion', 4))) * numPages, 2)
else:
lpp_available = "no"
total_amount = round(int(float(pricing_data('Script Conversion', 2))) * numPages, 2)
context["subtotal"] = round(total_amount, 2)
context["early_bird_discount"] = discount_limit_handler(DISCOUNT["early_bird"])
context["early_bird_calculate"] = round(
float((total_amount) * context["early_bird_discount"] / 100), 2)
# staff discount
if User.objects.get(id=request.user.id).is_staff: # changes done by manoj
context["sdiscount"] = discount_limit_handler(DISCOUNT["employ_discount"])
context["staff_discount_calculate"] = round(float(
(total_amount - context["early_bird_calculate"]) * context[
"sdiscount"] / 100), 2)
else:
context["sdiscount"] = 0
context["staff_discount_calculate"] = 0
user = User.objects.get(id=request.user.id)
try:
memberType = privilegedUser1.objects.filter(user=user, is_active="yes")
if memberType:
memberType = memberType.first().memberType
if memberType == "normal":
context["pdiscount"] = 0
context["membership_discount_calculate"] = 0
elif memberType == "yearly":
context["pdiscount"] = discount_limit_handler(DISCOUNT["yearly_member_additional"])
context["membership_discount_calculate"] = round(float((
total_amount -
context[
"early_bird_calculate"] -
context[
"staff_discount_calculate"]) *
context["pdiscount"] / 100), 2)
elif memberType == "Life Member":
context["pdiscount"] = discount_limit_handler(DISCOUNT["life_member_additional"])
context["membership_discount_calculate"] = round(float((
total_amount -
context[
"early_bird_calculate"] -
context[
"staff_discount_calculate"]) *
context["pdiscount"] / 100), 2)
if not privilegedUser1.objects.filter(user=request.user, is_active="yes").exists():
context["monthly_membership"] = 1
# context["membershipNarration"] = discount_limit_handler(DISCOUNT["monthly_member"])
context["pdiscount"] = 0
context["membership_discount_calculate"] = 0
except:
context["monthly_membership"] = 1
context["pdiscount"] = 0
context["membership_discount_calculate"] = 0
get_student_discount = get_discount(request.user.id, total_amount)
if get_student_discount == 0:
context["student_discount"] = 0
context["student_discount_calculate"] = 0
else:
context["student_discount"] = get_student_discount
context["student_discount_calculate"] = round(float((total_amount -
context["early_bird_calculate"] -
context["staff_discount_calculate"] -
context["membership_discount_calculate"]) *
context["student_discount"] / 100), 2)
context["Total_discount"] = round(float(
context["early_bird_calculate"] + context["staff_discount_calculate"] +
context["membership_discount_calculate"] + context["student_discount_calculate"]), 2)
context["remaining_amount"] = round(float(total_amount - context["Total_discount"]), 2)
context["net_service_charge"] = round(
float(context["remaining_amount"]), 2)
# GST
context["gst"] = discount_limit_handler(DISCOUNT["gst"])
context["gst_calculate"] = round(float(context["remaining_amount"] * context["gst"] / 100), 2)
context["net_payable"] = round(float(context["remaining_amount"] + context["gst_calculate"]), 2)
print(context)
# -> OLD Code
# context["book_id"] = y.book_id
# request.session["book_id"] = y.book_id
# payment calculation for book
# pdiscount = 1
# sdiscount = 1
# mdiscount = 1 - settings.RUNNING_DISCOUNT_CONVERSION / 100
# # numPages = int(numPages)
#
# if not privilegedUser1.objects.filter(
# user=request.user, is_active="yes"
# ).exists():
# # messages.success(request, "Become privileged member")
# # return redirect("payment")
# request.session["directly_pay_monthly"] = 1
# context = {"directly_pay_monthly": 1}
# try:
# memberType = privilegedUser1.objects.get(
# user=request.user, is_active="yes"
# ).memberType
# if memberType:
# if memberType == "normal":
# pdiscount = 1
# context["pdiscount"] = 0
# elif memberType == "yearly":
# pdiscount = 1 - settings.YEARLY_MEMBER_ADDITIONAL / 100
# context["pdiscount"] = settings.YEARLY_MEMBER_ADDITIONAL
# elif memberType == "Life Member":
# pdiscount = 1 - settings.LIFE_MEMBER_ADDITIONAL / 100
# context["pdiscount"] = settings.LIFE_MEMBER_ADDITIONAL
# if User.objects.get(id=request.user.id).is_staff:
# sdiscount = 1 - settings.EMPLOY_DISCOUNT / 100
# except:
# pdiscount = 1
# sdiscount = 1
# context["pdiscount"] = 0
# # pdiscount = 1
# # sdiscount = 1
# # mdiscount = 1 - settings.RUNNING_DISCOUNT_CONVERSION / 100
# # memberType = privilegedUser1.objects.get(
# # user=request.user, is_active="yes"
# # ).memberType
# # if memberType:
# # if memberType == "normal":
# # pdiscount = 1
# # context["pdiscount"] = 0
# # elif memberType == "yearly":
# # pdiscount = 1 - settings.YEARLY_MEMBER_ADDITIONAL / 100
# # context["pdiscount"] = settings.YEARLY_MEMBER_ADDITIONAL
# # elif memberType == "Life Member":
# # pdiscount = 1 - settings.LIFE_MEMBER_ADDITIONAL / 100
# # context["pdiscount"] = settings.LIFE_MEMBER_ADDITIONAL
# if User.objects.get(id=request.user.id).is_staff:
# sdiscount = 1 - settings.EMPLOY_DISCOUNT / 100
# # if request.POST.get("to_be_vetted_by_lpp") == "on":
# # lpp_available = "yes"
# # try:
# # lppamt = (
# # (numPages * settings.CONVERSION_PER_PAGE)
# # + (numPages * settings.LPP_PER_PAGE)
# # + context["directly_pay_monthly"]
# # )
# # except:
# # lppamt = (numPages * settings.CONVERSION_PER_PAGE) + (
# # numPages * settings.LPP_PER_PAGE
# # )
# # context["subtotal"] = round(
# # numPages * settings.CONVERSION_PER_PAGE, 2
# # )
# # # amt = numPages * settings.CONVERSION_PER_PAGE
# # # context["subtotal"] = round(amt, 2)
# #
# # # lppamt = (numPages * settings.CONVERSION_PER_PAGE) + (
# # # numPages * settings.LPP_PER_PAGE
# # # )
# # context["onlylppfee"] = round((numPages * settings.LPP_PER_PAGE), 2)
# # context["sublpptotal"] = round(lppamt, 2)
# # context["amount"] = round(
# # mdiscount * lppamt * pdiscount * sdiscount, 2
# # )
# # context["discount"] = lppamt - context["amount"]
# # request.session["amount"] = context["amount"]
# # request.session["onlylppfee"] = context["onlylppfee"]
# # request.session["lppamount"] = context["amount"]
# # request.session["discount"] = context["discount"]
# # request.session["member_discount"] = mdiscount
# # request.session["running_discount"] = pdiscount
# # request.session["team_discount"] = sdiscount
# # request.session["want_to_be_vetted"] = "on"
# # else:
# lpp_available = "no"
# try:
# amt = (
# numPages
# * settings.CONVERSION_PER_PAGE
# + context["directly_pay_monthly"]
# )
# except:
# amt = numPages * settings.CONVERSION_PER_PAGE
# context["subtotal"] = round(
# numPages * settings.CONVERSION_PER_PAGE, 2
# )
# context["amount"] = round(
# mdiscount * amt * pdiscount * sdiscount, 2
# )
# context["discount"] = amt - context["amount"]
#
# # try:
# request.session["amount"] = context["amount"]
# # except:
# # request.session["amount"] = context["amount"]
# request.session["subtotal"] = context["subtotal"]
# request.session["discount"] = context["discount"]
#
# context["conversion_per_page"] = settings.CONVERSION_PER_PAGE
# context["lpp_per_page"] = settings.LPP_PER_PAGE
# context[
# "running_discount_conversion"
# ] = settings.RUNNING_DISCOUNT_CONVERSION
# context["employ_discount"] = settings.EMPLOY_DISCOUNT
# context["yearly_member_additional"] = settings.YEARLY_MEMBER_ADDITIONAL
# context["life_member_additional"] = settings.LIFE_MEMBER_ADDITIONAL
# # context["restrict_to_five"] = "no"
# context["lpp_available"] = lpp_available.upper()
# context["numPages"] = numPages
# context["book_title"] = str(y.upload_book)
# request.session["book_id"] = str(y.book_id)
# context["src_lang"] = request.POST.get("src_lang")
# context["dest_lang"] = request.POST.get("target_lang")
# # request.session["script_file_path"] = x.script_file_path
context["restrict_to_five"] = "no"
context["lpp_available"] = lpp_available.upper()
context["numPages"] = numPages
context["book_title"] = str(y.upload_book)
context["src_lang"] = request.POST.get("src_lang")
context["dest_lang"] = request.POST.get("target_lang")
request.session["amount"] = context["net_payable"]
request.session["subtotal"] = context["subtotal"]
request.session["discount"] = context["Total_discount"]
request.session["book_id"] = str(y.book_id)
request.session["book_title"] = str(y.upload_book)
request.session["numPages"] = numPages
try:
wall = Wallet.objects.get(user=request.user)
context["balance"] = round(wall.balance, 2)
except:
context["balance"] = -1
with open(f"{basePath}/MNF/json_keys/conversionRates.json") as c:
curr = json.load(c)
try:
rate = curr["rates"]["INR"]
# c = CurrencyRates()
# rate = c.get_rate("USD", str(currency.upper()))
except Exception as e:
print("checkout error", e)
rate = 80
context["rate"] = rate
str1 = str(datetime.datetime.now()).split("-")
date_at = f'{str1[2][0:2]} - {str1[1]} - {str1[0]}'
context['date_at'] = date_at
try:
cd = centralDatabase.objects.get(user_id=request.user)
name = cd.firstName if cd.firstName else user.username
email_id = cd.email if cd.email else user.email
phone_number = str(cd.countryCode) + str(cd.contact) if cd.contact else "N/A"
address = cd.address if cd.address else "N/A"
except:
name = user.username
email_id = user.email
phone_number = "N/A"
address = "N/A"
context["name"] = name
context["email_id"] = email_id
context["phone_number"] = phone_number
context["address"] = address
# try:
# context["firstdiscount"] =
# context["seconddiscount"] =
# context["thirddiscount"] =
# except Exception as e:
# print(e, "<- Error")
return render(request, "conversion/invoice_book.html", context)
return render(request, "conversion/convertBook.html")
# -> For Viewing Your Books
# def view_converted_books(request):
# number = ReferUser.objects.filter(refferedBy=request.user).count()
# obj = BookConversion.objects.filter(
# user_id=request.user).order_by("-date_at")
#
# book_path = []
# pq = 0
# for i in obj:
# if i.translated_book_docx != "":
# book_path.append(i.translated_book_docx)
# pq += 1
#
# return render(
# request,
# "conversion/viewConvertedBooks.html",
# {"script_path": obj, "pq": pq, "number": number},
# )
# -> For Deleting your Book
def delete_converted_book(request, id):
to = request.user.email
key_value = {
"User": request.user.username,
"book_name": (((str(BookConversion.objects.get(id=id).upload_book).split("/"))[-1]).split("."))[0]
}
sendmail(to_email=[to], email_code="PP25", key_value=key_value)
BookConversion.objects.get(id=id).delete()
# if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
# blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user)
# userkey =decryptionOfPrivate(blockchain_obj.privateKey)
# deleteConversion(userkey.decode('utf-8'),blockchain_obj.user_id,id)
return HttpResponseRedirect("/conversion/view_conversion")
def paymentDoneBook_RazorPay(request):
keyID = request.session["keyID"]
keySecret = request.session["keySecret"]
if request.method == "POST":
book_id = request.session["book_id"]
book_title = request.session["book_title"]
# if request.session.get("want_to_be_vetted"):
# total_amount = request.session["lppamount"]
# else:
# total_amount = request.session["amount"]
# to_be_vetted_by_lpp = request.session["want_to_be_vetted"]
# total_amount = request.session["amount"]
# razorpay_order_id = request.POST["razorpay_order_id"]
# razorpay_payment_id = request.POST["razorpay_payment_id"]
# razorpay_signature = request.POST["razorpay_signature"]
# client = razorpay.Client(auth=(keyID, keySecret))
# params_dict = {
# "razorpay_order_id": razorpay_order_id,
# "razorpay_payment_id": razorpay_payment_id,
# "razorpay_signature": razorpay_signature,
# }
callback_context = callback(request.POST, request)
if callback_context['payment_status'] != 'success':
BookConversion.objects.get(book_id=book_id).delete()
# subject = "Something really went wrong"
# from_email = settings.EMAIL_HOST_USER
# to = request.user.email
# context_2 = {
# "Name": request.user.email,
# "service_name": "Conversion",
# }
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR24.html", context_2, from_email)
# -> PAyment UnSuccessfull Email
to = request.user.email
key_value = {
"User": request.user.username,
}
sendmail(to_email=[to], email_code="PP26", key_value=key_value)
return render(request, "payments/failed.html")
else:
# if request.session["pay_with_wallet"] == "yes":
# deduction_for_sep_wall(request)
# wall = Wallet.objects.get(user=request.user)
# wall.balance = request.session["fbalance"]
# wall.save()
if request.session["pay_with_wallet"] == "yes":
# deduction_for_sep_wall(request)
wall = Wallet.objects.get(user=request.user)
# for key, value in request.session.items():
# print('{} => {}'.format(key, value))
print("----------------amount", request.session["pay_wallet_deduction"])
print("----------------rate", request.session["CurrencyRate"])
print("final balance", round(wall.balance, 2) - (round(request.session["pay_wallet_deduction"], 2)))
wall.balance = round(wall.balance, 2) - (round(request.session["pay_wallet_deduction"], 2))
wall.save()
book_instance = BookConversion.objects.get(book_id=book_id)
# save central payment details in your database
book_instance.central_payment_id = request.session["central_payment_id"]
book_instance.payment_order_id = request.session["payment_order_id"]
book_instance.save()
# -> PAyment UnSuccessfull Email
to = request.user.email
key_value = {
"User": request.user.username,
}
sendmail(to_email=[to], email_code="PP24", key_value=key_value)
return render(request, "conversion/thanksbook.html", {"book_id": book_id})
# c = conversionPayment()
# c.pid = privilegedUser1.objects.get(user= request.user)
# c.script_title = script_title
# c.script_id = script_id
# c.to_be_vetted_by_lpp = to_be_vetted_by_lpp
# c.payment_intent_id = razorpay_payment_id
# c.total_amount = str(total_amount)
# c.script_file_path = script_file_path
# c.has_paid = 'yes'
# c.save()
# payFetch = client.payment.fetch(razorpay_payment_id,({'expand[]':'card'}))
# if client.payment.fetch(razorpay_payment_id, {"expand[]": "card"}):
# pay_method = "CARD"
# else:
# pay_method = "NOTCard"
# # -----------Adding Details to payment Details--------------------------
# currencyrate = request.session["CurrencyRate"]
# user_id = request.user
# payment_id = razorpay_payment_id
# services_used = "Book Conversion"
# # script_info = s
# total_amounts = round(
# (request.session["numPages"] * CONVERSION_PER_PAGE * currencyrate),
# 2,
# )
# discount = round((request.session["discount"] * currencyrate), 2)
# amount_charged = round((total_amount * currencyrate), 2)
# gateway_fee = round(
# ((RAZORPAY_PLATFORM_FEE / 100) * amount_charged), 2)
# currency = "INR"
# # pay_method = 'NOTCard'
# payment_status = "Success"
# payment_gateway = "RazorPay"
# number_of_pages = request.session["numPages"]
# PaymentData.objects.create(
# user_id=user_id,
# payment_id=payment_id,
# total_amount=total_amounts,
# services_used=services_used,
# # script_info=script_info,
# discount=discount,
# amount_charged=amount_charged,
# gateway_fee=gateway_fee,
# currency=currency,
# number_of_pages=number_of_pages,
# pay_method=pay_method,
# payment_status=payment_status,
# payment_gateway=payment_gateway,
# )
# try:
# if request.session["directly_pay_monthly"]:
# lasto = privilegedUser1.objects.last()
# privilegedUser1.objects.create(
# id=int(lasto.id) + 1,
# user=user_id,
# is_active="yes",
# transactionId=payment_id,
# memberType="normal",
# months=1
# )
# del request.session['directly_pay_monthly']
# except:
# pass
# return render(request, "conversion/thanksconversion.html", context)
def paymentDoneBook_Stripe(request):
# if pi.status == "succeeded":
#
# if request.session["pay_with_wallet"] == "yes":
# deduction_for_sep_wall(request)
# walls = Wallet.objects.get(user=request.user)
# walls.balance = request.session["fbalance"]
# walls.save()
#
# # -----------Adding Details to payment Details--------------------------
# currencyrate = request.session["CurrencyRate"]
# user_id = request.user
# payment_id = payment_intent_id
# services_used = "Book Conversion"
# # script_info = s
# number_of_pages = request.session["numPages"]
# total_amounts = round(
# (request.session["numPages"] *
# CONVERSION_PER_PAGE * currencyrate),
# 2,
# )
# discount = round((request.session["discount"] * currencyrate), 2)
# amount_charged = round((total_amount * currencyrate), 2)
# gateway_fee = round(
# ((STRIPE_PLATFORM_FEE / 100) * amount_charged), 2)
# currency = "INR"
# pay_method = "Card"
# payment_status = "Success"
# payment_gateway = "Stripe"
# PaymentData.objects.create(
# user_id=user_id,
# services_used=services_used,
# payment_id=payment_id,
# # script_info=script_info,
# amount_charged=amount_charged,
# total_amount=total_amounts,
# number_of_pages=number_of_pages,
# gateway_fee=gateway_fee,
# discount=discount,
# currency=currency,
# pay_method=pay_method,
# payment_status=payment_status,
# payment_gateway=payment_gateway,
# )
# try:
# if request.session["directly_pay_monthly"]:
# lasto = privilegedUser1.objects.last()
# privilegedUser1.objects.create(
# id=int(lasto.id) + 1,
# user=user_id,
# is_active="yes",
# transactionId=payment_id,
# memberType="normal",
# months=1
# )
# del request.session['directly_pay_monthly']
# except:
# pass
#
# return render(request, "conversion/thanksbook.html", {"book_id": book_id})
#
# # return render(request, "conversion/thanksconversion.html", context)
# else:
# subject = "Something really went wrong"
# from_email = settings.EMAIL_HOST_USER
# to = request.user.email
# context_2 = {
# "Name": request.user.email,
# "service_name": "Conversion",
# }
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR24.html", context_2, from_email)
# return render(request, "payments/failed.html")
if request.method == "GET":
book_id = request.session["book_id"]
book_title = request.session["book_title"]
# if request.session.get("want_to_be_vetted"):
# total_amount = request.session["lppamount"]
# else:
# total_amount = request.session["amount"]
# total_amount = request.session["amount"]
# to_be_vetted_by_lpp = request.session["want_to_be_vetted"]
# payment_intent_id = request.session["payment_intent_id"]
# pi = stripe.PaymentIntent.retrieve(payment_intent_id)
response = {
"id": request.GET.get("payment_intent"),
"client_secret": request.GET.get("payment_intent_client_secret"),
"status": request.GET.get("redirect_status"),
}
callback_content = callback(response, request)
if callback_content['payment_status'] == "success":
# if request.session["pay_with_wallet"] == "yes":
# deduction_for_sep_wall(request)
# walls = Wallet.objects.get(user=request.user)
# walls.balance = request.session["fbalance"]
# walls.save()
if request.session["pay_with_wallet"] == "yes":
# deduction_for_sep_wall(request)
wall = Wallet.objects.get(user=request.user)
# for key, value in request.session.items():
# print('{} => {}'.format(key, value))
print("----------------amount", request.session["pay_wallet_deduction"])
print("----------------rate", request.session["CurrencyRate"])
print("final balance", round(wall.balance, 2) - (round(request.session["pay_wallet_deduction"], 2)))
wall.balance = round(wall.balance, 2) - (round(request.session["pay_wallet_deduction"], 2))
wall.save()
book_instance = BookConversion.objects.get(book_id=book_id)
book_instance.central_payment_id = request.session[
"central_payment_id"] # save central payment details in your database
book_instance.payment_order_id = request.session["payment_order_id"]
book_instance.save()
# -> PAyment Successfull Email
to = request.user.email
key_value = {
"User": request.user.username,
}
sendmail(to_email=[to], email_code="PP24", key_value=key_value)
return render(request, "conversion/thanksbook.html", {"book_id": book_id})
else:
BookConversion.objects.get(book_id=book_id).delete()
# subject = "Something really went wrong"
# from_email = settings.EMAIL_HOST_USER
# to = request.user.email
# context_2 = {
# "Name": request.user.email,
# "service_name": "Conversion",
# }
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR24.html", context_2, from_email)
# -> PAyment UnSuccessfull Email
to = request.user.email
key_value = {
"User": request.user.username,
}
sendmail(to_email=[to], email_code="PP26", key_value=key_value)
return render(request, "payments/failed.html")
# #IPFS
# def start_ipfs_daemon():
# try:
# # Check if the IPFS daemon is already running
# subprocess.check_output(["ipfs", "id"])
# print("IPFS daemon is already running.")
# except subprocess.CalledProcessError:
# # If the IPFS daemon is not running, start it
# print("Starting IPFS daemon...")
# subprocess.Popen(["ipfs", "daemon"])
# # Wait for the daemon to start (you can adjust the delay as needed)
# time.sleep(5)
# print("IPFS daemon is now running.")
# #IPFS END
# start_ipfs_daemon()
# -> For making Translated PPT's
class ppt_conversion(threading.Thread):
def __init__(self, ppt, request, restrict=False):
self.ppt = ppt
self.request = request
self.restrict = restrict
threading.Thread.__init__(self)
def run(self):
try:
x = pptconversion.objects.get(ppt_id=self.ppt)
presentation = Presentation(x.upload_ppt)
if self.restrict:
presentation = Presentation(x.upload_ppt)
xml_slides = presentation.slides._sldIdLst
slides = list(xml_slides)
# Then I loop for all except the first (index 0):
for index in range(3, len(slides)):
xml_slides.remove(slides[index])
t = random.randint(1, 1000)
times = time.time()
times = int(times)
for key, value in languages.items():
if value == x.target_lang:
target = key
if value == x.source_lang:
source = key
print(">:>:>:>:12 translation start")
translate_presentation(presentation, source,
target, x.target_script, self.restrict)
print(">:>:>:>:12 translation end")
translated_ppt = f"{x.user_id}-{source}-{target}-{t}-{times}.pptx"
paths = f"{basePath}/media/ppt/converted/{translated_ppt}"
presentation.save(paths)
print(f"presentation convert saved {translated_ppt}")
x.translated_ppt = translated_ppt
x.save()
print('x.user_id.email', x.user_id.email)
sendmail(to_email=[x.user_id.email], email_code='CP2')
# Blockchain here--->
if UserCredentialsForBlockchain.objects.filter(user=self.request.user).exists():
blockchain_obj = UserCredentialsForBlockchain.objects.get(
user=self.request.user)
privatekey = blockchain_obj.privateKey
user_id = blockchain_obj.user_id
Project = self.request.session["script_id"]
private_Key = decryptionOfPrivate(privatekey)
status, getData = getPPTConversion(
private_Key.decode('utf-8'), user_id, Project)
if status == True:
data1 = getData[1]
pptconversion1 = eval(data1)
with open(f"{basePath}/media/ppt/converted/{translated_ppt}", 'rb') as _file:
hash = uploadDataToIPFSNode(_file)
pptconversion1["translated_ppt_hash"] = hash
pptconversion1["translated_ppt_path"] = paths
pptconversion1["translated_ppt"] = translated_ppt
original_file_path = pptconversion1.get("ppt_scriptFile_path")
user_id = blockchain_obj.user_id
project = self.request.session["script_id"]
Data = str(pptconversion1)
response = UploadPPTConversionData(
OWNER_KEY,blockchain_obj.publicKey,user_id, project, Data)
print("Response_final :", response)
hash = hash_decrypation(hash)
certificatepath = certificateGenrate(self.request.user.username,"PPT Conversion",hash)
to_email = [self.request.user.email]
email_code = 'BL1'
key_value = {
"service":"PPT Conversion",
"hash": hash,
"public key":blockchain_obj.publicKey,
"private key":private_Key.decode('utf-8'),
}
print("::::::::::::::",key_value)
sendmail(to_email=to_email , email_code=email_code,key_value=key_value, filePath=certificatepath)
# For Vetting
# if request.session
# obj = ppt.objects.get(script_id=script_id)
if x.lpp is True:
print("Making Vetting Request for ppt")
X = LPPTASKDatabase()
X.user_id = x.user_id
X.usernote = "Kindly check if the translated ppt file is correct as per the Uploaded PPT!"
X.translated_ppt = x
X.generated_from = "conversion"
X.amoutgiventolpp_dialogue = self.request.session["lppamount_after_discount"]
# temp_amount = ((request.session['onlylppfee']) * request.session['team_discount']
# * request.session['member_discount'] * request.session['running_discount'])
# X.amoutgiventolpp_action = round((temp_amount/2), 2)
# X.amoutgiventolpp_dialogue = round((temp_amount/2), 2)
X.save()
# task_assigner(int(X.task_id), "conversion_ppt")
print("Making Vetting task Request for ppt")
else:
# temp1 = str(x.upload_ppt)
# temp = f"{basePath}/media/{temp1}"
# data = [temp, paths]
# print(self.request.session["originalppt"])
# print(data, x.ppt_string, self.request.user.email,
# " : Passed to blockchain")
# files, timestamp = upload_multiFile_to_ipfs(
# data, x.ppt_string, "convertPPT", self.request.user.email)
# x.timestamp = timestamp
# x.uploaded_ppt_encoded = files[0]
# x.translated_ppt_encoded = files[1]
# print(x.timestamp, x.uploaded_ppt_encoded,
# x.translated_ppt_encoded, " : Return from Blockchain")
x.save()
# "heading2": f"To view from blockchain use following details: Timestamp - {x.timestamp}, Key - {x.script_title}, Service - convertScript",
with open(rf"{basePath}/ideamall/templates/ideamall/body.txt") as f:
body = f.read()
context_email = {
"Date": date.today(),
"Name": x.user_id.email,
"emailcode": "",
"heading1": "Congratulation! your presentation is converted",
"heading2": "Thank you for using our service",
"body": body,
}
# import os
# if os.path.exists(f"{basePath}/media/ppt/converted/{translated_ppt}"):
# os.remove(f"{basePath}/media/ppt/converted/{translated_ppt}")
# else:
# print("The file does not exist")
# if os.path.exists(original_file_path):
# os.remove(original_file_path)
# else:
# print("The file does not exist")
# # whomtosend, titleofmail, dateofemail, context\
# # sendemail(
# # x.user_id.email,
# # "conversion complete",
# # date.today(),
# # context_email,
# # EMAIL_HOST_USER,
# # ).start()
# # sendmail(to_email=[x.user_id.email],email_code='CP2')
# return True
except Exception as e:
print("Errorr is", e)
# write refund code
x = pptconversion.objects.get(ppt_id=self.ppt)
auto_refund(x.central_payment_id)
class ppt_Files_Download(threading.Thread):
def __init__(self, ppt_file, Path):
self.ppt_file = ppt_file
self.Path = Path
threading.Thread.__init__(self)
def run(self):
download_file_System(self.ppt_file, self.Path)
class ppt_Original_Download(threading.Thread):
def __init__(self, ppt_file, Path):
self.ppt_file = ppt_file
self.Path = Path
threading.Thread.__init__(self)
def run(self):
download_file_System(self.ppt_file, self.Path)
def get_ppt_script(request):
if request.method == "POST":
df = pd.read_csv(rf"{basePath}/lpp/scripts.csv")
lang1 = request.POST.get("language")
print(lang1)
if lang1 == "":
lang1 = "English"
print(lang1, " : languages :: types : ", type(lang1))
list1_d = df.loc[df[lang1] == "D", "Script"].tolist()
print("Bakery 20.1: ", list1_d)
return JsonResponse({"data": list1_d})
# -> Initital Saving of PPT in database and extracting various languages present in that
def pptcovert(request):
print("Entered ConversionFunction")
# print("MY base path is " ,str(BASE_DIR))
if request.method == "POST":
start_time = time.time()
restrict = request.POST.get('restrict')
print(request.POST)
x = pptconversion()
x.ppt_string = str(time.time()) + "-ppt"
ppt_string = str(time.time()) + "-ppt"
script_id = int(time.time())
# request.session["script_id"] = str(script_id)
MyURL = ""
dial_src_script = ""
non_dial_src_lang = ""
non_dial_src_script = ""
script_title = ""
author_name = ""
numPages = 0
context = {}
print("pptuploadedfn")
user_id = request.user
x.upload_ppt = request.FILES.get("script")
file_path = str(request.FILES.get("script"))
request.session["originalppt"] = f"{basePath}/media/ppt/original/{file_path}"
x.user_id = request.user
request.session["pptstring"] = x.ppt_string
author_name = str(request.user.username)
script_title = x.upload_ppt.name.split("/")[-1]
request.session["slide_title"] = script_title
print("pptuploadedfn2")
prs = Presentation(x.upload_ppt)
numPages = len(prs.slides)
if restrict and numPages > 3:
numPages = 3
x.slide_count = numPages
print("Value of restrict:", restrict)
print("Number of pages:", numPages)
print(len(prs.slides), "pptuploadedfn3")
x.save()
MyURL = "/media/scripts/ppt/" + str(script_title)
i = 1
# Blockchain
pptconversion1 = {}
if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user)
private_Key = decryptionOfPrivate(blockchain_obj.privateKey)
contex = request.FILES.get("script")
with open(f"{basePath}/media/{x.upload_ppt}", 'rb') as _file:
hash = uploadDataToIPFSNode(_file)
pptconversion1["ppt_scriptFile_hash"] = hash
print("my_hash1", hash)
current_datetime = datetime.datetime.now()
pptconversion1["slide_count"] = numPages
pptconversion1["ppt_string"] = ppt_string
pptconversion1["script_title"] = script_title
pptconversion1["non_dial_src_lang"] = non_dial_src_lang
pptconversion1["author_name"] = author_name
pptconversion1["ppt_scriptFile_path"] = f"{basePath}/media/{x.upload_ppt}"
pptconversion1["upload_ppt"] = f"{x.upload_ppt}"
pptconversion1["date_at"] = current_datetime.strftime(
"%Y-%m-%d %H:%M:%S")
hash = hash_decrypation(hash)
certificatepath = certificateGenrate(request.user.username,"Original PPT",hash)
to_email = [request.user.email]
email_code = 'BL1'
key_value = {
"service":"Original PPT",
"hash": hash,
"public key":blockchain_obj.publicKey,
"private key":private_Key.decode('utf-8')
}
sendmail(to_email=to_email , email_code=email_code,key_value=key_value,filePath=certificatepath)
request.session["pptconversion1"] = str(pptconversion1)
for slide in prs.slides:
print("slide number %d" % i)
i += 1
etc_list = ["", " ", ",", " ,"]
sentence = ""
non_dial_src_lang = ""
script_use = ""
print('#9870124555')
# if slide.shapes[0].text is not None:
# sentence = slide.shapes[0].text
if slide.shapes[0].has_text_frame:
sentence = slide.shapes[0].text
sentence = re.sub(
"""[!@#$%^&*()+=}{:;"'<>?/_-]""", "", sentence)
if len(sentence) < 5:
continue
non_dial_src_lang = language_detector(sentence)
script_use = script_det(sentence)
if non_dial_src_lang != "" and script_use != "":
print(i, "slidessssssssssssss")
print(
non_dial_src_lang, script_use, "languagesssssssssssssssssssssss"
)
break
else:
if slide.has_notes_slide:
text_frame = slide.notes_slide.notes_text_frame
if len(text_frame.text) > 0:
try:
if text_frame.text in etc_list:
continue
# print("text", text_frame.text)
sentence = text_frame.text
translator = Translator()
non_dial_src_lang = language_detector(sentence)
script_use = script_det(sentence)
if non_dial_src_lang != "" and script_use != "":
break
except:
non_dial_src_lang = ""
sentence = ""
script_use = ""
else:
break
if sentence == "":
for shape in slide.shapes:
if not shape.has_text_frame:
continue
for paragraph in shape.text_frame.paragraphs:
for index, paragraph_run in enumerate(paragraph.runs):
try:
if paragraph_run.text in etc_list:
continue
sentence = paragraph_run.text
translator = Translator()
non_dial_src_lang = language_detector(
sentence)
script_use = script_det(sentence)
if non_dial_src_lang != "" and script_use != "":
break
except:
non_dial_src_lang = ""
sentence = ""
script_use = ""
else:
break
# slide = prs.slides[0]
# heading = slide.shapes.title.text
# translator = Translator()
# non_dial_src_lang = translator.detect(heading)
# print("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
# non_dial_src_lang.lang)
# script_use = script_det(heading)
# print("script used: ", script_use)
# print("The Data of formInput is:", formInput)
request.session["script_use"] = script_use
slang = languages.get(non_dial_src_lang)
if slang == None:
slang = "abc"
context = {
"id": user_id,
"numPages": numPages,
"ppt": x.upload_ppt,
"option4": languages,
"fileName": MyURL,
"non_dial_src_lang": non_dial_src_lang,
"non_dial_src_lang_full": slang,
"author_name": author_name,
"script_title": script_title,
"Uppt": prs,
}
print("-----------------------------------------------")
print(context)
end_time = time.time()
print("-------------Taken Time for input ppt processing->", end_time - start_time)
return render(request, "conversion/pptupload.html", context)
return render(request, "conversion/pptupload.html")
def pptDiscountHandler():
pass
# -> Actually Running Translation and Transliteration of PPT
def convertppt(request):
if request.method == "POST":
print("request.session variables", )
for key, value in request.session.items():
print('{} => {}'.format(key, value))
for key, value in request.POST.items():
print('{} => {}'.format(key, value))
try:
x = pptconversion.objects.get(ppt_string=request.session["pptstring"])
except:
x = pptconversion()
x.user_id = request.user
print("slides number are",x.slide_count)
try:
if x.upload_ppt:
print("exists ")
else:
x.upload_ppt = request.POST.get("fileUpload")
except:
x.upload_ppt = request.POST.get("fileUpload")
source_language = request.POST.get("non_dial_src_lang")
x.source_lang = languages[source_language]
try:
x.source_script = request.session["script_use"]
except:
x.source_script = language_script[str(x.source_lang)]
x.target_lang = request.POST.get("nondial_dest_language")
x.target_script = request.POST.get("dial_dest_script")
restrict = False
# x.sample = request.POST.get("restrict")
if request.POST.get("restrict") == 'on':
x.slide_count = 3
restrict = True
print(request.POST.get("to_be_vetted_by_lpp"), "Vetting on or off #787")
#sample blockchain
try:
pptconversion1 = eval(request.session["pptconversion1"])
except:
pptconversion1 = {}
if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
with open(f"{basePath}/media/{x.upload_ppt}", 'rb') as _file:
hash = uploadDataToIPFSNode(_file)
pptconversion1["ppt_scriptFile_hash"] = hash
print("my_hash1", hash)
current_datetime = datetime.datetime.now()
pptconversion1["slide_count"] = request.POST.get("numPages")
pptconversion1["ppt_string"] = request.POST.get("ppt_string")
pptconversion1["script_title"] = request.POST.get("script_title")
pptconversion1["non_dial_src_lang"] = request.POST.get("non_dial_src_lang")
pptconversion1["author_name"] = request.POST.get("author_name")
pptconversion1["ppt_scriptFile_path"] = f"{basePath}/media/{x.upload_ppt}"
pptconversion1["upload_ppt"] = f"{x.upload_ppt}"
pptconversion1["date_at"] = current_datetime.strftime(
"%Y-%m-%d %H:%M:%S")
request.session["pptconversion1"] = str(pptconversion1)
if request.POST.get("to_be_vetted_by_lpp") == "on":
x.lpp = True
pptconversion1["lpp"] = True
id = x.ppt_id
request.session["script_id"] = str(id)
try:
if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
blockchain_obj = UserCredentialsForBlockchain.objects.get(
user=request.user)
pptconversion1["source_lang"] = languages[source_language]
pptconversion1["target_lang"] = request.POST.get(
"nondial_dest_language")
pptconversion1["target_script"] = request.POST.get(
"dial_dest_script")
pptconversion1["ppt_id"] = request.session["script_id"]
UserId = blockchain_obj.user_id
Project = request.session["script_id"]
# Project = id
Data = str(pptconversion1)
userPrivateKey = blockchain_obj.privateKey
userkey = decryptionOfPrivate(userPrivateKey)
hash = UploadPPTConversionData(
OWNER_KEY,blockchain_obj.publicKey, UserId, Project, Data)
print("my_tx_hash", hash)
except:
pass
if x.slide_count <= 3:
x.amount = 0
x.save()
# with open(rf"{basePath}/ideamall/templates/ideamall/body.txt") as f:
# body = f.read()
# context_email = {
# "Date": date.today(),
# "Name": x.user_id.email,
# "emailcode": "",
# "heading1": "Thank you!",
# "heading2": " for using ppt conversion service "
# + " you will get notification whenever the conversation completes",
# "body": body,
# }
# whomtosend, titleofmail, dateofemail, context\
# sendemail(
# x.user_id.email,
# "Thankyou for using service",
# date.today(),
# context_email,
# EMAIL_HOST_USER,
# ).start()
print("Starting conversion of ppt")
print(x.upload_ppt)
ppt_conversion(x.ppt_id, request, restrict).start()
try:
del request.session["pptstring"]
except:
pass
sendmail(to_email=[x.user_id.email], email_code='CP4')
sendmail(to_email=[x.user_id.email], email_code='CP9')
print('is the email working for ppt')
print("ending conversion of ppt")
return render(request, "conversion/thanksppt.html")
# Blockchain implement
if request.POST.get("to_be_vetted_by_lpp") == "on":
lpp_available = "yes"
total_amount = round(int(float(pricing_data('PPT Conversion', 4))) * x.slide_count, 2)
else:
lpp_available = "no"
total_amount = round(int(float(pricing_data('PPT Conversion', 2))) * x.slide_count, 2)
print('All discounts ----------------------', centralPayment_get_discounts(request, total_amount))
pricelist = centralPayment_get_discounts(request, total_amount)
context = {}
context["ppt_id"] = id
request.session["ppt_id"] = str(id)
context["sub_total"] = round(total_amount, 2)
context["membership_discount"] = pricelist["membership_discount_calculate"]
context["staff_discount"] = pricelist["staff_discount_calculate"]
context["student_discount"] = pricelist["student_discount_calculate"]
context["early_bird_discount"] = pricelist["early_bird_calculate"]
context['total_discount'] = pricelist['total_discount']
context['net_service_charge'] = pricelist['net_service_charge']
context["total_payable"] = pricelist["total_payable"]
context["gst_calculate"] = pricelist["gst_calculate"]
context["gross_payable"] = pricelist["gross_payable"]
if request.POST.get("to_be_vetted_by_lpp") == "on":
calc = round(float((float(pricing_data("PPT Conversion", 4)) - float(pricing_data("PPT Conversion", 2))) / float(pricing_data("PPT Conversion", 4))) * pricelist["total_payable"], 2)
request.session['lppamount_after_discount'] = calc
if not privilegedUser1.objects.filter(user=request.user, is_active="yes").exists():
context["monthly_membership"] = 1
#old code to be destoyed
# context = {}
# context["ppt_id"] = id
# request.session["ppt_id"] = str(id)
# print("ending conversion of ppt1")
# # payment calculation for presentation
# pdiscount = 1
# sdiscount = 1
# mdiscount = 1 - RUNNING_DISCOUNT_CONVERSION / 100
# # if not privilegedUser1.objects.filter(
# # user=request.user, is_active="yes"
# # ).exists():
# # messages.success(request, "Become privileged member")
# # return redirect("payment")
# # return True
# if not privilegedUser1.objects.filter(
# user=request.user, is_active="yes"
# ).exists():
# # messages.success(request, "Become privileged member")
# # return redirect("payment")
# # request.session["directly_pay_monthly"] = 1
# context = {"directly_pay_monthly": 1}
# try:
# memberType = privilegedUser1.objects.get(
# user=request.user, is_active="yes"
# ).memberType
# print("ending conversion of ppt2")
# if memberType:
# if memberType == "normal":
# pdiscount = 1
# context["pdiscount"] = 0
# elif memberType == "yearly":
# pdiscount = 1 - YEARLY_MEMBER_ADDITIONAL / 100
# context["pdiscount"] = YEARLY_MEMBER_ADDITIONAL
# elif memberType == "Life Member":
# pdiscount = 1 - LIFE_MEMBER_ADDITIONAL / 100
# context["pdiscount"] = LIFE_MEMBER_ADDITIONAL
# except:
# pdiscount = 1
# # sdiscount = 1
# context["pdiscount"] = 0
# print("ending conversion of ppt3")
# if User.objects.get(id=request.user.id).is_staff:
# sdiscount = 1 - EMPLOY_DISCOUNT / 100
# else:
# sdiscount = 1
# if request.POST.get("to_be_vetted_by_lpp") == "on":
# lpp_available = "yes"
# amt = x.slide_count * CONVERSION_PER_PAGE
# context["total"] = round(amt, 2)
# lppamt = (x.slide_count * CONVERSION_PER_PAGE) + (
# x.slide_count * LPP_PER_PAGE
# )
# context["onlylppfee"] = round((x.slide_count * LPP_PER_PAGE), 2)
# amount_to_be_given_to_lpp = round(
# mdiscount * context["onlylppfee"] * pdiscount * sdiscount, 2
# )
# context["subtotal"] = round(lppamt, 2)
# context["amount"] = round(
# mdiscount * lppamt * pdiscount * sdiscount, 2)
# x.amount = context["amount"]
# request.session["pptamount"] = context["amount"]
# context["discount"] = lppamt - context["amount"]
# request.session["pptdiscount"] = lppamt - context["amount"]
# request.session["lppamount_after_discount"] = amount_to_be_given_to_lpp
# request.session["total_amount1"] = context["subtotal"]
# request.session["amount1"] = context["amount"]
# request.session["discount1"] = context["discount"]
# print("ending conversion of ppt4")
# else:
# print("ending conversion of ppt5")
# lpp_available = "no"
# amt = x.slide_count * CONVERSION_PER_PAGE
# context["total"] = round(amt, 2)
# context["subtotal"] = round(amt, 2)
# context["amount"] = round(
# mdiscount * amt * pdiscount * sdiscount, 2)
# context["discount"] = amt - context["amount"]
# x.amount = context["amount"]
# request.session["total_amount1"] = context["total"]
# request.session["amount1"] = context["amount"]
# request.session["discount1"] = context["discount"]
# request.session["pptamount"] = context["amount"]
# request.session["pptdiscount"] = amt - context["amount"]
# print("ending conversion of ppt6")
# context["conversion_per_page"] = CONVERSION_PER_PAGE
# context["lpp_per_page"] = LPP_PER_PAGE
# context["running_discount_conversion"] = RUNNING_DISCOUNT_CONVERSION
# context["employ_discount"] = EMPLOY_DISCOUNT
# context["yearly_member_additional"] = YEARLY_MEMBER_ADDITIONAL
# context["life_member_additional"] = LIFE_MEMBER_ADDITIONAL
# context["value_after_rd"] = round(
# ((context["running_discount_conversion"] / 100)) * context["subtotal"], 2)
# context["value_after_td"] = round(((context["employ_discount"] / 100)) * (
# 1 - (context["running_discount_conversion"] / 100)) * context["subtotal"], 2)
# context["value_after_md"] = round(((context["pdiscount"] / 100)) * (1 - (context["employ_discount"] / 100)) * (
# 1 - (context["running_discount_conversion"] / 100)) * context["subtotal"], 2)
context["restrict_to_five"] = "no"
context["lpp_available"] = lpp_available.upper()
context["numPages"] = x.slide_count
# context["script_title"] = x.script_title
context["ndial_src"] = x.source_lang
context["ndial_dest"] = x.target_lang
context["dial_dest_script"] = x.target_script
context["dial_src_script"] = x.source_script
context["ppt_title"] = request.session["slide_title"].split(".")[0]
print("ending conversion of ppt7")
x.save()
print("ending conversion of ppt8")
print("kuch na kaho3456")
try:
wall = Wallet.objects.get(user=request.user)
context["balance"] = round(wall.balance, 2)
print('Kya na kaho3456')
except:
context["balance"] = -1
with open(f"{basePath}/MNF/json_keys/conversionRates.json") as c:
curr = json.load(c)
try:
rate = curr["rates"]["INR"]
# c = CurrencyRates()
# rate = c.get_rate("USD", str(currency.upper()))
print("kuch na kaho3456789")
except Exception as e:
print("checkout error", e)
rate = 80
context["rate"] = rate
user = User.objects.get(id=request.user.id)
str1 = str(datetime.datetime.now()).split("-")
date_at = f'{str1[2][0:2]} - {str1[1]} - {str1[0]}'
context['date_at'] = date_at
try:
cd = centralDatabase.objects.get(user_id=request.user)
name = cd.firstName if cd.firstName else user.username
email_id = cd.email if cd.email else user.email
# phone_number = str(cd.countryCode) + str(cd.contact) if cd.contact else "N/A"
# address = cd.address if cd.address else "N/A"
except:
user = User.objects.get(id=request.user.id)
name = user.username
email_id = user.email
# phone_number = "N/A"
# address = "N/A"
context["name"] = name
context["email_id"] = email_id
context["phone_number"] = pricelist['contact'] if pricelist['contact'] else "N/A"
context["address"] = pricelist['address'] if pricelist['address'] else "N/A"
request.session['amount'] = context['gross_payable']
request.session["discount"] = context["total_discount"]
request.session["subtotal"] = context["sub_total"]
print("kuch na kaho34560000")
return render(request, "conversion/invoice_pptconversion.html", context)
# -> For Deleting your PPT
def delete_ppt(request, id):
# if request.method == "POST":
# x = pptconversion.objects.get(ppt_id=request.POST.get("pptid"))
# print(x, 'did i do that or what?')
# sendmail(to_email=[request.user.email],email_code='CP7')
sendmail(to_email=[request.user.email], email_code='CP7')
# pptconversion.objects.get(ppt_id=id).delete()
if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
try:
blockchain_obj = UserCredentialsForBlockchain.objects.get(
user=request.user)
userkey = decryptionOfPrivate(blockchain_obj.privateKey)
print("funcation is calling.......", userkey.decode(
'utf-8'), blockchain_obj.user_id, id)
deletePPTConversion(OWNER_KEY,blockchain_obj.publicKey, blockchain_obj.user_id, id)
print("funcation called......", userkey.decode(
'utf-8'), blockchain_obj.user_id, id)
pptconversion.objects.get(ppt_id=id).delete()
return HttpResponseRedirect("/conversion/view_conversion")
except:
pptconversion.objects.get(ppt_id=id).delete()
return HttpResponseRedirect("/conversion/view_conversion")
else:
pptconversion.objects.get(ppt_id=id).delete()
return HttpResponseRedirect("/conversion/view_conversion")
# -> Feedback on Conversion of PPT by User
def feedback_ppt(request):
if request.method == "POST":
x = pptconversion.objects.get(ppt_id=request.POST.get("pptid"))
if (
str(request.POST.get("error_text")) == " "
or str(request.POST.get("error_text")) == ""
):
x.error_faced_feedback = ""
else:
x.error_faced_feedback = str(request.POST.get("error_text"))
if request.POST.get("rating") == " " or request.POST.get("rating") == "":
x.translation_accuracy_rate = 0
else:
x.translation_accuracy_rate = int(request.POST.get("rating"))
x.improvement_feedback = str(request.POST.get("improvement"))
x.attention_feedback = str(request.POST.get("text"))
try:
x.exp_rate = int(request.POST.get("accurate"))
except:
pass
try:
x.content_accuracy_rate = int(request.POST.get("language"))
except:
pass
x.save()
with open(rf"{basePath}/ideamall/templates/ideamall/body.txt") as f:
body = f.read()
context_email = {
"Date": date.today(),
"Name": x.user_id.email,
"emailcode": "",
"heading1": "Thank you!",
"heading2": " your feedback is very important for us, thankyou for feedback ",
"body": body,
}
# whomtosend, titleofmail, dateofemail, context\
# sendemail(
# x.user_id.email,
# "Feedback recieved",
# date.today(),
# context_email,
# EMAIL_HOST_USER,
# ).start()
sendmail(to_email=[x.user_id.email], email_code='CP8')
print("feedback of ppt mail")
return redirect("view_conversion")
def ppt_tutorial(request):
return render(request,"conversion/Tutorial_video.html")
@login_required(login_url="/PersonalLogin-2")
def Get_Existing_Scripts(request):
scripts = MNFScriptDatabase.objects.filter(user_id = request.user.id).values_list('script_id', 'script_file_path')
if len(scripts) == 0:
return JsonResponse({"status":"Success", })
existing_scripts = {}
for script in scripts:
existing_scripts[str((((str(script[1]).split("/"))[-1]).split("."))[0])] = str(script[0])
return JsonResponse(existing_scripts)
@login_required(login_url="/PersonalLogin-2")
def load_existing_script(request, id):
# -> Loading Script
script = MNFScriptDatabase.objects.get(user_id = request.user, script_id = id)
context = {
"id": script.id,
"numPages": script.numPages,
"author_name": script.author_name,
"script_title": script.script_title,
"dial_src_script": script.dial_src_script,
"dial_src_lang_full": languages.get(script.dial_src_language),
"non_dial_src_script": script.nondial_src_script,
"non_dial_src_lang_full": languages.get(script.nondial_src_language),
"existing_script": True,
}
print("Redirecting to 2nd Page", context)
return render(request, "conversion2/conversion_processing.html", context)
def lpp_after_conversion_payment(request):
obj = ScriptTranslations.objects.get(translation_id=request.POST.get('translation_id'))
total_amount = round(int(float(pricing_data('Script Conversion', 4))
- float(pricing_data('Script Conversion', 2))) * obj.script_link_id.numPages, 2)
request.session['translation_id'] = request.POST.get('translation_id')
pricelist = centralPayment_get_discounts(request, total_amount)
print("pricelist", pricelist)
context = {}
context['script_title'] = (((obj.script_link_id.script_file_path.split("/"))[-1]).split("."))[0]
context['numPages'] = obj.script_link_id.numPages
context['ndial_src'] = languages[obj.script_link_id.nondial_src_language]
context['dial_src'] = languages[obj.script_link_id.nondial_src_language]
context["ndial_dest"] = languages[obj.nondial_dest_language]
context["dial_dest"] = languages[obj.dial_dest_language]
context["dial_dest_script"] = obj.dial_dest_script
if not privilegedUser1.objects.filter(user=request.user, is_active="yes").exists():
context["monthly_membership"] = 1
context["subtotal"] = round(total_amount, 2)
context["early_bird_calculate"] = pricelist["early_bird_calculate"]
context["staff_discount_calculate"] = pricelist["staff_discount_calculate"]
context["membership_discount_calculate"] = pricelist["membership_discount_calculate"]
context["student_discount_calculate"] = pricelist["student_discount_calculate"]
if int(pricelist['student_discount_calculate']) > 0:
request.session['student_discount_calculate'] = "Yes"
else:
request.session['student_discount_calculate'] = "No"
context['Total_discount'] = pricelist['total_discount']
context['remaining_amount'] = pricelist['total_payable']
context["net_service_charge"] = pricelist["net_service_charge"]
context["gst_calculate"] = pricelist["gst_calculate"]
context["net_payable"] = pricelist["gross_payable"]
request.session['amount'] = context["net_payable"]
request.session['subtotal'] = context["subtotal"]
request.session['discount'] = context["Total_discount"]
try:
wall = Wallet.objects.get(user=request.user)
context["balance"] = round(wall.balance, 2)
except:
context["balance"] = -1
with open(f"{basePath}/MNF/json_keys/conversionRates.json") as c:
curr = json.load(c)
try:
rate = curr["rates"]["INR"]
except Exception as e:
print("checkout error", e)
rate = 80
context["rate"] = rate
str1 = str(datetime.datetime.now()).split("-")
date_at = f'{str1[2][0:2]} - {str1[1]} - {str1[0]}'
context['date_at'] = date_at
user = User.objects.get(id=request.user.id)
try:
cd = centralDatabase.objects.get(user_id=request.user)
name = cd.firstName if cd.firstName else user.username
email_id = cd.email if cd.email else user.email
phone_number = str(cd.countryCode) + str(cd.contact) if cd.contact else "N/A"
address = cd.address if cd.address else "N/A"
except:
name = user.username
email_id = user.email
phone_number = "N/A"
address = "N/A"
context["name"] = name
context["email_id"] = email_id
context["phone_number"] = phone_number
context["address"] = address
print("7878Context is :", context)
return render(request, "conversion/invoice_lpp.html", context)
def paymentDoneLpp(request, gateway):
if not request.session['translation_id'] or (gateway != "stripe" and gateway != "razorpay"):
return HttpResponseBadRequest()
if gateway == "stripe":
response = {
"id": request.GET.get("payment_intent"),
"client_secret": request.GET.get("payment_intent_client_secret"),
"status": request.GET.get("redirect_status"),
}
callback_content = callback(response, request)
if callback_content['payment_status'] != "success":
return render(request, "payments/failed.html")
if request.session["pay_with_wallet"] == "yes":
# deduction_for_sep_wall(request)
wall = Wallet.objects.get(user=request.user)
print("final balance", round(wall.balance, 2) - (
round(request.session["pay_wallet_deduction"], 2)))
wall.balance = round(wall.balance, 2) - (
round(request.session["pay_wallet_deduction"], 2))
wall.save()
elif gateway == "razorpay":
callback_context = callback(request.POST, request)
if callback_context['payment_status'] != 'success':
subject = "Something really went wrong"
# from_email = settings.EMAIL_HOST_USER
# to =
to = request.user.email
key_value = {
"service_name": "Conversion",
}
sendmail(to_email=[to], email_code="CP11", key_value=key_value)
# context_2 = {
# "Name": request.user.email,
# "service_name": "Conversion",
# }
# message = render_to_string('payment/templates/payments/MR24.html', context_2)
#
#
# # password = emails_creadentials.objects.get(email="noreply@mynextfilm.ai")
# connection = get_connection(host="smtp.gmail.com", port=587, username="noreply@mynextfilm.ai",
# password="iiby yciy jdux fslv", use_tls=True)
# to_email = request.user.email
# email = EmailMessage(subject, message, to=[to_email], connection=connection)
# email.send()
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR24.html", context_2, from_email)
return render(request, "payments/failed.html")
if request.session["pay_with_wallet"] == "yes":
# deduction_for_sep_wall(request)
wall = Wallet.objects.get(user=request.user)
print("----------------amount", request.session["pay_wallet_deduction"])
print("----------------rate", request.session["CurrencyRate"])
print("final balance", round(wall.balance, 2) - (round(request.session["pay_wallet_deduction"], 2)))
wall.balance = round(wall.balance, 2) - (round(request.session["pay_wallet_deduction"], 2))
wall.save()
obj = ScriptTranslations.objects.get(translation_id=request.session.get('translation_id', None))
obj.lpp = True
obj.save()
X = LPPTASKDatabase()
X.user_id = obj.user_id
X.usernote = "Kindly check if the translated file is correct as per the Uploaded Document!"
X.translated_script = obj
X.generated_from = "conversion"
temp_amount = request.session["amount"]
X.amoutgiventolpp_action = round((temp_amount / 2), 2)
X.amoutgiventolpp_dialogue = round((temp_amount / 2), 2)
X.save()
# task_assigner(int(X.task_id), "conversion")
return redirect('view_conversion')
def paymentIntentlpp(request):
if request.method == "POST":
set_payment_token(request)
keyID = request.session["keyID"]
for key, value in request.session.items():
print('{} => {}'.format(key, value))
total_amount = request.session["amount"]
total_amount1 = request.session["subtotal"]
# amount_charged = request.session["amount"]
amount_discount = request.session["discount"]
request.session["pay_with_wallet"] = "no"
request.session["amount_before_pay_wallet"] = total_amount
# is he instituitional student or not
if request.session.get("student_discount_calculate") == "Yes":
from institutional.models import AffiliatedStudent, UnaffiliatedStudent, WaitForInstituteStudent
user = User.objects.get(pk=request.user.id)
if UnaffiliatedStudent.objects.filter(user=user).exists():
user = UnaffiliatedStudent.objects.get(user=user)
if user.free_credits >= total_amount:
user.free_credits -= total_amount
user.save()
context = {
"mode": "Institutional User",
}
return JsonResponse(context)
elif user.free_credits < total_amount:
total_amount -= user.free_credits
user.free_credits = 0
user.save()
elif WaitForInstituteStudent.objects.filter(user=user).exists():
user = WaitForInstituteStudent.objects.get(user=user)
if user.free_credits >= total_amount:
user.free_credits -= total_amount
user.save()
context = {
"mode": "Institutional User",
}
return JsonResponse(context)
elif user.free_credits < total_amount:
total_amount -= user.free_credits
user.free_credits = 0
user.save()
return True
elif AffiliatedStudent.objects.filter(user=user).exists():
user = AffiliatedStudent.objects.get(user=user)
if user.free_credits >= total_amount:
user.free_credits -= total_amount
user.save()
context = {
"mode": "Institutional User",
}
return JsonResponse(context)
elif user.free_credits < total_amount:
total_amount -= user.free_credits
user.free_credits = 0
user.save()
try:
print("pay_wallet it is", request.POST.get("pay_wallet"))
if request.POST.get("pay_wallet") == "true":
request.session["pay_with_wallet"] = "yes"
with open(f"{basePath}/MNF/json_keys/conversionRates.json") as c:
curr = json.load(c)
try:
rate = curr["rates"]["INR"]
except Exception as e:
rate = 80
print("Checking Wallet")
wall = Wallet.objects.get(user=request.user)
if wall.balance >= (total_amount * rate):
print("wallet if hai")
request.session["pay_wallet_deduction"] = round(total_amount * rate, 2)
total_amount = 0
else:
print("wallet else hai")
request.session["pay_wallet_deduction"] = round(wall.balance, 2)
total_amount = round((round(total_amount * rate, 2) - round(wall.balance, 2)) / rate, 2)
except Exception as e:
print("Error is:",e)
pass
request.session["amount"] = total_amount
services_used = 1
context = create_indent(request, 'LPP', str(
request.session['translation_id']), services_used, '', total_amount1, total_amount, amount_discount)
for key, value in request.session.items():
print('{} => {}'.format(key, value))
with open(f"{basePath}/MNF/json_keys/conversionRates.json") as c:
curr = json.load(c)
try:
rate = curr["rates"]["INR"]
except Exception as e:
rate = 80
request.session["CurrencyRate"] = rate
centralPayment_instance = CentralPayment.objects.get(
id=context["central_pay_id"])
# handle razor pay gateway →
if "orderId" in context:
request.session["payment_order_id"] = context["orderId"]
request.session["central_payment_id"] = context["central_pay_id"]
pid = centralPayment_instance.order_id
amtINR = round(centralPayment_instance.amount_charged * rate, 2)
context = {
"mode": "RazorPay",
"pk": keyID,
"amtINR": amtINR,
"pid": pid,
"amount": centralPayment_instance.amount_charged,
}
return JsonResponse(context)
# handle stripe gateway →
elif "client_secret" in context:
# save central payment details in your database
request.session["payment_order_id"] = context["client_secret"]
request.session["central_payment_id"] = context["central_pay_id"]
amtINR = round(centralPayment_instance.amount_charged * rate, 2)
context = {
"mode": "Stripe",
"pk": context["pub_key"],
"total_amount": centralPayment_instance.amount_charged,
"secret_key": context["client_secret"],
"amtINR": amtINR,
}
return JsonResponse(context)
# handle corporate profile →
elif "monthly_user" in context:
request.session['central_pay_id'] = context["central_pay_id"]
context = {
"mode": "Corporate User",
}
return JsonResponse(context)
@csrf_exempt
def conversion_process_starter(request):
# if request.method == "POST":
# print("this are the params", request.POST)
# for key in ["translation_id"]:
# if key not in request.POST:
# return HttpResponseBadRequest()
# print("Started Execution")
# try:
# translated_script = ScriptTranslations.objects.get(translation_id=request.POST.get("translation_id", None))
# conversion_params = {
# "user": translated_script.user_id,
# "file_path": "/home/mnfidea/mnf/MNF/app/media/" + translated_script.script_link_id.script.name,
# "original_script_id": translated_script.script_link_id.script_id,
# "translated_script_id": translated_script.translation_id,
# "sample_id": request.POST.get("sample_id", None),
# "existing_script": request.POST.get("existing_script", None),
# "iteration_no": request.POST.get("iteration_no", None),
# "juggernaut_pages_deduction": request.POST.get("juggernaut_pages_deduction", None),
# "language_set": request.POST.get("language_set", None),
# "amount_without_subscrption": request.POST.get("amount_without_subscrption", None),
# }
# obj = Conversion(**conversion_params)
# background_thread = threading.Thread(target=background_execution, args=(obj,))
# background_thread.start()
# # obj.convert()
# return JsonResponse({"status":"Process Started"})
# except Exception as e:
# print("error:", e)
# return JsonResponse({"status":"error", "description":str(e)})
import boto3
session = boto3.Session(
aws_access_key_id='AKIAQVLBBGCB45RMLKVW', # replace with your key
aws_secret_access_key='ZWc6KOc5LuBLuCEBDDfQTor+Q7rp3fFH74gVt+AA', # replace with your key
)
sqs = session.resource('sqs', region_name='ap-south-1')
from mnfapp.models import ScriptTranslations
print("Started Executin this from conversion")
queue = sqs.get_queue_by_name(QueueName="mnfqueue")
# try:
messages = queue.receive_messages(
MessageAttributeNames=["All"],
MaxNumberOfMessages=5,
WaitTimeSeconds=20,
)
msg = messages[0]
for msg in messages:
try:
print("Received message: %s: %s", msg.message_id, msg.body)
print(type(msg.body))
body_dict = json.loads(msg.body)
translated_script = ScriptTranslations.objects.get(translation_id=body_dict["translation_id"])
object_key = "INPUT/" + (translated_script.script_link_id.script.name.split("/"))[-1]
local_file_path = "/home/ubuntu/Conversion_Kitchen_Code/kitchen_counter/media/" + translated_script.script_link_id.script.name
s3_client = boto3.client('s3',
aws_access_key_id="AKIAQVLBBGCB45RMLKVW",
aws_secret_access_key="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",
region_name="ap-south-1"
)
s3_client.download_file("conversion-kitchen", object_key, local_file_path)
conversion_params = {
"user": translated_script.user_id,
"file_path": str(basePath) + "/media/" + translated_script.script_link_id.script.name,
"original_script_id": translated_script.script_link_id.script_id,
"translated_script_id": translated_script.translation_id,
"sample_id": body_dict.get('sample_id', None),
"existing_script": body_dict.get('sample_id', None),
"iteration_no": body_dict.get('iteration_no', None),
"juggernaut_pages_deduction": body_dict.get("juggernaut_pages_deduction", None),
"language_set": body_dict.get("language_set", None),
"amount_without_subscrption": body_dict.get("amount_without_subscrption", None)
}
print("reached here")
obj = Conversion(**conversion_params)
# obj.convert()
background_thread = threading.Thread(target=background_execution, args=(obj,))
background_thread.start()
# background_thread.join()
msg.delete()
return JsonResponse({"sattus":"process started"})
except Exception as error:
print("error execution from queue: %s", error)