from mnfapp.views import base, languages as lang import re from django.contrib import messages from MNF.settings import BasePath, COUNTRY_KEY, EMAIL_HOST_USER from mnfapp.models import MNFScriptDatabase from mnfapp.models import SampleScript, PaymentData from datetime import date import pandas as pd import time # from mnfapp.views import PaymentDetails # from scriptAudit.script_audit_codes.script_audit import do_script_audit # from neutralAudit.mnf_script_audit_v8 import call_script_audit_for_conversion # from neutralAudit.views import audit1 from payment.models import conversionPayment, privilegedUser1 from forex_python.converter import CurrencyRates from mnfapp.models import * from users.models import * import stripe from django.shortcuts import redirect from PyPDF2 import PdfFileReader, PdfFileWriter from .forms import CScript, SScript, AScript from .models import UploadScript, StoryConversion, BookConversion, pptconversion from MNF.settings import ( BasePath, YEARLY_MEMBER_ADDITIONAL, RUNNING_DISCOUNT_CONVERSION, STRIPE_SECRET_KEY, STRIPE_PUBLISHABLE_KEY, RAZORPAY_KEY_ID, RAZORPAY_KEY_SECRET, CONVERSION_PER_PAGE, STRIPE_PLATFORM_FEE, RAZORPAY_PLATFORM_FEE, LIFE_MEMBER_ADDITIONAL, EMPLOY_DISCOUNT, LPP_PER_PAGE, ) import subprocess from django.shortcuts import render from django.contrib.auth.decorators import login_required from .translation.detection import getInputs, script_det, language_detector import random from googletrans import Translator from subprocess import Popen from pptx import Presentation # from conversion.translation import final_translation from conversion.translation.twostepconversion import translate_function from mnfapp.models import MNFScriptDatabase, Notifications from ideamall.views import sendemail from page_script.models import MNFScriptDatabase_2, Conversions, Conversion_link from django.contrib.auth.decorators import login_required from pymongo import MongoClient from django.core.mail import EmailMessage from django.conf import settings from django.http import HttpResponse, JsonResponse, HttpResponseRedirect from pathlib import Path from django.core.files.storage import FileSystemStorage from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.html import strip_tags import os import datetime import razorpay from pytz import timezone from django.contrib.auth.models import User from .booktranslator.newConvertBook import convert_books # from .storytranslator.trans import convert_story from lpp.views import task_assigner from lpp.models import LPPTASKDatabase import threading from threading import Thread # ppt convert from conversion.ppt_translation.final_srt_ppt import translate_presentation from page_script.views import service_update_internal 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 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", } # -> 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 # 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") # -> 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() # -> Countimg 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 # -> Initital Saving of Script in database and extracting various languages present in that def conversion(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": M = MNFScriptDatabase() UScript = CScript(request.POST, request.FILES) if UScript.is_valid(): M.script = UScript.cleaned_data.get("script") 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" ) MyURL = "/media/" + str(script_title) formInput = getInputs(str(BASE_DIR) + MyURL) 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] 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, } return render(request, "conversion/conversion.html", context) return render( request, "conversion/conversion.html", { "list": sampleList, "language_pairs": language_pairs, "default_script": default_script, "script_pairs": script_pairs, }, ) # -> 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 obj.translated_script_path: return JsonResponse({"status": "success"}, status=200) else: return JsonResponse({"status": "pending"}, status=202) # -> Actually Running Translation and Transliteration of script def make_conversion(request): print("MAke Conversion mein hu") script_file_path = request.GET["script_file_path"] request_id = request.GET["request_id"] str1 = str(script_file_path) if str1[41:45] == "user": script_file_path = "/home/" + str(str1[41:]) script_id = request.GET["script_id"] dial_conv_script = request.GET["dial_conv_script"] dial_src_lang = request.GET["dial_src_lang"] non_dial_src_lang = request.GET["non_dial_src_lang"] dial_src_script = request.GET["dial_src_script"] restrict_to_five = request.GET["restrict_to_five"] option3 = request.GET.get("option3") option4 = request.GET.get("option4") option5 = request.GET.get("option5") option6 = request.GET.get("option6") if request.GET["centralised"] == "yes": service_update_internal(script_id, request_id, "Conversion", "20% Completed") 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 script_file_path = str(basePath) + script_file_path script_title = str( MNFScriptDatabase_2.objects.get(script_id=script_id).script_name ) dial_dest_lang = obj.dial_dest_language dial_dest_script = obj.dial_dest_script non_dial_dest_lang = obj.nondial_dest_language dual_dial_script = obj.dual_dial_script # Yes,No else: user_script_data = MNFScriptDatabase.objects.get(script_id=script_id) script_title = user_script_data.script_title dial_dest_lang = user_script_data.dial_dest_language dial_dest_script = user_script_data.dial_dest_script non_dial_dest_lang = user_script_data.nondial_dest_language dual_dial_script = user_script_data.dual_dial_script # Yes,No print("Conversion Translation is Starting") print( rf'translate_function("{script_file_path}", "{script_id}", "{dial_conv_script}", "{dial_src_lang}","{non_dial_src_lang}", "{dial_src_script}", "{restrict_to_five}", "{option3}", "{option4}", "{option5}", "{option6}")' ) if request.GET["centralised"] == "yes": service_update_internal(script_id, request_id, "Conversion", "30% Completed") pass # try: translate_function( script_file_path, script_id, dial_src_lang, non_dial_src_lang, dial_src_script, restrict_to_five, option3, option4, option5, option6, request.GET["centralised"], ) if request.GET["centralised"] == "yes": service_update_internal(script_id, request_id, "Conversion", "90% Completed") pass if request.GET.get("to_be_vetted_by_lpp") == "on": if request.POST.get("centralised") == "yes": # Vetting is not allowed from Page_script conversions pass else: obj = MNFScriptDatabase.objects.get(script_id=script_id) 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["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") print("Script Translated successfully and Sent for Vetting if chosen") if request.GET["centralised"] == "yes": pass service_update_internal(script_id, request_id, "Conversion", "Completed") user = request.user subject = "Conversion Generated Successfully " + "." from_email = EMAIL_HOST_USER to = request.user.email response = redirect("narration").url path = request.build_absolute_uri(response) context = { # "Name": user, "script_id": script_id, "script_name": script_title, "dual_dial": dual_dial_script, "dial_src_lang": dial_src_script, "dial_dest_lang": languages.get(dial_dest_lang), "non_dial_dest_lang": languages.get(non_dial_dest_lang), "non_dial_src_lang": languages.get(non_dial_src_lang), "dial_dest_script": dial_dest_script, "status": "Success", "path": path, } html_content = render_to_string( "conversion/email.html", context ) # render with dynamic value print(html_content, "this is a html content ****************** ") # 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. print("email process started") msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() print("after mail has been sent my context is", context) return JsonResponse(context, status=200) # except Exception as e: # print("Error:", e) # print( # "Script translation failed due to some internal error. If you have made any payment for conversion that will be refunded" # ) # payment_intent_id = user_script_data.payment_intent_id # print( # "translated script file path in except", # user_script_data.translated_script_path # ) # if request.POST.get("centralised") == "yes": # obj = MNFScriptDatabase_2.objects.get(script_id=script_id) # else: # obj = MNFScriptDatabase.objects.get(script_id=script_id) # print("obj.script converted function", obj.translated_script_path) # if payment_intent_id: # if payment_intent_id[0:4] == "pay": # client = razorpay.Client(auth=(keyID, keySecret)) # payment_id = payment_intent_id # paydetail = client.payment.fetch(payment_id) # total_amount = request.POST.get( # "total_amount") - (paydetail["fee"] / 100) # 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 # payment_amount = int(float(total_amount) * 100 * rate) # client.payment.refund( # payment_id, {"amount": payment_amount, "speed": "normal", }) # else: # stripe.Refund.create(payment_intent_id) # return JsonResponse({}, status=505) # -> For Viewing Your Conversion @login_required def view_conversion(request): ppt = pptconversion.objects.filter( user_id=request.user.id).order_by("-date_at") ppt_all = pptconversion.objects.filter(user_id=request.user.id).count() number = ReferUser.objects.filter(reffered_by=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.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.script_id == task.translated_script.script_id: script_is_vetted[-1]["0"] = "1" script_is_vetted[-1]["1"] = task.outputfile lenV = len(script_path) countOfScript = len(script_is_vetted) 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, }, ) # -> For Deleting your Conversion def delete_script(request, id): MNFScriptDatabase.objects.get(id=id).delete() return HttpResponseRedirect("/conversion/view_conversion") # -> Feedback on Conversion by User def feedback_user(request): if request.method == "POST": x = MNFScriptDatabase.objects.get(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("rating2")) if request.POST.get("rating3") == " " or request.POST.get("rating3") == "": x.translation_accuracy_rate = 0 else: x.translation_accuracy_rate = int(request.POST.get("rating3")) x.save() return redirect("view_conversion") # -> For Demo of Conversion def demo(request): number = ReferUser.objects.filter(reffered_by=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}) # -> Conversion Checkout def conversionCheckout(request): if request.method == "POST": if request.POST.get("want_to_be_vetted") == "yes": 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: 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" ) if request.POST["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"] = wall.balance - (balance*rate) wall.save() request.session["amount"] = payable total_amount = request.session["amount"] 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/checkoutC_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/checkoutC.html", context) return render(request, "conversion/conversion.html") # ppt checkout # -> Conversion Checkout def pptCheckout(request): 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: total_amount = request.session["pptamount"] request.session["want_to_be_vetted"] = "off" if request.POST["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"] = wall.balance - (balance*rate) wall.save() request.session["amount"] = payable total_amount = request.session["amount"] 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") # -> Conversion Checkout @login_required 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": context = { "pk": STRIPE_PUB_KEY, "payment_intent_secret": pi.client_secret, } return render(request, "conversion/3dsecuredConversion.html", context) return render(request, "payments/paymentdone.html") # -> Conversion Stripe Payment Done Message def paymentDoneC(request): 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"] non_dial_src_script = request.session["non_dial_src_script"] dual_dial_script = request.session["dual_dial_script"] 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"] 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) if pi.status == "succeeded": if Wallet.objects.filter(user=request.user).exists(): wall = Wallet.objects.get(user=request.user) wall.balance = request.session["fbalance"] wall.save() c = conversionPayment() 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 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.save() # -----------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, "script_title": script_title, "script_file_path": script_file_path, "dial_conv_script": dial_conv_script, "nondial_dest_language": nondial_dest_language, "dial_dest_language": dial_dest_language, "dial_dest_script": dial_dest_script, "dial_src_lang": dial_src_lang, "non_dial_src_lang": non_dial_src_lang, "dial_src_script": dial_src_script, "dual_dial_script": dual_dial_script, "total_amount": total_amount, "to_be_vetted_by_lpp": to_be_vetted_by_lpp, "restrict_to_five": "no", "option3": option3, "option4": option4, "option5": option5, "option6": option6, } return render(request, "conversion/my_conversions.html", context) else: return render(request, "payments/failed.html") # -> Conversion Razorpay Payment Done Message def paymentDoneC_RazorPay(request): 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"] 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"] 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) except: return render(request, "payments/failed.html") if Wallet.objects.filter(user=request.user).exists(): wall = Wallet.objects.get(user=request.user) wall.balance = request.session["fbalance"] wall.save() c = conversionPayment() 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 s.payment_intent_id = razorpay_payment_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.save() # 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 = "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, ) context = { "script_id": script_id, "script_title": script_title, "script_file_path": script_file_path, "dial_conv_script": dial_conv_script, "nondial_dest_language": nondial_dest_language, "dial_dest_language": dial_dest_language, "dial_dest_script": dial_dest_script, "dial_src_lang": dial_src_lang, "non_dial_src_lang": non_dial_src_lang, "dial_src_script": dial_src_script, "dual_dial_script": dual_dial_script, "total_amount": total_amount, "to_be_vetted_by_lpp": to_be_vetted_by_lpp, "restrict_to_five": "no", "option3": option3, "option4": option4, "option5": option5, "option6": option6, } return render(request, "conversion/my_conversions.html", context) else: return render(request, "payments/failed.html") # -> Conversion Razorpay Payment Done Message def paymentDoneppt_RazorPay(request): 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() return render(request, "payments/failed.html") if Wallet.objects.filter(user=request.user).exists(): 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 ppt_conversion(x.ppt_id, request).start() return render(request, "conversion/thanksppt.html") else: x.delete() return render(request, "payments/failed.html") # -> Conversion Stripe Payment Done Message def paymentDoneppt_stripe(request): if request.method == "POST": 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() return render(request, "payments/failed.html") if pi.status == "succeeded": if Wallet.objects.filter(user=request.user).exists(): 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() return render(request, "payments/failed.html") # # -> At 10sec intervals check if story conversion completed # def is_story_converted(request): # story_id = request.GET["story_id"] # obj = StoryConversion.objects.get(story_id=story_id) # print("obj.script convetred function", obj.translated_story_docx) # if obj.translated_story_docx: # return JsonResponse({"status": "success"}, status=200) # else: # return JsonResponse({"status": "pending"}, status=202) # # -> Actually Running Translation and Transliteration of story # def my_story(request): # y = StoryConversion.objects.get(story_id=str(request.GET["story_id"])) # filename = basePath + "/media/" + str(y.upload_story) # src_lang = str(y.source_language) # target_lang = str(y.target_language) # filename_true = filename.replace("(", "") # filename_true2 = filename_true.replace(")", "") # try: # output = convert_story(filename_true2, src_lang, target_lang) # # some_translated_script_path = output # y.translated_story_docx = str(output)[27:] # y.save() # return JsonResponse({"status": "success"}, status=200) # except: # return JsonResponse({}, status=505) # # -> Initital Saving of Story in database and extracting various languages present in that # def convert_storyy(request): # if request.method == "POST": # y = StoryConversion() # 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.story_id = "story_" + str(str4) # UScript = SScript(request.POST, request.FILES) # if UScript.is_valid(): # y.upload_story = UScript.cleaned_data.get("story") # y.target_language = lang[request.POST.get("target_lang")] # y.source_language = lang[request.POST.get("src_lang")] # y.save() # return render(request, "conversion/my_stories.html", {"story_id": y.story_id}) # return render(request, "conversion/convertStory.html") # # -> For Viewing Your Stories # def view_converted_stories(request): # number = ReferUser.objects.filter(reffered_by=request.user).count() # obj = StoryConversion.objects.filter(user_id=request.user).order_by("-date_at") # script_path = [] # pq = 0 # for i in obj: # if i.translated_story_docx != "": # script_path.append(i.translated_story_docx) # pq += 1 # return render( # request, # "conversion/viewStory.html", # {"script_path": obj, "pq": pq, "number": number}, # ) # # -> For Deleting your Story # def delete_converted_story(request, id): # StoryConversion.objects.get(id=id).delete() # return HttpResponseRedirect("/conversion/view_converted_stories") # -> Actually Running Translation and Transliteration of book def my_book(request): print("Entering My_Book Conversion Function") y = BookConversion.objects.get(book_id=str(request.GET["book_id"])) pdf = PdfFileReader(open(basePath + "/media/" + str(y.upload_book), "rb")) numpages = pdf.getNumPages() print(numpages) if numpages <= 10: # try: path = (convert_books(basePath + "/media/" + str(y.upload_book)).split("/"))[6:] 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 = str(orig_path) y.save() print("Entering My_Book Conversion Function") return JsonResponse({"status": "success"}, status=200) else: intermediate_pages = [] # if numpages % 10 != 0: hard_pages = numpages // 10 for i in range(hard_pages): page = (10 * i, 10 * (i + 1)) intermediate_pages.append(page) final_pages = numpages - 10 * hard_pages intermediate_pages.append( (10 * hard_pages, 10 * hard_pages + final_pages)) print("counter 1234") print(intermediate_pages) for page_start, page_end in intermediate_pages: # from PyPDF2 import PdfFileWriter, PdfFileReader # pdf_reader = PdfFileReader(open(filename, "rb")) pdf_writer1 = PdfFileWriter() for page in range(page_start, page_end): pdf_writer1.addPage(pdf.getPage(page)) with open( f"/home/user/mnf/project/MNF/media/part_{page_start}_{page_end}.pdf", "wb", ) as file1: pdf_writer1.write(file1) pass # -> 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) # -> Initital Saving of Book in database and extracting various languages present in that def convert_book(request): if request.method == "POST": print("Entering Convert Bok Function") 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) Book = AScript(request.POST, request.FILES) if Book.is_valid(): y.upload_book = Book.cleaned_data.get("myfile") y.source_language = lang[request.POST.get("src_lang")] y.target_language = lang[request.POST.get("target_lang")] y.save() print("Exiting Convert Bok Function") return render(request, "conversion/my_books.html", {"book_id": y.book_id}) return render(request, "conversion/convertBook.html") # -> For Viewing Your Books def view_converted_books(request): number = ReferUser.objects.filter(reffered_by=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): BookConversion.objects.get(id=id).delete() return HttpResponseRedirect("/conversion/view_converted_books") # -> For making Translated PPT's class ppt_conversion(threading.Thread): def __init__(self, ppt, request): self.ppt = ppt self.request = request threading.Thread.__init__(self) def run(self): # try: x = pptconversion.objects.get(ppt_id=self.ppt) presentation = Presentation(x.upload_ppt) 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 translate_presentation(presentation, source, target, x.target_script) 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() # For Vetting # if request.session # obj = ppt.objects.get(script_id=script_id) 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") 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!", "heading2": " your presentation is converted", "body": body, } # whomtosend, titleofmail, dateofemail, context\ sendemail( x.user_id.email, "conversion complete", date.today(), context_email, EMAIL_HOST_USER, ).start() return True # except: # pass # write refund code 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": x = pptconversion() x.ppt_string = str(time.time()) + "-ppt" 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") 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) x.slide_count = numPages print(len(prs.slides), "pptuploadedfn3") x.save() MyURL = "/media/scripts/ppt/" + str(script_title) i = 1 for slide in prs.slides: print("slide number %d" % i) i += 1 etc_list = ["", " ", ",", " ,"] sentence = "" non_dial_src_lang = "" script_use = "" if slide.shapes[0].text is not None: 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 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": languages.get(non_dial_src_lang), "author_name": author_name, "script_title": script_title, "Uppt": prs, } print("-----------------------------------------------") print(context) return render(request, "conversion/pptupload.html", context) return render(request, "conversion/pptupload.html") # -> Actually Running Translation and Transliteration of PPT def convertppt(request): if request.method == "POST": x = pptconversion.objects.get(ppt_string=request.session["pptstring"]) source_language = request.POST.get("non_dial_src_lang") x.source_lang = languages[source_language] x.source_script = request.session["script_use"] x.target_lang = request.POST.get("nondial_dest_language") x.target_script = request.POST.get("dial_dest_script") print(request.POST.get("to_be_vetted_by_lpp"), "Akashhhh") if request.POST.get("to_be_vetted_by_lpp") == "on": x.lpp = True id = x.ppt_id 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") ppt_conversion(x.ppt_id, request).start() print("ending conversion of ppt") return render(request, "conversion/thanksppt.html") context = {} context["ppt_id"] = 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") 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 print("ending conversion of ppt3") if User.objects.get(id=request.user.id).is_staff: sdiscount = 1 - EMPLOY_DISCOUNT / 100 if request.POST.get("to_be_vetted_by_lpp") == "on": lpp_available = "yes" amt = x.slide_count * CONVERSION_PER_PAGE context["subtotal"] = 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["sublpptotal"] = 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 print("ending conversion of ppt4") else: print("ending conversion of ppt5") lpp_available = "no" amt = x.slide_count * CONVERSION_PER_PAGE context["subtotal"] = round(amt, 2) context["amount"] = round( mdiscount * amt * pdiscount * sdiscount, 2) context["discount"] = amt - context["amount"] x.amount = context["amount"] 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["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["script_title"] = request.session["slide_title"].split(".")[0] print("ending conversion of ppt7") x.save() print("ending conversion of ppt8") try: wall = Wallet.objects.get(user=request.user) context["balance"] = wall.balance 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 return render(request, "conversion/ppt_checkout.html", context) # -> For Deleting your PPT def delete_ppt(request, id): 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() print("feedback of ppt mail") return redirect("view_conversion")