Conversion_Kitchen_Code/kitchen_counter/lpp/LPP/views.py

4843 lines
194 KiB
Python
Executable File

# from tkinter.messagebox import NO
# import phonenumbers
# from project.MNF.narration.views import character_list
# from tkinter import E
import concurrent.futures
import datetime
import io
import json
import logging
import os
import random
import re # added import
import select
import subprocess
import sys
import time
from centralizePayment.models import CentralPayment
import traceback
import zipfile # added import
from io import StringIO
from itertools import zip_longest
from pathlib import Path
from queue import Queue
from subprocess import Popen
import razorpay
import requests
import stripe
from asgiref.sync import async_to_sync
from bs4 import BeautifulSoup
from bs4.element import Comment
from channels.generic.websocket import (AsyncWebsocketConsumer,
WebsocketConsumer)
from channels.layers import get_channel_layer
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.sites.shortcuts import get_current_site
from django.core.files.base import ContentFile
from django.core.mail import EmailMessage, EmailMultiAlternatives
from django.db.models.signals import post_save
from django.dispatch import Signal, receiver
from django.forms import ValidationError as FormValidationError
# sse
from django.http import (HttpResponse, HttpResponseRedirect, JsonResponse,
StreamingHttpResponse)
from django.shortcuts import redirect, render
from django.template import loader
# Multiligule
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.encoding import force_bytes
from django.utils.html import strip_tags
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_GET
from forex_python.converter import CurrencyRates
from google.cloud import texttospeech
from google.cloud import translate_v2 as Translate
from PyPDF2 import PdfFileReader
from pytz import timezone
from tqdm import tqdm
from urllib3 import HTTPResponse
# Websocket
from auto_email.views import sendmail
from users.models import UserCredentialsForBlockchain
from Blockchain2.decryption import decryptionOfPrivate, decryptionOfUrl, download_file_System
from Blockchain2.DataStorage import uploadDataToIPFSNode
from Blockchain2.Narration import getUserprojectIds,NarrationData,getNarrationData
import tempfile
from Blockchain2.blockchainsetting import (GET_OWNER, SET_ONLY_OWNER,
UPLOAD_FILES)
# from Blockchain2.GetFromBlockChain import getUserprojectIds
from Blockchain2.WalletCreation import walletCreation
from blockchain.submitIPFS import upload_zipfile_to_ipfs
from centralizePayment.views import callback, create_indent
from conversion.forms import CScript, NScript
from conversion.models import UploadScript
from conversion.translation.detection import getInputs
from conversion.translation.translation_function import translate_comparison
from MNF.email import mnfnsendemail
# from neutralAudit import mnf_script_subset_v2 as mnf_ss # 2
# from neutralAudit import sa_functions as sf # 9
# from neutralAudit import sa_functions_english as sf_eng
from MNF.settings import BasePath, GetMongoDBUrl
from mnfapp.models import (Author, MNFScriptDatabase, Notifications,
PaymentData, PitchVector, SampleScript,
centralDatabase)
from narration.vectorcode.code import vector_generation
from neutralAudit_old import mnf_script_subset_v2 as mnf_ss # 2
from neutralAudit_old import sa_functions as sf # 9
from neutralAudit_old import sa_functions_english as sf_eng
from payment.models import privilegedUser1
from Pitchdeck.models import Name, PitchVectorMultiAuthor
# from .models import ProgressBar
from scriptAudit.mnf_script_audit import NeutralAudit
from scriptAudit.models import ScriptAuditModel
from scriptAudit.utils import (check_status_and_trigger_vector,
generate_script_id_for_pitchdeck)
from scriptpage.forms import userForm
from users.models import *
from users.views import deduction_for_sep_wall
from utils import filesystem
from utils.scripts_functions import script_upload
from . import linebyline_narration
# from .Pitchdeck.Character_Introduction import TestingC, Char_function
from .Pitchdeck.Character_Introduction import (Char_audio_class, Char_function,
TestingC, audio_video)
from .Pitchdeck.ElevatorPitch import pitch_function
from .Pitchdeck.onepager import Pager_function
from .Pitchdeck.screenplay import screenplay_main
# from narration.Narration_Code import linebyline_narration
basePath = BasePath()
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = rf"{basePath}/narration/Narration_Code/authentication.json"
client = texttospeech.TextToSpeechClient()
translate_client = Translate.Client()
#end
PROGRESS = 10
progress_dict = {}
old_progress_dict = {}
from pymongo import MongoClient
# from Character_Introduction.char_function import char_function
# Commented as audit app changed - mohit
# from scriptAudit.script_audit_codes.script_audit import do_script_audit
# from videos.models import Video
logging.basicConfig(filename="./yameen.log",
format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p',level=logging.DEBUG,filemode="a")
# from rest_framework.decorators import (api_view, authentication_classes,
# permission_classes)
# from django.core.mail import EmailMultiAlternatives
# from django.utils.html import strip_tags
# from . import global_database
# from .Narration_Code import narration_generation # see here
# this has been imported by rohit on 26th December 2021
# from .Pitchdeck.Character_Introduction import TestingC
# removed version numbers from blow imports - Amulya 22/12/22
# from neutralAudit import mnf_script_subset_v1 as
MongoDBUrl = GetMongoDBUrl()
# MongoDBUrl="mongodb+srv://mnfv:1234@cluster0.h09hcrq.mongodb.net/?retryWrites=true&w=majority"
print("narration MongodbUrl", MongoDBUrl)
# Create your views here.
#
stripe.api_key = settings.STRIPE_SECRET_KEY
STRIPE_PUB_KEY = settings.STRIPE_PUBLISHABLE_KEY
# keyID = settings.RAZORPAY_KEY_ID
# keySecret = settings.RAZORPAY_KEY_SECRET
UsdConversionRate = 80
# keyID = "rzp_test_6U9A7gZuno8Qz1"
# keySecret = "SrhczTH4dmrxW8SrzeqOdBSP"
progress_updated = Signal()
def set_payment_token(request):
if request.user.is_superuser:
request.session["keyID"] = settings.T_RAZORPAY_KEY_ID
request.session["keySecret"] = settings.T_RAZORPAY_KEY_SECRET
else:
request.session["keyID"] = settings.RAZORPAY_KEY_ID
request.session["keySecret"] = settings.RAZORPAY_KEY_SECRET
# Multiligule
def multilingual_render(req, templateName: str, context: dict):
t = loader.get_template(templateName)
rendered_html = t.render(context, req)
soup = BeautifulSoup(rendered_html, 'html.parser')
def translate_and_replace_text(text):
if "multi_language" in req.session:
trans_text = translate_client.translate(text, source_language="en", target_language=req.session["multi_language"])
return trans_text["translatedText"]
return text
def find_and_replace_text_in_element(element):
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = [executor.submit(translate_and_replace_text, text) for text in element.find_all(text=is_user_visible)]
for future, text in zip(futures, element.find_all(text=is_user_visible)):
if text != '\n':
translated_text = future.result()
text.replace_with(translated_text)
if "multi_language" in req.session:
if req.session["multi_language"] != "en":
target_element = soup.find(id="mulitligule")
if target_element:
find_and_replace_text_in_element(target_element)
target_element_nav = soup.find(id="nav_mulitligual")
if target_element_nav:
find_and_replace_text_in_element(target_element_nav)
footer_elements = soup.find_all('footer')
for footer in footer_elements:
find_and_replace_text_in_element(footer)
modified_html = soup.prettify(encoding="UTF-8")
with open("/home/user/mnf/project/MNF/Pitchdeck/test2024.html", "wb") as file:
file.write(modified_html)
return HttpResponse(modified_html, content_type='text/html; charset=utf-8')
## caution : in case of a variant interpertition the english version will take priority.
def set_language(request):
if request.method == 'POST':
selected_language = request.POST.get('selected_language')
if selected_language:
request.session['multi_language'] = selected_language
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("multi_language:-" + str(request.session['multi_language']) + str(selected_language)+"\n")
return HttpResponse(status=200)
def is_user_visible(element):
if element.parent.name in ['style', 'script', 'head', 'meta', '[document]']:
return False
elif isinstance(element, Comment):
return False
return True
#end
BASE_DIR = Path(__file__).resolve().parent.parent
demo_files ={
"en":[
["sample_english",rf"{basePath}/media/NarrationDemoVideos/sample_english_pitchdeck.webm", rf"{basePath}/media/NarrationDemoVideos/sample_english.pdf", rf"{basePath}/media/NarrationDemoVideos/sample_english_screenplay.webm", rf"{basePath}/media/NarrationDemoVideos/Character_Introduction.webm",{"characterName":["pravesh","yameen"],"filepath":["pravesh.mp4","yameen.mp4"],}],
],
"hi":[
["yameenHI.docx","/home/user/mnf/project/MNF/media/NarrationDemoVideos/xyz_neha12_line.webm","/home/user/mnf/project/MNF/media/NarrationDemoVideos/newEnglis549_Ra7WQGc.pdf", "/home/user/mnf/project/MNF/media/NarrationDemoVideos/Character_Introduction.webm", "/home/user/mnf/project/MNF/media/NarrationDemoVideos/Character_Introduction.webm", "/home/user/mnf/project/MNF/media/NarrationDemoVideos/AroundYa4_Vuazii8.webm",],
["parveshHi.docx","/home/user/mnf/project/MNF/media/NarrationDemoVideos/xyz_neha12_line.webm","/home/user/mnf/project/MNF/media/NarrationDemoVideos/newEnglis549_Ra7WQGc.pdf", "/home/user/mnf/project/MNF/media/NarrationDemoVideos/Character_Introduction.webm", "/home/user/mnf/project/MNF/media/NarrationDemoVideos/Character_Introduction.webm", "/home/user/mnf/project/MNF/media/NarrationDemoVideos/AroundYa4_Vuazii8.webm",],
],
"fr":[
["sample_french",rf"{basePath}/media/NarrationDemoVideos/sample_french_pitchdeck.webm", rf"{basePath}/media/NarrationDemoVideos/sample_french.pdf", rf"{basePath}/media/NarrationDemoVideos/sample_french_screenplay.webm", rf"{basePath}/media/NarrationDemoVideos/Character_Introduction.webm", " ",],
],
"mr":[
["Sample_Marathi Script", rf"{basePath}/media/NarrationDemoVideos/Sample_Marathi_Script_pitchdeck.webm", rf"{basePath}/media/NarrationDemoVideos/Sample_Marathi_Script.pdf", rf"{basePath}/media/NarrationDemoVideos/Sample_Marathi_Script_screenplay.webm", rf"{basePath}/media/NarrationDemoVideos/Character_Introduction.webm", " ",],
],
}
languages = {
"hi": "Hindi",
"en": "English",
"ur": "Urdu",
"ar": "Arabic",
"bn": "Bengali",
"kn": "Kannada",
"ta": "Tamil",
"bg": "Bulgarian",
"bn": "Bangla",
"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": "Gujrati",
"or": "Odia",
"zh": "Chinese",
"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": "Kazak",
"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",
}
CURRENCY_SYMBOLS_MAP = {
"AED": "د.إ",
"AFN": "؋",
"ALL": "L",
"AMD": "֏",
"ANG": "ƒ",
"AOA": "Kz",
"ARS": "$",
"AUD": "$",
"AWG": "ƒ",
"AZN": "",
"BAM": "KM",
"BBD": "$",
"BDT": "",
"BGN": "лв",
"BHD": ".د.ب",
"BIF": "FBu",
"BMD": "$",
"BND": "$",
"BOB": "$b",
"BRL": "R$",
"BSD": "$",
"BTC": "฿",
"BTN": "Nu.",
"BWP": "P",
"BYR": "Br",
"BYN": "Br",
"BZD": "BZ$",
"CAD": "$",
"CDF": "FC",
"CHF": "CHF",
"CLP": "$",
"CNY": "¥",
"COP": "$",
"CRC": "",
"CUC": "$",
"CUP": "",
"CVE": "$",
"CZK": "",
"DJF": "Fdj",
"DKK": "kr",
"DOP": "RD$",
"DZD": "دج",
"EEK": "kr",
"EGP": "£",
"ERN": "Nfk",
"ETB": "Br",
"ETH": "Ξ",
"EUR": "",
"FJD": "$",
"FKP": "£",
"GBP": "£",
"GEL": "",
"GGP": "£",
"GHC": "",
"GHS": "GH₵",
"GIP": "£",
"GMD": "D",
"GNF": "FG",
"GTQ": "Q",
"GYD": "$",
"HKD": "$",
"HNL": "L",
"HRK": "kn",
"HTG": "G",
"HUF": "Ft",
"IDR": "Rp",
"ILS": "",
"IMP": "£",
"INR": "",
"IQD": "ع.د",
"IRR": "",
"ISK": "kr",
"JEP": "£",
"JMD": "J$",
"JOD": "JD",
"JPY": "¥",
"KES": "KSh",
"KGS": "лв",
"KHR": "",
"KMF": "CF",
"KPW": "",
"KRW": "",
"KWD": "KD",
"KYD": "$",
"KZT": "",
"LAK": "",
"LBP": "£",
"LKR": "",
"LRD": "$",
"LSL": "M",
"LTC": "Ł",
"LTL": "Lt",
"LVL": "Ls",
"LYD": "LD",
"MAD": "MAD",
"MDL": "lei",
"MGA": "Ar",
"MKD": "ден",
"MMK": "K",
"MNT": "",
"MOP": "MOP$",
"MRO": "UM",
"MRU": "UM",
"MUR": "",
"MVR": "Rf",
"MWK": "MK",
"MXN": "$",
"MYR": "RM",
"MZN": "MT",
"NAD": "$",
"NGN": "",
"NIO": "C$",
"NOK": "kr",
"NPR": "",
"NZD": "$",
"OMR": "",
"PAB": "B/.",
"PEN": "S/.",
"PGK": "K",
"PHP": "",
"PKR": "",
"PLN": "",
"PYG": "Gs",
"QAR": "",
"RMB": "",
"RON": "lei",
"RSD": "Дин.",
"RUB": "",
"RWF": "R₣",
"SAR": "",
"SBD": "$",
"SCR": "",
"SDG": "ج.س.",
"SEK": "kr",
"SGD": "$",
"SHP": "£",
"SLL": "Le",
"SOS": "S",
"SRD": "$",
"SSP": "£",
"STD": "Db",
"STN": "Db",
"SVC": "$",
"SYP": "£",
"SZL": "E",
"THB": "฿",
"TJS": "SM",
"TMT": "T",
"TND": "د.ت",
"TOP": "T$",
"TRL": "",
"TRY": "",
"TTD": "TT$",
"TVD": "$",
"TWD": "NT$",
"TZS": "TSh",
"UAH": "",
"UGX": "USh",
"USD": "$",
"UYU": "$U",
"UZS": "лв",
"VEF": "Bs",
"VND": "",
"VUV": "VT",
"WST": "WS$",
"XAF": "FCFA",
"XBT": "Ƀ",
"XCD": "$",
"XOF": "CFA",
"XPF": "",
"YER": "",
"ZAR": "R",
"ZWD": "Z$",
"XPD": "Pd",
"ZMK": "ZK",
"VEB": "Bs",
"SDD": "SD",
"ESP": "Pt",
"SKK": "Sk",
"RUR": "",
"ROL": "RON",
"PLZ": "",
"XPD": "Pd oz",
"NLG": "ƒ",
"MXP": "$",
"LUF": "F",
"ITL": "ITL",
"IEP": "£",
"GRD": "",
"XAU": "XAU",
"DEM": "DEM",
"FRF": "Fr",
"FIM": "Mk",
"NLG": "ƒ",
"CSK": "Kčs",
"CYP": "",
"BGL": "лв",
"BEF": "ƒ",
"ATS": "ATS",
"ARP": "$",
"XPT": "XPT",
"PTE": "",
"XDR": "XDR",
"XAG": "XAG",
"XPD": "XPD",
}
# from .serializers import ProgressBarSerializer
# from rest_framework.response import Response
# @api_view(['GET'])
# def progressBar(request,userid):
# if request.method == "GET":
# if id is not None:
# main = ProgressBar.objects.all().filter(id=userid)
# serializer = ProgressBarSerializer(main, many=True)
# return Response(serializer.data)
# main = ProgressBar.objects.all().filter(id = userid)
# serializer = ProgressBarSerializer(main, many=True)
# return Response(serializer.data)
def convert_to_pdf(input_docx, out_folder):
p = subprocess.Popen(
[
"libreoffice",
"--headless",
"--convert-to",
"pdf",
"--outdir",
out_folder,
input_docx,
]
)
print(["--convert-to", "pdf", input_docx])
p.communicate()
def countPages(docfile, pdfname):
convert_to_pdf(docfile, rf"{basePath}/media/PdfFiles")
pdf = PdfFileReader(open(rf"{basePath}/media/PdfFiles/{pdfname}", "rb"))
number_of_pages = pdf.getNumPages()
return number_of_pages
def narration(request):
number = ReferUser.objects.filter(refferedBy=request.user).count()
file_pk = request.GET.get("file_detail")
if file_pk:
file_qry = MNFScriptDatabase.objects.filter(script_id=file_pk).first()
else:
file_qry = None
M = MNFScriptDatabase()
sampleList = SampleScript.objects.filter(status="N")
MyURL = ""
dial_src_script = ""
dial_src_lang = ""
non_dial_src_lang = ""
non_dial_src_script = ""
script_title = ""
author_name = ""
numPages = 0
UScript = CScript()
id = ""
x = datetime.datetime.now(timezone("UTC")).astimezone(
timezone("Asia/Kolkata"))
# print("MY base path is " ,str(BASE_DIR))
UploadedScript = UploadScript()
print(" Upar Aaa rha hai")
if request.method == "POST":
M.script = request.FILES["script"]
if request.POST.get("linebyline"):
M.linebyline = "True"
if request.POST.get("characterintro"):
M.character_intro = "True"
if request.POST.get("screenplayanalysis"):
M.screenplay_analysis = "True"
M.save()
MyURL = M.script.url
# UScript = CScript(request.POST, request.FILES)
# if UScript.is_valid():
# UploadedScript.script = UScript.cleaned_data.get("script")
# MyURL = UploadedScript.script.url
print(MyURL)
print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$" * 4)
# UploadedScript.save()
# script_title = MyURL[7:-5] + str(x.strftime("%d"))+ "_"+ str(x.strftime("%b"))+ "_"+ str(x.strftime("%H"))+ str(x.strftime("%I"))
author_name = str(request.user.username)
# ------------------neha
request.session["script_name"] = M.script.name
script_title = request.session["script_name"]
# script_title = script_title[8:]
if script_title[-3:] == "pdf":
print(
"This do_script_audit start->",
datetime.datetime.now(timezone("UTC")).astimezone(
timezone("Asia/Kolkata")
),
)
# print(do_script_audit(basePath + MyURL, "1234", "scripts"))
print(
"This do_script_audit end->",
datetime.datetime.now(timezone("UTC")).astimezone(
timezone("Asia/Kolkata")
),
)
pdf = PdfFileReader(open(rf"{basePath}/{MyURL}", "rb"))
numPages = pdf.getNumPages()
# MyURL = MyURL[:-3]+"docx"
else:
numPages = countPages(str(BASE_DIR) + MyURL,
script_title[7:-4] + "pdf")
print(
"This do_script_audit start->",
datetime.datetime.now(timezone("UTC")).astimezone(
timezone("Asia/Kolkata")),
)
formInput = getInputs(str(BASE_DIR) + MyURL)
print(
"This do_script_audit end->",
datetime.datetime.now(timezone("UTC")).astimezone(
timezone("Asia/Kolkata")),
)
dial_src_script = formInput[2]
dial_src_lang = formInput[1]
non_dial_src_lang = formInput[0]
non_dial_src_script = formInput[3]
print("done")
return render(
request,
"narration/narration.html",
{
"numPages": numPages,
"id": M.id,
"list": sampleList,
"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,
"file": file_qry,
"number": number,
},
)
def get_page_count(file):
archive = zipfile.ZipFile(file, "r")
ms_data = archive.read("doc/docx")
archive.close()
app_xml = ms_data.decode("utf-8")
regex = r"<(Pages|Slides)>(\d)</(Pages|Slides)>"
matches = re.findall(regex, app_xml, re.MULTILINE)
match = matches[0] if matches[0:] else [0, 0]
page_count = match[1]
return page_count
def characterNarrate(request):
print("characterNarrate starting here")
if request.method == "POST":
print("characterNarrate POST starting here")
selected_character = request.POST.getlist("character_check")
print(f" selected characters {selected_character}")
# Pitchvector-- Add a field for selected Character list and save
input_dir = request.session.get("script_dir_url")
print(f"input dir {input_dir}")
# input_filename=request.session["script_name"]
input_filename = request.session["script_name"]
print("enter subset characters")
dic_of_chr_path = mnf_ss.get_subset_character_script(
input_dir, input_filename, selected_character
)
print(dic_of_chr_path)
print("exit subset characters")
return render(
request,
"Pitchdeck/Pitchnarrate2.html",
{"script": request.session["script_name"][:-5]},
)
return render(
request,
"Pitchdeck/characterNarration.html",
{"character_list": request.session["saved_characters_list"]},
)
# @login_required(login_url="/")
def pitchnarrate_view(request):
number = ReferUser.objects.filter(refferedBy=request.user).count()
print("Delhi India: 0")
screenplay_form = userForm(request.POST, request.FILES)
if request.method == "POST":
logging.debug("in pitchnarrate_view")
if not screenplay_form.is_valid():
raise screenplay_form.error_class
logging.debug(screenplay_form.changed_data)
screenplay_name = screenplay_form.cleaned_data["screenplay"]
author = screenplay_form.cleaned_data["author"]
language = screenplay_form.cleaned_data["language"]
script_file = screenplay_form.cleaned_data["file"]
# script_file = screenplay_form.cleaned_data["file"]
script_ext = script_file.name.split(".")[-1]
script_file_name = screenplay_name + "." + script_ext
file = ContentFile(
script_file.read(),
script_file_name,
)
script_data = filesystem.new_screenplay(
request.user,
author,
screenplay_name,
file,
"script-original",
language,
)
request.session["script_name"] = script_data.get("name")
request.session["line_by_line_narration"] = request.POST.get(
"line_by_line_narration"
)
request.session["character_introduction"] = request.POST.get(
"character_introduction"
)
request.session["screenplay_analysis"] = request.POST.get(
"screenplay_analysis")
request.session["one_pager"] = request.POST.get("one_pager")
request.session["elevator_pitch"] = request.POST.get("elevator_pitch")
request.session["character_narration"] = request.POST.get(
"character_narration")
script_id = script_data.get("script").get("id")
print("new Delhi India: 1")
z = PitchVector()
while True:
audit_model = ScriptAuditModel.objects.get(script__id=script_id)
if audit_model.status == "SUCCESS":
break
elif audit_model.status == "FAILURE":
raise Exception("Audit Failed")
print("apple100")
file = filesystem.get_script(script_id, "script-docx", create=True)
z.choosescript = file
z.save()
request.session["script_url"] = file.path
print(
"apple101 _______________________________________________________________________________\n\n",
file.path,
)
request.session["script_dir_url"] = str(BASE_DIR) + "/media/scripts/"
print("harsh")
formInput = getInputs(file.path)
dial_src_script = formInput[2]
dial_src_lang = formInput[1]
non_dial_src_lang = formInput[0]
non_dial_src_script = formInput[3]
print("done")
request.session["dial_src_script"] = dial_src_script
request.session["dial_src_lang"] = dial_src_lang
request.session["non_dial_src_lang"] = non_dial_src_lang
request.session["non_dial_src_script"] = non_dial_src_script
print("character started")
request.session["line_by_line_narration"] = request.POST.get(
"line_by_line_narration"
)
request.session["character_introduction"] = request.POST.get(
"character_introduction"
)
request.session["screenplay_analysis"] = request.POST.get(
"screenplay_analysis")
request.session["one_pager"] = request.POST.get("one_pager")
request.session["elevator_pitch"] = request.POST.get("elevator_pitch")
request.session["character_narration"] = request.POST.get(
"character_narration")
print("checklbl", request.session["line_by_line_narration"])
print("checkci", request.session["character_introduction"])
print("checksa", request.session["screenplay_analysis"])
print("checkop", request.session["one_pager"])
print("checkep", request.session["elevator_pitch"])
print("checkcn", request.session["character_narration"])
input_dir = str(BASE_DIR) + "/media/scripts/"
input_filename = request.session["script_name"]
print("----------OM----------view")
print(input_dir)
# char_list = mnf_ss.get_character_list(input_dir, input_filename)
audit = NeutralAudit(script_id)
char_list = audit.get_character_list()
request.session["saved_characters_list"] = list(char_list)
print("get_character_list done")
char_list1 = list(char_list)
script_upload(file, request.user)
if len(char_list1) > 2:
newlist = char_list1[0:2]
else:
newlist = char_list1
no_of_char = len(newlist)
print(
"\n\n\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n\n"
)
print("checkcn", request.session.items())
print(
"\n\n\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n\n"
)
# if no_of_char == 1:
# return render(
# request,
# "Pitchdeck/Pitchnarrate2.html",
# {
# "script": request.session["script_name"],
# "character_list": char_list1,
# "firstcharacter": newlist[0],
# "five_character": newlist,
# "cd": centralDatabase.objects.get(user_id=request.user),
# },
# )
# else:
# return render(
# request,
# "Pitchdeck/Pitchnarrate2.html",
# {
# "script": request.session["script_name"],
# "character_list": char_list1,
# "firstcharacter": newlist[0],
# "secondcharacter": newlist[1],
# "five_character": newlist,
# "cd": centralDatabase.objects.get(user_id=request.user),
# },
# )
return render(
request,
"Pitchdeck/pitchnarratefile.html",
{"number": number, "formInput": screenplay_form},
)
@login_required(login_url="/")
def Pitchnarrate_yameen(request):
# print("request",request)
print("request.user",request.user)
number = ReferUser.objects.filter(refferedBy=request.user).count()
# print("Delhi India: 1")
z = PitchVector()
if request.method == "POST":
# UScript = NScript(request.POST, request.FILES)
# print("request.FILES", request.FILES)
# print('UScript',UScript)
# if UScript.is_valid():
# z.choosescript = UScript.cleaned_data.get("scriptss")
# # print("****************************777777777778888888889999999999999**************************")
# print('z.choosescript', z.choosescript)
# z.save()
# # filename = UScript.cleaned_data.get("scriptss")
# aa = re.sub("[^A-Za-z0-9 /._]+", "", str(z.choosescript))
# print("aa",aa)
# # bb = aa.replace(" ", "_")
# # print(bb)
# filename = str(aa).replace(" ", "_")
# filename = filename[8:]
id = request.POST.get("Nscript_id")
print("Iddddddddd", type(id))
x = SampleScript.objects.get(id=id)
filePath = x.script_file_path
filename = filePath.split('/')[-1]
print("filenamessssssssssssssssssss", filename)
z.choosescript = filename
z.save()
request.session["script_name"] = filename
file_url = str(BASE_DIR) + "/media/scripts/" + filename
print("file_urlss", file_url)
request.session["script_url"] = file_url
# used because get_subset_character_script needs file dir
request.session["script_dir_url"] = str(BASE_DIR) + "/media/scripts/"
print("harsh")
formInput = getInputs(file_url)
dial_src_script = formInput[2]
dial_src_lang = formInput[1]
non_dial_src_lang = formInput[0]
non_dial_src_script = formInput[3]
print("done")
request.session["dial_src_script"] = dial_src_script
request.session["dial_src_lang"] = dial_src_lang
request.session["non_dial_src_lang"] = non_dial_src_lang
request.session["non_dial_src_script"] = non_dial_src_script
print("character started")
checkedopt = []
print(request.POST.get("line_by_line_narration"))
request.session["line_by_line_narration"] = request.POST.get(
"line_by_line_narration"
)
request.session["character_introduction"] = request.POST.get(
"character_introduction"
)
request.session["screenplay_analysis"] = request.POST.get(
"screenplay_analysis")
request.session["one_pager"] = request.POST.get("one_pager")
request.session["elevator_pitch"] = request.POST.get("elevator_pitch")
request.session["character_narration"] = request.POST.get(
"character_narration")
input_dir = str(BASE_DIR) + "/media/scripts/"
input_filename = filename
print("----------OM----------yameen")
print(input_dir)
char_list = mnf_ss.get_character_list(input_dir, input_filename)
print(char_list)
request.session["saved_characters_list"] = list(char_list)
print("get_character_list done")
numPages = countPages(file_url, file_url.rsplit(
"/", 1)[1].rsplit(".", 1)[0] + ".pdf")
print("no of page", numPages)
if numPages > 5:
try:
membertype = privilegedUser1.objects.get(
user=request.user, is_active="yes")
print("neha privalige", membertype)
char_list1 = list(char_list)
# script_upload(filePat, request.user)
if len(char_list1) > 2:
newlist = char_list1[0:2]
else:
newlist = char_list1
no_of_char = len(newlist)
if no_of_char == 1:
return render(
request,
"Pitchdeck/Pitchnarrate2.html",
{
"script": filename[:-5],
"character_list": char_list1,
"firstcharacter": newlist[0],
"five_character": newlist,
"cd": centralDatabase.objects.get(user_id=request.user),
"numPages": numPages,
},
)
else:
return render(
request,
"Pitchdeck/Pitchnarrate2.html",
{
"script": filename[:-5],
"character_list": char_list1,
"firstcharacter": newlist[0],
"secondcharacter": newlist[1],
"five_character": newlist,
"cd": centralDatabase.objects.get(user_id=request.user),
"numPages": numPages,
},
)
except:
messages.error(request, "You are not a privileged member.")
return render(request, "Pitchdeck/Pitchnarrate1.html")
# return redirect("payment")
else:
char_list1 = list(char_list)
# script_upload(filePath, request.user)
if len(char_list1) > 2:
newlist = char_list1[0:2]
else:
newlist = char_list1
no_of_char = len(newlist)
if no_of_char == 1:
return render(
request,
"Pitchdeck/Pitchnarrate2.html",
{
"script": filename[:-5],
"character_list": char_list1,
"firstcharacter": newlist[0],
"five_character": newlist,
"cd": centralDatabase.objects.get(user_id=request.user),
"numPages": numPages,
},
)
else:
return render(
request,
"Pitchdeck/Pitchnarrate2.html",
{
"script": filename[:-5],
"character_list": char_list1,
"firstcharacter": newlist[0],
"secondcharacter": newlist[1],
"five_character": newlist,
"cd": centralDatabase.objects.get(user_id=request.user),
"numPages": numPages,
},
)
return render(request, "Pitchdeck/Pitchnarrate1.html", {"number": number})
@login_required(login_url="/")
def Pitchnarrate1(request, id=None):
print("request", request)
print("request.user", request.user.email)
number = ReferUser.objects.filter(refferedBy=request.user).count()
print("Delhi India: 1")
Module= "narration"
servicesName = "PitchdeckCreation"
z = PitchVector()
if request.method == "POST":
# if 'form_identifier' in request.POST:
# print("############################# TRUE ###################################################")
# print('request.FILES["scriptss"]',request.FILES["scriptss"])
# fileExists = script_upload(request.FILES["scriptss"], request.user, 1)
# print("fileExists",fileExists)
# return render(request, "Pitchdeck/Pitchnarrate1.html")
# MongoDBUrl = "mongodb+srv://MNF:root@cluster0.gbkxi.gcp.mongodb.net/DB?retryWrites=true&w=majority"
MongoDBUrl = "mongodb+srv://mynextfilm:mnf123@cluster0.ojasb.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"
client = MongoClient(MongoDBUrl)
db = client.DB
# try:
try:
# script_upload(request.FILES["scriptss"], request.user)
fileExists = script_upload(request.FILES["scriptss"], request.user, 1)
if fileExists:
# pitch_data = db["mnfapp_pitchvector"].find_one({"script_id": str(script_id)})
print("scriptName########////", str(request.FILES["scriptss"].name))
s_name=str(request.FILES["scriptss"].name)
# numPages = countPages(s_name, s_name.rsplit("/", 1)[1].rsplit(".", 1)[0] + ".pdf")
# print("with file exist",numPages)
sript_title=s_name.split(".")[0]
user_script_data = db["mnfapp_mnfscriptdatabase"].find_one({"script_title": sript_title})
print("user_script_data ##########################",user_script_data)
if user_script_data:
recent_id=user_script_data.get('script_id')
if user_script_data['characterwise_narration']=='True'or user_script_data['linebyline']=='True'or user_script_data['screenplay_analysis']=='True'or user_script_data['character_intro']=='True' or user_script_data['onepager']=='True'or user_script_data['elevator_pitch']=='True':
script_database = db["mnfapp_pitchvector"].find_one({"script_id":recent_id})
print(script_database)
else:
pass
else:
pass
except Exception as e:
error = e
return render(request, "Pitchdeck/Pitchnarrate1.html", {"error":error})
UScript = NScript(request.POST, request.FILES)
print("request.FILES", request.FILES)
print('UScript', UScript)
if UScript.is_valid():
z.choosescript = UScript.cleaned_data.get("scriptss")
print('z.choosescript', z.choosescript)
z.save()
# filename = UScript.cleaned_data.get("scriptss")
# aa = re.sub("[^A-Za-z0-9 /._]+", "", str(z.choosescript))
# print("aa", aa)
# # bb = aa.replace(" ", "_")
# # print(bb)
# filename = str(aa).replace(" ", "_")
filename = str(z.choosescript)
filename = filename[8:]
#Blockchain
if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user)
contex = z.choosescript
hash = uploadDataToIPFSNode(contex)
print("hash;;;;;;;;>>",hash)
request.session["original_script_file_hash"] = hash
# :::::::::::::
# print("filename................................>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>...................>>>>>>>>>>>>>>>>..", filename)
# print(filename.name)
request.session["script_name"] = filename
file_url = str(BASE_DIR) + "/media/scripts/" + filename
print("file_url", file_url)
request.session["script_url"] = file_url
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("f: " + str(file_url) + "\n")
# used because get_subset_character_script needs file dir
request.session["script_dir_url"] = str(BASE_DIR) + "/media/scripts/"
print("harsh")
try:
# print("Entered Try *&*&*&*&*&")
# formInput = getInputs(file_url)
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("In Try block" + "\n")
print("entered Try :::::::::::::::")
formInput = getInputs(file_url)
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("form data: " + str(formInput ) + "\n")
dial_src_script = formInput[2]
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("dial_src_script data: " + str(dial_src_script ) + "\n")
dial_src_lang = formInput[1]
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("dial_src_langa: " + str(dial_src_lang ) + "\n")
non_dial_src_lang = formInput[0]
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("non_dial_src_lang: " + str(non_dial_src_lang ) + "\n")
non_dial_src_script = formInput[3]
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("non_dial_src_script: " + str(non_dial_src_script ) + "\n")
print("done")
request.session["dial_src_script"] = dial_src_script
request.session["dial_src_lang"] = dial_src_lang
request.session["non_dial_src_lang"] = non_dial_src_lang
request.session["non_dial_src_script"] = non_dial_src_script
except:
error = "Could not process this type of file"
return render(request, "Pitchdeck/Pitchnarrate1.html", {"error": error})
print("character started")
checkedopt = []
# print(request.POST.get("line_by_line_narration"))
request.session["line_by_line_narration"] = request.POST.get(
"line_by_line_narration"
)
request.session["character_introduction"] = request.POST.get(
"character_introduction"
)
request.session["screenplay_analysis"] = request.POST.get(
"screenplay_analysis")
request.session["one_pager"] = request.POST.get("one_pager")
request.session["elevator_pitch"] = request.POST.get("elevator_pitch")
request.session["character_narration"] = request.POST.get(
"character_narration")
print("charWise")
print(request.session["character_narration"])
services_use = []
if request.session["line_by_line_narration"] == "Line by Line Narration(Video)":
print(request.session["line_by_line_narration"])
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("Line by line1: " + str(request.session["line_by_line_narration"]) + "\n")
services_use.append("Line by Line Narration")
if request.session["character_introduction"] == "Character Introduction(Video)":
print(request.session["character_introduction"])
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("Character introduction1: " + str(request.session["character_introduction"]) + "\n")
services_use.append("Character Introduction")
if request.session["screenplay_analysis"] == "Screenplay Analysis(Video)":
print(request.session["screenplay_analysis"])
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("Screenplay analysis1: " + str(request.session["screenplay_analysis"]) + "\n")
services_use.append("Screenplay Analysis")
if request.session["elevator_pitch"] == "Elevator Pitch(Video)":
print(request.session["elevator_pitch"])
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("Elevator pitch1: " + str(request.session["elevator_pitch"]) + "\n")
services_use.append("Elevator Pitch")
if request.session["one_pager"] == "One Pager(PDF)":
print(request.session["one_pager"])
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("One pager1: " + str(request.session["one_pager"]) + "\n")
services_use.append("One Pager")
if request.session["character_narration"] == "Characterwise Narration(Video)":
print(request.session["character_narration"])
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("Character narration1: " + str(request.session["character_narration"]) + "\n")
services_use.append("Characterwise Narration")
input_dir = str(BASE_DIR) + "/media/scripts/"
input_filename = filename
print("----------OM----------")
print(input_dir)
#----------------------modified audit part
input_script_path = os.path.join(input_dir,input_filename) #paveen
print("input_script_path:::::::::::", input_script_path)
script_id_audit = generate_script_id_for_pitchdeck(input_script_path,request)
request.session["script_id_audit"] = script_id_audit
print('Yameenmrequest.session["script_id_audit"]', request.session["script_id_audit"])
print("neutral audit started---------------")
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("1.neutral audit started---------------" + "\n")
try:
neutral_aud = NeutralAudit(script_id_audit)
print("neutral audit ended-----------")
char_lst = neutral_aud.get_character_list()
except:
char_lst = None
error = "Our Services are currently not available"
return render(request, "Pitchdeck/Pitchnarrate1.html", {"error": error})
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("char list ended-------------------------" + "\n")
print("2.neutral audit ended-------------------------")
print("HERE IS THE CHARACTER SUBSET",str(char_lst))
# dist_audit_character_subset = script_audit_obj.get_character_subset(char_list)
char_list = char_lst
#---------------------------------------------end--------------------------
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("3.LIST of CHARACTERS: " + str(char_list) + "\n")
# print("dist_audit_character_subsetyameen",dist_audit_character_subset)
# request.session["dist_audit_character_subset"] = dist_audit_character_subset
# char_list = mnf_ss.get_character_list(input_dir, input_filename)
print("char_list________________________________________________",char_list)
request.session["saved_characters_list"] = list(char_list)
print("get_character_list done")
numPages = countPages(file_url, file_url.rsplit(
"/", 1)[1].rsplit(".", 1)[0] + ".pdf")
print("no of page", numPages)
# if numPages > 5:
# try:
# membertype = privilegedUser1.objects.filter(user=request.user, is_active="yes")
# print("neha privalige", membertype)
# char_list1 = list(char_list)
# if len(char_list1) > 2:
# newlist = char_list1[0:2]
# else:
# newlist = char_list1
# no_of_char = len(newlist)
# print("........",newlist)
# print(">>>>>>>>>>>>>charlenght",no_of_char)
# if no_of_char == 1:
# return render(
# request,
# "Pitchdeck/Pitchnarrate2.html",
# {
# "script": filename[:-5],
# "character_list": char_list1,
# "numberofcharacter": len(char_list1),
# "firstcharacter": newlist[0],
# "five_character": newlist,
# "cd": centralDatabase.objects.get(user_id=request.user),
# "numPages": numPages,
# "user_name": request.user.username,
# "user_email": request.user.email,
# "services_use": services_use,
# "services_len": len(services_use),
# # "script_database": script_database
# },
# )
# else:
# return render(
# request,
# "Pitchdeck/Pitchnarrate2.html",
# {
# "script": filename[:-5],
# "character_list": char_list1,
# "numberofcharacter": len(char_list1),
# "firstcharacter": newlist[0],
# "secondcharacter": newlist[1],
# "five_character": newlist,
# "cd": centralDatabase.objects.get(user_id=request.user),
# "numPages": numPages,
# "user_name": request.user.username,
# "user_email": request.user.email,
# "services_use": services_use,
# "services_len": len(services_use),
# # "script_database": script_database
# },
# )
# except:
# messages.error(request, "You are not a privileged member.")
# print("@@@@@@@@ privileged member nahi hai hai @@@@@@@@@@@@@@@@")
# return render(request, "Pitchdeck/Pitchnarrate1.html")
# # return redirect("payment")
# else:
char_list1 = list(char_list)
print("char_list", char_list1)
if len(char_list1) > 2:
newlist = char_list1[0:2]
else:
newlist = char_list1
no_of_char = len(newlist)
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("Number of char pitchnarrate1: " + str(no_of_char) + "\n")
print("characater lenght ",no_of_char)
if no_of_char != 0:
if no_of_char == 1:
print("no_of_char == 1")
return render(
request,
"Pitchdeck/Pitchnarrate2.html",
{
"script": filename[:-5],
"character_list": char_list1,
"firstcharacter": newlist[0],
"numberofcharacter": len(char_list1),
"five_character": newlist,
"cd": centralDatabase.objects.get(user_id=request.user),
"numPages": numPages,
"user_name": request.user.username,
"user_email": request.user.email,
"services_use": services_use,
"services_len": len(services_use),
# "script_database": script_database
},
)
else:
print("no_of_char, else",)
return render(
request,
"Pitchdeck/Pitchnarrate2.html",
{
"script": filename[:-5],
"character_list": char_list1,
"numberofcharacter": len(char_list1),
"firstcharacter": newlist[0],
"secondcharacter": newlist[1],
"five_character": newlist,
"cd": centralDatabase.objects.get(user_id=request.user),
"numPages": numPages,
"user_name": request.user.username,
"user_email": request.user.email,
"services_use": services_use,
"services_len": len(services_use),
# "script_database": script_database
},
)
else:
error = "Sorry something went wrong while fetching The characters from script"
return render(request, "Pitchdeck/Pitchnarrate1.html", {"error": error})
print("Return to page one")
return render(request,"Pitchdeck/Pitchnarrate1.html",{"context":number})
@login_required(login_url="/")
def Pitchnarrate2(request):
# number = ReferUser.objects.filter(refferedy=request.user).count()
print("Delhi India****************************************: 2")
print(request.session)
print(request.session.items())
MNFScriptDatabase1 = {}
if request.method == "GET":
print("Delhigetting")
if request.method == "POST":
l = request.session["saved_characters_list"]
print(f"saved characters: {l}")
y = MNFScriptDatabase()
y.script_id = "scr_" + str(int(time.time()))
blockchainscript_id = int(time.time())
request.session["blockchainscript_id"]=blockchainscript_id
print("we are printing script id",y.script_id)
y.connecting_id = ""
connecting_id = ""
# y.author_name = request.POST.get('author_name')
y.script_title = request.POST.get("scriptname")
script_title = request.POST.get("scriptname")
url = request.session.get("script_url")
script_filename = request.session["script_name"] # get the filename
y.document_name = script_filename # save the filename
document_name = script_filename
print(script_filename)
script_page_count = countPages(
url, (((script_filename.split("/"))[-1]).split("."))[0] + ".pdf"
) # get the page count
print("neha1155op")
print(script_page_count)
y.numPages = script_page_count # save the page count
# y.script_title = request.POST['script_title']
numPages = script_page_count
y.script_file_path = url
script_file_path = url
y.actionline_language = request.session["non_dial_src_lang"]
actionline_language = request.session["non_dial_src_lang"]
y.actionline_script_language = request.session["non_dial_src_script"]
actionline_script_language = request.session["non_dial_src_script"]
y.dialogues_script_language = request.session["dial_src_script"]
dialogues_script_language = request.session["dial_src_script"]
y.dialogues_language = request.session["dial_src_lang"]
dialogues_language = request.session["dial_src_lang"]
request.session["line_by_line_narration"] = request.POST.get(
"line_by_line_narration"
)
request.session["character_introduction"] = request.POST.get(
"character_introduction"
)
request.session["screenplay_analysis"] = request.POST.get(
"screenplay_analysis")
request.session["one_pager"] = request.POST.get("one_pager")
request.session["elevator_pitch"] = request.POST.get("elevator_pitch")
request.session["character_narration"] = request.POST.get(
"character_narration")
print(request.session["character_narration"])
print(request.session["line_by_line_narration"])
print(request.session["screenplay_analysis"])
print(request.session["one_pager"])
print(request.session["elevator_pitch"])
service_use = []
if request.session["line_by_line_narration"] == "Line by Line Narration(Video)":
print(request.session["line_by_line_narration"])
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("Line by Line narration: " + str(request.session["line_by_line_narration"]) + "\n")
y.linebyline = "True"
MNFScriptDatabase1["linebyline"] = "True"
service_use.append("Line by Line Narration")
if request.session["character_introduction"] == "Character Introduction(Video)":
print(request.session["character_introduction"])
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("Character introduction: " + str(request.session["character_introduction"]) + "\n")
y.character_intro = "True"
MNFScriptDatabase1["character_intro"] = "True"
service_use.append("Character Introduction")
if request.session["screenplay_analysis"] == "Screenplay Analysis(Video)":
print(request.session["screenplay_analysis"])
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("Screenplay analysis: " + str(request.session["screenplay_analysis"]) + "\n")
y.screenplay_analysis = "True"
MNFScriptDatabase1["screenplay_analysis"] = "True"
service_use.append("Screenplay Analysis")
if request.session["elevator_pitch"] == "Elevator Pitch(Video)":
print(request.session["elevator_pitch"])
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("Elevator Pitch: " + str(request.session["elevator_pitch"]) + "\n")
y.elevator_pitch = "True"
MNFScriptDatabase1["elevator_pitch"] = "True"
service_use.append("Elevator Pitch")
if request.session["one_pager"] == "One Pager(PDF)":
print(request.session["one_pager"])
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("One pager: " + str(request.session["one_pager"]) + "\n")
y.onepager = "True"
MNFScriptDatabase1["one_pager"] = "True"
service_use.append("One Pager")
if request.session["character_narration"] == "Characterwise Narration(Video)":
print(request.session["character_narration"])
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("Character narration: " + str(request.session["character_narration"]) + "\n")
y.characterwise_narration = "True"
MNFScriptDatabase1["characterwise_narration"] = "True"
service_use.append("Characterwise Narration")
y.user_id = request.user
user_id = request.user
# print("userid session")
# y.progress = 10
request.session["service_use"]=len(service_use)
y.save()
MNFScriptDatabase1["user_id_id"] = str(user_id)
MNFScriptDatabase1["blockchainscript_id"] = blockchainscript_id
MNFScriptDatabase1["script_title"] = script_title
MNFScriptDatabase1["script_filename"]= script_filename
MNFScriptDatabase1["actionline_language"] = actionline_language
MNFScriptDatabase1["actionline_script_language"] = actionline_script_language
MNFScriptDatabase1["dialogues_language"] = dialogues_language
MNFScriptDatabase1["dialogues_script_language"] = dialogues_script_language
MNFScriptDatabase1["document_name"] = document_name
MNFScriptDatabase1["script_file_path"] = script_file_path
MNFScriptDatabase1["original_script_file_hash"] = request.session["original_script_file_hash"]
# xx = PitchVectorMultiAuthor()
pitchvector1={}
x = PitchVector()
x.choosescript = request.session["script_name"]
x.scriptDetails = y
x.script_id = y.script_id
x.scriptname = y.script
scriptname = y.script
x.genre = request.POST.get("genre")
genre = request.POST.get("genre")
x.subGenre = request.POST.get("subgenre")
subGenre = request.POST.get("subgenre")
x.projecttype = request.POST.get("projecttype")
projecttype = request.POST.get("projecttype")
x.noepisodes = request.POST.get("nepisode")
noepisodes = request.POST.get("nepisode")
x.eachepisodes = request.POST.get("eachepisode")
eachepisodes = request.POST.get("eachepisode")
x.other = request.POST.get("other")
other = request.POST.get("other")
x.language = request.POST.get("language")
language = request.POST.get("language")
x.dialect_language = request.POST.get(
"dialect_language") # ---------changes
dialect_language = request.POST.get(
"dialect_language")
x.platformproposed = request.POST.get("proposed")
platformproposed = request.POST.get("proposed")
x.country = request.POST.get("country")
country = request.POST.get("country")
x.countryCode = request.POST.get("code")
countryCode = request.POST.get("code")
x.state = request.POST.get("state")
state = request.POST.get("state")
x.city = request.POST.get("city")
city = request.POST.get("city")
x.languagebelt = request.POST.get("langugebelt")
languagebelt = request.POST.get("langugebelt")
x.target_audience = request.POST.get("target")
target_audience = request.POST.get("target")
x.target_field = request.POST.get("field")
target_field = request.POST.get("field")
x.timeperiod = request.POST.get("period")
timeperiod = request.POST.get("period")
x.geography = request.POST.get("geography")
geography = request.POST.get("geography")
x.dialogue_reference = request.POST.get("dialogue")
dialogue_reference = request.POST.get("dialogue")
x.premise = request.POST.get("premise")
premise = request.POST.get("premise")
x.logline = request.POST.get("logline")
logline = request.POST.get("logline")
x.save()
# y.progress = 20
# y.save()
# manoj - store data to central database
cd = centralDatabase.objects.get(user_id=request.user)
cd.country = x.country
cd.state = x.state
cd.city = x.city
cd.project_type = x.projecttype
cd.genre = x.genre
cd.subgenre = x.subGenre
cd.language = x.language
cd.set_in_time = x.timeperiod
cd.set_in_geography = x.geography
cd.logline = x.logline
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("disct "+ str(pitchvector1)+ "\n")
# #CharacterWise Narration
print(request.POST.getlist("`character_check`"))
if request.POST.get("characterwise"):
selected_characters = request.POST.getlist("character_check")
# replace " " with "_" as uncove docx to pdf conversion was given error
# for i in range(len(selected_characters)):
# if " " in selected_characters[i]:
# selected_characters[i] = selected_characters[i].replace(" ","_")
x.set_selected_characters(selected_characters)
y.set_selected_characters(selected_characters)
print(
f"selected characters: {x.get_selected_characters()} type: {type(x.get_selected_characters())}"
)
# # Author details
if request.POST.get("author"):
# authorss = []
# # xx.script_id = y.script_id
# # xx.save()
# print("request.POST.getlist('name')",request.POST.getlist('name'))
# print("request.POST.getlist('auth_name')",request.POST.getlist('auth_name'))
# print("request.POST.getlist('auth_name') len", len(request.POST.getlist('auth_name')))
# print("request.FILES.getlist('uploadimage1')[i]",request.FILES.getlist('uploadimage1'))
# zips = zip_longest(request.POST.getlist('name'), request.POST.getlist('email'),request.POST.getlist('number'),request.POST.getlist('link'),request.FILES.getlist('uploadimage1'),request.POST.getlist('about'))
# print("::::::::::::::zip:::::::::::",set(zips))
# # for i in range(len(request.POST.getlist('name'))):
# # author = {
# # 'name': request.POST.getlist('name')[i],
# # 'email': request.POST.getlist('email')[i],
# # 'phone': request.POST.getlist('number')[i],
# # 'link': request.POST.getlist('link')[i],
# # 'image': request.FILES.getlist('uploadimage1')[i],
# # 'about': request.POST.getlist('about')[i],
# # }
# # authorss.append(author)
# for name, email, number, link, img, about in zip_longest(request.POST.getlist('name'), request.POST.getlist('email'),request.POST.getlist('number'),request.POST.getlist('link'),request.FILES.getlist('uploadimage1'),request.POST.getlist('about')):
# author = {
# 'name': name,
# 'email': email,
# 'phone': number,
# 'link': link,
# 'image': img,
# 'about': about,
# }
# authorss.append(author)
# # name_obj = Name.objects.create(name=name)
# # xx.names.add(name_obj)
# # xx.save()
# print("::::::::::::::::::--> authorss <--::::::::::::::::::",authorss)
# # l = request.FILES.getlist('uploadimage')[5]
# # lst = global_database.DB['mnfapp_pitchvector']
x.author = True
author = True
x.name = request.POST.get("auth_name")
name = request.POST.get("auth_name")
y.author_name = request.POST.get("auth_name")
author_name = request.POST.get("auth_name")
y.save()
x.author_profile = request.FILES.get("uploadimage")
x.author_email = request.POST.get("email")
x.phonenumber = request.POST.get("number")
x.author_about = request.POST.get("about")
x.author_link = request.POST.get("link")
x.save()
# Blockchain Data
MNFScriptDatabase1["author_name"] = author_name
# central database
cd.about = x.author_about
x.author1 = [
x.author_profile,
request.POST.get("auth_name"),
request.POST.get("about"),
request.POST.get("number"),
request.POST.get("email"),
request.POST.get("link"),
]
auth_name = request.POST.get("auth_name")
# store session variable
request.session["author_name"] = auth_name
auth_img = request.FILES.get("uploadimage")
auth_email = request.POST.get("email")
auth_phone = request.POST.get("number")
auth_about = request.POST.get("about")
auth_link = request.POST.get("link")
print(
auth_email,
auth_about,
auth_img,
auth_link,
auth_name,
auth_phone,
"====================Author Details Here===========================",
)
created_author = Author.objects.create(
author_profile=auth_img,
name=auth_name,
author_about=auth_about,
author_email=auth_email,
phonenumber=auth_phone,
author_link=auth_link,
)
# if auth_img:
# created_author.author_profile = request.FILES.get("uploadimage")
# created_author.save()
x.author_details.add(created_author)
print(created_author, "000000000000000000000000000000000")
x.save()
# # Plot and story flow
if request.POST.get("plot_story_flow"):
x.plot_story_flow = True
plot_story_flow = True
x.protagonist = request.POST.get("protagonist")
x.barrier = request.POST.get("barrier")
x.midpoint = request.POST.get("midpoint")
x.climax = request.POST.get("climax")
x.conflictresolved = request.POST.get("resolved")
x.minute_protogonist = request.POST.get("minute_pro")
x.conflict_reaches_climax = request.POST.get("conflict")
x.save()
# Blockchain
# # About shooting
if request.POST.get("shooting"):
x.shooting = True
x.special_preperation = request.POST.get("specialpre")
x.days_shoot_required = request.POST.get("shoot")
x.percentage_location = request.POST.get("location")
x.percentage_scene = request.POST.get(
"scene"
) # percentage of scenes having stunts
percentage_scene = request.POST.get(
"scene"
)
x.major_prosthetic = request.POST.get("major")
x.during_production = request.POST.get("during_pro")
x.save()
# Dream cast & Locations
if request.POST.get("dream_cast_locations"):
x.dream_cast_locations = True
dream_cast_locations = True
x.upload_image1 = request.FILES.get("uploadimage1")
upload_image1 = request.FILES.get("uploadimage1")
x.leadcharacter = [
request.POST.get("leadcharacter"),
request.POST.get("proposedactor1"),
x.upload_image1,
]
leadcharacter = [
request.POST.get("leadcharacter"),
request.POST.get("proposedactor1"),
upload_image1,
]
# x.leadcharacter = request.POST.get('leadcharacter')
# x.proposedactor1 = request.POST.get('proposedactor1')
x.upload_image2 = request.FILES.get("uploadimage2")
upload_image2 = request.FILES.get("uploadimage2")
x.secondleadcharacter = [
request.POST.get("secondleadcharacter"),
request.POST.get("proposedactor2"),
x.upload_image2,
]
secondleadcharacter = [
request.POST.get("secondleadcharacter"),
request.POST.get("proposedactor2"),
upload_image2,
]
# x.secondleadcharacter = request.POST.get('secondleadcharacter')
# x.proposedactor2 = request.POST.get('proposedactor2')
x.upload_image3 = request.FILES.get("uploadimage3")
upload_image3 = request.FILES.get("uploadimage3")
x.mainvillan = [
request.POST.get("mainvillan"),
request.POST.get("proposedactor3"),
x.upload_image3,
]
mainvillan = [
request.POST.get("mainvillan"),
request.POST.get("proposedactor3"),
upload_image3,
]
# x.mainvillan = request.POST.get('mainvillan')
# x.proposedactor3 = request.POST.get('proposedactor3')
x.upload_image4 = request.FILES.get("uploadimage4")
upload_image4 = request.FILES.get("uploadimage4")
x.associatecharacter = [
request.POST.get("associatecharacter"),
request.POST.get("proposedactor4"),
x.upload_image4,
]
associatecharacter = [
request.POST.get("associatecharacter"),
request.POST.get("proposedactor4"),
upload_image4,
]
# x.proposedactor4 = request.POST.get('proposedactor4')
x.upload_image5 = request.FILES.get("uploadimage5")
upload_image5 = request.FILES.get("uploadimage5")
x.associatevillan = [
request.POST.get("associatevillan"),
request.POST.get("proposedactor5"),
x.upload_image5,
]
associatevillan = [
request.POST.get("associatevillan"),
request.POST.get("proposedactor5"),
upload_image5,
]
# x.proposedactor5 = request.POST.get('proposedactor5')
x.upload_image6 = request.FILES.get("uploadimage6")
upload_image6 = request.FILES.get("uploadimage6")
x.firstlocation = [
request.POST.get("firstlocation"),
request.POST.get("proposedactor6"),
x.upload_image6,
]
firstlocation = [
request.POST.get("firstlocation"),
request.POST.get("proposedactor6"),
upload_image6,
]
x.upload_image7 = request.FILES.get("uploadimage7")
upload_image7 = request.FILES.get("uploadimage7")
x.secondlocation = [
request.POST.get("secondlocation"),
request.POST.get("proposedactor7"),
x.upload_image7,
]
secondlocation = [
request.POST.get("secondlocation"),
request.POST.get("proposedactor7"),
upload_image7,
]
# Pager_function
# x.proposedactor7 = request.POST.get('proposedactor7')
x.upload_image8 = request.FILES.get("uploadimage8")
upload_image8 = request.FILES.get("uploadimage8")
x.thirdlocation = [
request.POST.get("thirdlocation"),
request.POST.get("proposedactor8"),
x.upload_image8,
]
if request.session["character_introduction"] == "Character Introduction(Video)":
extraCharData = []
for charName, purposeActor, image in zip_longest(request.POST.getlist('character_list'), request.POST.getlist('proposed_actor_list'),request.FILES.getlist('upload_image_list')):
charData = {
"name": charName,
"purpose_actor": purposeActor,
"image": str(image)
}
extraCharData.append(charData)
print("$$$$$$$$$$$$$$______extraCharData______$$$$$$$$$$$$$$", extraCharData)
x.upload_image6 = str(extraCharData)
upload_image6 = str(extraCharData)
pitchvector1["upload_image6 "]=upload_image6
x.save()
# x.proposedactor8 = request.POST.get('proposedactor8')
x.save()
# # About Film budget
if request.POST.get("film_budget"):
x.film_budget = True
film_budget = True
# x.making_expenses = request.POST.get("expense")
x.percentage_scenes_required = request.POST.get("percentage_vfx")
# x.vfx_expenses = request.POST.get("vfx")
x.approx_budget_required = request.POST.get("approx_budget")
# ---------------------changes by neha 18/03/23
# x.making_expenses_currency = request.POST.get("projectbudget1")
# x.vfx_expenses_currency = request.POST.get("projectbudget2")
x.approx_budget_currency = request.POST.get("projectbudget3")
# --------end
x.save()
# cd.budget_amount = x.approx_budget_required
# # Strengths & Expectations
if request.POST.get("strengths_and_expectation"):
x.strengths_and_expectation = True
x.script_succed = request.POST.get("succed")
x.produced_now = request.POST.get("produce_now")
x.monetary_non_monetary_expectation = request.POST.get(
"expectations")
x.save()
cd.save()
# return render(request,"Pitchdeck/PitchnarratedVideos.html",{"script_id": y.script_id,"script_file_path": "","restrict_to_five": "Yes",},) # altered line
# -----BY HARSH
# try:
# membertype = privilegedUser1.objects.get(
# user=request.user, is_active="yes"
# ).memberType
# except:
# messages.error(request, "You are not a privileged member.")
# return render(request, "Pitchdeck/Pitchnarrate1.html")
request.session["script_id"] = y.script_id
script_id=request.session["script_id"]
request.session["numPages"] = y.numPages
request.session["actionline_language"] = y.actionline_language
request.session["actionline_script_language"] = y.actionline_script_language
request.session["dialogues_language"] = y.dialogues_language
request.session["dialogues_script_language"] = y.dialogues_script_language
request.session["languages"] = [
y.actionline_language, y.dialogues_language]
request.session["document_name"] = y.document_name
request.session["script_title"] = y.script_title
request.session["script_file_path"] = y.script_file_path
context = {
"script_id": y.script_id,
"script_file_path": y.script_file_path,
}
context["restrict_to_five"] = "yes"
context["numPages"] = y.numPages
context['script_title'] = y.script_title
context["ndial_src"] = y.actionline_language
context["dial_src"] = y.dialogues_language
context["ndial_script"] = y.actionline_script_language
context["dial_script"] = y.dialogues_script_language
# y.progress = 40
y.save()
# Blockchain code by Asha..
request.session["pitchvector1"] = str(pitchvector1)
request.session["MNFScriptDatabase1"] = str(MNFScriptDatabase1)
# :::::::::::::
# x = User.objects.get(id=request.user)
# id = x.id
id = request.user.id
num_pages = request.session["numPages"]
print("did lil chanps1", num_pages)
# ---------------------------------------changes
if num_pages > 5:
# check user is priviledged member or not
if not privilegedUser1.objects.filter(user=request.user,is_active="yes").exists():
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("Not a privilage user"+ str(privilegedUser1.objects.filter(user=request.user,is_active="yes"))+ "\n")
context["membershipNarration"] = int(settings.MONTHLY_MEMBER)
request.session["UpdatePriviledgedUser"] = True
# try:
# 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
# )
# except:
# pass
pricelist = NarrationPricing(y.script_id, l, id)
print("pricelist in pre",pricelist)
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("4."+ str(pricelist)+ "\n")
request.session["total_amount"] = pricelist["total_amount"]
context["total_amount"] = pricelist["total_amount"]
context["amount_charged"] = pricelist["amount_charged"] + int(settings.MONTHLY_MEMBER)
request.session["amount_charged"] = pricelist["amount_charged"] + int(settings.MONTHLY_MEMBER)
# context["discount"] = context["total_amount"] + context["membershipNarration"] - context["amount_charged"]
# request.session["discount"]=round(context["discount"], 2)
# context["discount"] = request.session["discount"]
pdiscount= 0
context["pdiscount"] = pdiscount
context["sdiscount"] = pricelist["sdiscount"]
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("5.stafff discount-------------------" + str(context["sdiscount"]) + "\n")
if pricelist["sdiscount"]==0:
context["staff_discount_calculate"] = 0
else:
staff_discount_calculate = float((pricelist["sdiscount"] / 100) * pricelist["total_amount"])
context["staff_discount_calculate"] = staff_discount_calculate
p_discount_calculate = float((context["total_amount"]-context["staff_discount_calculate"])*pricelist["pdiscount"] / 100)
context["p_discount_calculate"] = p_discount_calculate
context["rdiscount"] = pricelist["rdiscount"]
running_discount_calculate = float((context["total_amount"]-context["staff_discount_calculate"]-context["p_discount_calculate"])*context["rdiscount"]/ 100)
context["running_discount_calculate"] = running_discount_calculate
context["imdiscount"] = pricelist["imdiscount"]
im_discount_calculate = float((context["total_amount"]-context["staff_discount_calculate"]-context["p_discount_calculate"]-context["running_discount_calculate"])*pricelist["imdiscount"]/ 100)
context["im_discount_calculate"] =round(im_discount_calculate,2)
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("5.student discount-------------------" + str(context["im_discount_calculate"]) + "\n")
# context["discount"] = context["total_amount"] - \
# context["amount_charged"]
# context["discount"]= context["amount_charged"]+ context["p_discount_calculate"]+ context["staff_discount_calculate"]+ context["running_discount_calculate"]+ context["im_discount_calculate"]
context["discount"] = float(context["staff_discount_calculate"]+context["p_discount_calculate"]+context["running_discount_calculate"]+context["im_discount_calculate"])
request.session["discount"]=round(context["discount"], 2)
context["discount"] = request.session["discount"]
print("did lil chanps0")
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
print("did lil chanps2")
request.session["pages_greater_than_five"] = "true"
indent_context = create_indent(request,"Pitchdeck",script_id,len(service_use), "",pricelist["total_amount"], pricelist["amount_charged"],context["discount"])
request.session["indent_context"] = indent_context
return render(request, "Pitchdeck/narration_checkoutnew.html", context)
else:
request.session["UpdatePriviledgedUser"] = False
pricelist = NarrationPricing(y.script_id, l, id) # changes done by manoj
print("pricelist in post",pricelist)
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("5." + str(pricelist) + "\n")
request.session["total_amount"] = pricelist["total_amount"]
context["total_amount"] = pricelist["total_amount"]
context["membershipNarration"] = 0
context["amount_charged"] = pricelist["amount_charged"]
request.session["amount_charged"] = pricelist["amount_charged"]
context["pdiscount"] = pricelist["pdiscount"]
context["sdiscount"] = pricelist["sdiscount"]
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("5.stafff discount-------------------" + str(context["sdiscount"]) + "\n")
if pricelist["sdiscount"]==0:
context["staff_discount_calculate"] = 0
else:
staff_discount_calculate = float((pricelist["sdiscount"] / 100) * pricelist["total_amount"])
context["staff_discount_calculate"] = staff_discount_calculate
p_discount_calculate = float((context["total_amount"]-context["staff_discount_calculate"])*pricelist["pdiscount"] / 100)
context["p_discount_calculate"] = p_discount_calculate
context["rdiscount"] = pricelist["rdiscount"]
running_discount_calculate = float((context["total_amount"]-context["staff_discount_calculate"]-context["p_discount_calculate"])*context["rdiscount"]/ 100)
context["running_discount_calculate"] = running_discount_calculate
context["imdiscount"] = pricelist["imdiscount"]
im_discount_calculate = float((context["total_amount"]-context["staff_discount_calculate"]-context["p_discount_calculate"]-context["running_discount_calculate"])*pricelist["imdiscount"]/ 100)
context["im_discount_calculate"] =round(im_discount_calculate,2)
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("5.student discount-------------------" + str(context["im_discount_calculate"]) + "\n")
# context["discount"] = context["total_amount"] - \
# context["amount_charged"]
# context["discount"]= context["amount_charged"]+ context["p_discount_calculate"]+ context["staff_discount_calculate"]+ context["running_discount_calculate"]+ context["im_discount_calculate"]
context["discount"] = float(context["staff_discount_calculate"]+context["p_discount_calculate"]+context["running_discount_calculate"]+context["im_discount_calculate"])
request.session["discount"]=round(context["discount"], 2)
context["discount"] = request.session["discount"]
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
print("did lil chanps2")
request.session["pages_greater_than_five"] = "true"
indent_context = create_indent(request,"Pitchdeck",script_id,len(service_use), "",pricelist["total_amount"], pricelist["amount_charged"],context["discount"])
request.session["indent_context"] = indent_context
return render(request, "Pitchdeck/narration_checkoutnew.html", context)
else:
print("did lil chanps3")
request.session["pages_greater_than_five"] = "false"
context = {
"script_id": request.session["script_id"],
"script_file_path": request.session["script_file_path"],
"restrict_to_five": "no",
"servies_user":service_use,
"servies_user_length" : len(service_use),
}
return render(request, "Pitchdeck/PitchnarratedVideos.html", context)
# ---------------------------------end change
return render(
request,
"Pitchdeck/Pitchnarrate2.html",
{"cd": centralDatabase.objects.get(user_id=request.user)},
)
def NarrationPricing(script_id, l, u):
script_info = MNFScriptDatabase.objects.get(script_id=script_id)
vector_info = PitchVector.objects.get(script_id=script_id)
numPages = script_info.numPages
amt_linebyline = 0
amt_character_intro = 0
amt_screenplay_analysis = 0
amt_elevator_pitch = 0
amt_onepager = 0
amt_characterwise_narration = 0
if script_info.linebyline == "True":
amt_linebyline = settings.LINE_BY_LINE * numPages
if script_info.onepager == "True":
# amt_onepager = settings.ONE_PAGER
if numPages > 0 and numPages <= 15:
amt_onepager = settings.ONE_PAGER1
if numPages >= 16 and numPages <= 50:
amt_onepager = settings.ONE_PAGER2
if numPages >= 51 and numPages <= 100:
amt_onepager = settings.ONE_PAGER3
if numPages > 100:
amt_onepager = settings.ONE_PAGER4
if script_info.elevator_pitch == "True":
# amt_elevator_pitch = settings.ELEVATOR_PITCH
if numPages > 0 and numPages <= 15:
amt_elevator_pitch = settings.ELEVATOR_PITCH1
if numPages >= 16 and numPages <= 50:
amt_elevator_pitch = settings.ELEVATOR_PITCH2
if numPages >= 51 and numPages <= 100:
amt_elevator_pitch = settings.ELEVATOR_PITCH3
if numPages > 100:
amt_elevator_pitch = settings.ELEVATOR_PITCH4
if script_info.screenplay_analysis == "True":
if numPages > 0 and numPages <= 15:
amt_screenplay_analysis = settings.SCREENPLAY_ANALYSIS1
if numPages >= 16 and numPages <= 50:
amt_screenplay_analysis = settings.SCREENPLAY_ANALYSIS2
if numPages >= 51 and numPages <= 100:
amt_screenplay_analysis = settings.SCREENPLAY_ANALYSIS3
if numPages > 100:
amt_screenplay_analysis = settings.SCREENPLAY_ANALYSIS4
if script_info.character_intro == "True":
# amt_character_intro = len(l) * settings.CHARACTER_INTRODUCTION
if numPages > 0 and numPages <= 15:
amt_character_intro = settings.CHARACTER_INTRODUCTION1
if numPages >= 16 and numPages <= 50:
amt_character_intro = settings.CHARACTER_INTRODUCTION2
if numPages >= 51 and numPages <= 100:
amt_character_intro = settings.CHARACTER_INTRODUCTION3
if numPages > 100:
amt_character_intro = settings.CHARACTER_INTRODUCTION4
if script_info.characterwise_narration == "True":
# selected_character = vector_info.selected_characters
# selected_character = json.loads(selected_character)
# amt_characterwise_narration = (
# len(selected_character) * settings.CHARACTERWISE_NARATION
# )
amt_characterwise_narration = settings.CHARACTERWISE_NARATION * numPages
total_amount = (
amt_linebyline
+ amt_onepager
+ amt_elevator_pitch
+ amt_screenplay_analysis
+ amt_character_intro
+ amt_characterwise_narration
)
amount_charged = total_amount
# ----To calculate if package discount is available
if (
script_info.linebyline == "True"
and script_info.onepager == "True"
and script_info.elevator_pitch == "True"
and script_info.screenplay_analysis == "True"
and script_info.character_intro == "True"
and script_info.characterwise_narration == "True"
):
amount_charged = total_amount - (
total_amount * settings.COMPLETE_PITCHDECK / 100
)
if (
script_info.linebyline != "True"
and script_info.onepager == "True"
and script_info.elevator_pitch == "True"
and script_info.screenplay_analysis != "True"
and script_info.character_intro != "True"
and script_info.characterwise_narration != "True"
):
amount_charged = total_amount - (
total_amount * settings.ONEPAGER_ELEVATORPITCH / 100
)
if (
script_info.linebyline != "True"
and script_info.onepager != "True"
and script_info.elevator_pitch != "True"
and script_info.screenplay_analysis == "True"
and script_info.character_intro == "True"
and script_info.characterwise_narration != "True"
):
amount_charged = total_amount - (
total_amount * settings.SCREENPLAY_CHARACTERINTRO / 100
)
if (
script_info.linebyline == "True"
and script_info.onepager != "True"
and script_info.elevator_pitch != "True"
and script_info.screenplay_analysis == "True"
and script_info.character_intro == "True"
and script_info.characterwise_narration != "True"
):
amount_charged = total_amount - (
total_amount * settings.LBL_SCREENPLAY_CHARACTERINTRO / 100
)
pricelist = {
"total_amount": total_amount,
"amt_linebyline": amt_linebyline,
"amt_character_intro": amt_character_intro,
"amt_screenplay_analysis": amt_screenplay_analysis,
"amt_elevator_pitch": amt_elevator_pitch,
"amt_onepager": amt_onepager,
"amt_characterwise_narration": amt_characterwise_narration,
"pdiscount":int(0),
}
# ------To calculate priviledge discount
user = User.objects.get(id=u)
# manoj updated code for priviledged user
try:
memberType = privilegedUser1.objects.filter(user=user, is_active="yes") # changes done by manoj
if memberType:
memberType = memberType.first().memberType
if memberType == "normal":
pricelist["pdiscount"] = 0
elif memberType == "yearly":
pricelist["pdiscount"] = settings.YEARLY_MEMBER_ADDITIONAL
amount_charged = amount_charged - (
settings.YEARLY_MEMBER_ADDITIONAL * amount_charged / 100
)
elif memberType == "Life Member":
pricelist["pdiscount"] = settings.LIFE_MEMBER_ADDITIONAL
amount_charged = amount_charged - (
settings.LIFE_MEMBER_ADDITIONAL * amount_charged / 100
)
except:
pricelist["pdiscount"] = 0
pricelist["sdiscount"] = 0
if User.objects.get(id=u).is_staff: # changes done by manoj
pricelist["sdiscount"] = settings.EMPLOY_DISCOUNT
amount_charged = amount_charged - (
settings.EMPLOY_DISCOUNT * amount_charged / 100
)
pricelist["rdiscount"] = settings.RUNNING_DISCOUNT_PITCHDECK
amount_charged = amount_charged - (
settings.RUNNING_DISCOUNT_PITCHDECK * amount_charged / 100
)
pricelist["imdiscount"] = 0
# changes done by manoj
if Institutional_user.objects.filter(user=user, status="verified").exists():
pricelist["imdiscount"] = settings.IM_DISCOUNT
amount_charged = amount_charged - \
(settings.IM_DISCOUNT * amount_charged / 100)
pricelist["amount_charged"] = float(round(amount_charged, 2))
return pricelist
# @csrf_exempt
# @require_GET
# def Pitch_creation(request):
# reset_progress_dict(userId=request.user.id)
# script_id = request.GET["script_id"]
# from pymongo import MongoClient
# # MongoDBUrl = "mongodb+srv://mynextfilm:mnf123@cluster0.ojasb.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"
# client = MongoClient(MongoDBUrl)
# db = client.DB
# ScriptDatabase = "mnfapp_mnfscriptdatabase"
# script_info = db[ScriptDatabase].find_one({"script_id": script_id})
# script_file_path = script_info.get("script_file_path")
# # try:
# data_for_blockchain = []
# data_for_blockchain.append(script_file_path)
# # raise ValueError #-----to test for payment refund commentout
# update_progress(userId=request.user.id, progress=30)
# try:
# print("vector started in pitchcretatio")
# vector_generation.vector_gen(script_file_path, script_id)
# print("Vectors generated succesfully")
# update_progress(userId=request.user.id, progress=50)
# except Exception as e:
# update_progress(userId=request.user.id, progress=0)
# time.sleep(20)
# delet_user_progress(userId=request.user.id)
# sys.exit(e)
# script_info = db[ScriptDatabase].find_one({"script_id": script_id})
# VectorDatabase = "mnfapp_pitchvector"
# vector_info = db[VectorDatabase].find_one({"script_id": script_id})
# # try:
# if script_info != None:
# # Code to convert docx to pdf
# """
# str1 = "unoconv -f pdf"
# str2 = script_info.get("script_file_path")
# str3 = str1 + " " + str2
# print("Filpath:", script_info.get("script_file_path"))
# os.system(str3)
# print("File converted")
# temp = script_info.get("script_file_path").split("/")
# temp = temp[-1].split(".")
# # print(rf"{basePath}/MNF/media/PdfFiles/{temp} + '.pdf'")
# """
# document_name = script_info["document_name"][0:-5]
# script_info[
# "script_file_pdf_path"
# ] = rf"{basePath}/media/PdfFiles/{document_name}.pdf"
# print("Pitch Creation", script_info)
# script_info["narration_video_path"] = ""
# script_info["line_by_line_narration_video_path"] = ""
# script_info["script_genre"] = ""
# # pdf = PdfFileReader(open(script_info.get("script_file_pdf_path"), "rb"))
# # number_of_pages = pdf.getNumPages()
# # print("No. of pages in PDF:", number_of_pages)
# # script_info["number_of_pages"] = int(number_of_pages)
# db[ScriptDatabase].save(script_info)
# else:
# print(" Entry for script id not found")
# # restrict = request.GET["restrict_to_five"]
# # narration_generation.narration_function(script_id, restrict)
# # narration_generation.narration_function(script_id)
# # linebyline_narration.line_by_line_narration(script_id) #changed 12th March
# print(
# "**************************************************************************************************************"
# )
# print(
# "******************************_______*************************************************************************"
# )
# # screenplay_main.screenplay_function(script_id)
# # pitch_function.pitch_function(script_id)
# print("________start here______")
# script_title = script_info.get("script_title")
# print("$$")
# if script_info["characterwise_narration"] == "True":
# """
# access selected_characters here from database
# run characterwise script generation function
# """
# try:
# print("________characterwise_narration______")
# selected_character = vector_info["selected_characters"]
# # selected_character = script_info["selected_characters"]
# input_dir = request.session.get("script_dir_url")
# input_filename = request.session["script_name"]
# selected_character = json.loads(
# selected_character) # json string to list
# dic_of_chr_path = mnf_ss.get_subset_character_script(
# input_dir, input_filename, selected_character
# )
# print("Out of Mohit Function")
# path_list = []
# # character_pagecount=[]
# for i in selected_character:
# print("Entering loop of character ,", i)
# c = MNFScriptDatabase()
# c.script_id = "scr_" + str(int(time.time()))
# # c.main_script_id = script_info["main"]
# print("script_info connecting_id",
# script_info["connecting_id"])
# # c.connecting_id = script_id
# c.connecting_id = script_info
# print("Printing Script id of first character", c.script_id)
# c.script_title = script_title + \
# "_" + str(i) # session variable
# url = dic_of_chr_path[i]
# pdfname = url.split("/")[-1][0:-5] + ".pdf"
# c.script_file_path = url
# str1 = "unoconv -f pdf"
# # str2 = script_info.get("script_file_path")
# # str2 = url.replace(" ","_")
# str2 = url
# str3 = str1 + " " + '"' + str2 + '"'
# print("Filpath:", url)
# os.system(str3)
# print("File converted")
# temp = url.split("/")
# # name.docx
# temp = temp[-1].split(".")
# # c.script_file_pdf_path = rf"{basePath}/media/PdfFiles/{temp[0]}"+ ".pdf"
# c.script_file_pdf_path = rf"{url[:-5]}" + ".pdf"
# print("printing script path", c.script_file_pdf_path)
# print("printing url", url)
# print(
# "************************",
# rf"{basePath}/media/PdfFiles/{temp[0]}" + ".pdf",
# )
# # pdf = PdfFileReader(open(rf"{basePath}/media/PdfFiles/{temp[0]}"+ ".pdf", "rb"))
# pdf = PdfFileReader(open(rf"{c.script_file_pdf_path}", "rb"))
# # number_of_pages = countPages(
# # url, pdfname) # get the page count
# print("1")
# number_of_pages = pdf.getNumPages()
# # character_pagecount.append(number_of_pages)
# print("1")
# c.numPages = number_of_pages
# # print("1")
# # c.script_file_path = url
# print("1")
# c.actionline_language = request.session["non_dial_src_lang"]
# print("1")
# c.actionline_script_language = request.session["non_dial_src_script"]
# print("1")
# c.dialogues_script_language = request.session["dial_src_script"]
# print("1")
# c.dialogues_language = request.session["dial_src_lang"]
# c.author_name = request.session["author_name"]
# print("1")
# # c.user_id = script_info["user_id_id"]
# # c.user_id = request.user
# print("1")
# c.save()
# print("Vector Creating for Character")
# print("script path", c.script_file_path)
# print("script id", c.script_id)
# vector_generation.vector_gen(c.script_file_path, c.script_id)
# print(f"Vector Created for {script_title}")
# # c.save()
# linebyline_narration.line_by_line_narration(
# c.script_id) # error here
# print("Characterwise Video Created")
# c.line_by_line_narration_video_path = (
# rf"{basePath}/media/videos/Narrated_Videos/{c.script_title}.webm"
# )
# # lst.append()
# path_list.append(
# rf"{basePath}/media/videos/Narrated_Videos/{c.script_title}.webm"
# )
# # exit()
# # script_info["character_pagecount"] = json.dumps(character_pagecount)
# script_info["characterwise_video_path"] = json.dumps(path_list)
# data_for_blockchain.append(json.dumps(path_list))
# db[ScriptDatabase].save(script_info)
# except Exception as e:
# update_progress(userId=request.user.id, progress=0)
# time.sleep(10)
# delet_user_progress(userId=request.user.id)
# sys.exit(e)
# # print("will this work",dic_of_chr_path)
# if script_info["onepager"] == "True":
# try:
# print("Before pager_function", script_id)
# Pager_function.pager_function(script_id)
# script_info[
# "onepager_pdf_path"
# ] = rf"{basePath}/media/Onepager/{script_title}.pdf"
# data_for_blockchain.append(
# rf"{basePath}/media/Onepager/{script_title}.pdf")
# db[ScriptDatabase].save(script_info)
# print("One Pager generated sucessfully")
# except Exception as e:
# update_progress(userId=request.user.id, progress=0)
# time.sleep(10)
# delet_user_progress(userId=request.user.id)
# sys.exit(e)
# if script_info["screenplay_analysis"] == "True":
# try:
# print("Rohit before")
# screenplay_main.screenplay_function(script_id)
# print("Rohit after")
# script_info[
# "screenplay_analysis_video_path"
# ] = rf"{basePath}/media/Screenplay/{script_title}_screenplay.webm"
# data_for_blockchain.append(
# rf"{basePath}/media/Screenplay/{script_title}_screenplay.webm"
# )
# db[ScriptDatabase].save(script_info)
# print("Screenplay generated sucessfully")
# except Exception as e:
# update_progress(userId=request.user.id, progress=0)
# time.sleep(10)
# delet_user_progress(userId=request.user.id)
# sys.exit(e)
# if script_info["elevator_pitch"] == "True":
# try:
# print("Entering ElevatorPitch: ")
# pitch_function.pitch_function(script_id)
# script_info["elevator_pitch_video_path"] = (
# rf"{basePath}/media/Pitch/" +
# str(script_title) + "_pitchdeck.webm"
# )
# data_for_blockchain.append(
# rf"{basePath}/media/Pitch/" +
# str(script_title) + "_pitchdeck.webm"
# )
# print("ElevatorPitch generated sucessfully")
# db[ScriptDatabase].save(script_info)
# print("Rohit2")
# except Exception as e:
# update_progress(userId=request.user.id, progress=0)
# time.sleep(10)
# delet_user_progress(userId=request.user.id)
# sys.exit(e)
# if script_info["character_intro"] == "True":
# try:
# print("----Entering character introduction-----")
# # obj = TestingC.Char_video_class(script_id)
# # characterdata = obj.char_data_written()
# # for i in characterdata:
# # obj.first_intro_page(i)
# Char_function.char_function(script_id)
# script_info["character_intro_video_path"] = rf'{basePath}/media/character_Intro/{str(script_title)}.webm'
# # # # data_for_blockchain.append(rf"{basePath}/media/Pitch/" + str(script_title) + "_pitchdeck.webm")
# print("character introduction generated sucessfully")
# db[ScriptDatabase].save(script_info)
# print("Rohit2")
# except Exception as e:
# update_progress(userId=request.user.id, progress=0)
# time.sleep(10)
# delet_user_progress(userId=request.user.id)
# sys.exit(e)
# if script_info["linebyline"] == "True":
# try:
# print("Rohit3")
# linebyline_narration.line_by_line_narration(script_id)
# print("Narration generated sucessfully")
# script_title = script_info.get("script_title")
# # script_info[
# # 'narration_video_path'] = rf"{basePath}/media/videos/Narrated_Videos/{script_title}.webm"
# script_info[
# "line_by_line_narration_video_path"
# ] = rf"{basePath}/media/videos/Narrated_Videos/{script_title}.webm"
# script_info["narration_video_path"] = script_info[
# "line_by_line_narration_video_path"
# ]
# except Exception as e:
# update_progress(userId=request.user.id, progress=0)
# time.sleep(10)
# delet_user_progress(userId=request.user.id)
# sys.exit(e)
# # data_for_blockchain.append(script_info["narration_video_path"])
# context = {
# "status": "Success",
# }
# user = request.user
# email = user.email
# # ------------------------------------------------------blockchain
# # script_path = str(rf"{basePath}/media/scripts/{script_title}")
# print("list ", data_for_blockchain)
# # data = [script_path, data_for_blockchain ]
# # print("All Files ",data)
# print("Function 11")
# update_progress(userId=request.user.id, progress=85)
# try:
# files, timestamp = upload_zipfile_to_ipfs(
# data_for_blockchain, str(script_title), "pitchdeck", email
# )
# script_info["timestamp"] = timestamp
# print("timestamp of blockchain", files, timestamp)
# script_info["uploaded_script_encoded"] = files
# # script_info["translated_script_encoded"] = files[1]
# db[ScriptDatabase].save(script_info)
# except Exception as e:
# update_progress(userId=request.user.id, progress=0)
# time.sleep(10)
# delet_user_progress(userId=request.user.id)
# sys.exit(e)
# # ---------------------------------------------------------------------------
# current_site = get_current_site(request)
# context = {
# "domain": current_site.domain,
# "serviceName": "Pitch Creation",
# "name": email,
# "amount": request.POST.get("total_amount"),
# # "timestamp":timestamp,
# # "key":script_title
# }
# num_pages = request.session["numPages"]
# if num_pages > 5: # ----------------neha
# request.session["pages_greater_than_five"] == "true"
# message = render_to_string("narration/MR31.html", context)
# text_content = strip_tags(message)
# msg = EmailMultiAlternatives(
# "Successfully Narrated",
# text_content,
# settings.EMAIL_HOST_USER,
# [email],
# )
# msg.attach_alternative(message, "text/html")
# msg.send()
# else:
# # send mail only for confirmation hjgjh
# request.session["pages_greater_than_five"] = "false" # --------neha
# message = render_to_string("narration/MR31.html", context)
# text_content = strip_tags(message)
# msg = EmailMultiAlternatives(
# "Successfully Narrated",
# text_content,
# settings.EMAIL_HOST_USER,
# [email],
# )
# msg.attach_alternative(message, "text/html")
# msg.send()
# del request.session["pages_greater_than_five"]
# var = Notifications(
# user_id=request.user,
# notification=str(
# "Narration generated successfully for " + script_title),
# )
# var.save()
# update_progress(userId=request.user.id, progress=100)
# time.sleep(10)
# delet_user_progress(userId=request.user.id)
# return JsonResponse(context)
def Pitch_creation(request):
reset_progress_dict(userId=request.user.id)
script_id = request.GET["script_id"]
from pymongo import MongoClient
# MongoDBUrl = "mongodb+srv://mynextfilm:mnf123@cluster0.ojasb.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"
client = MongoClient(MongoDBUrl)
db = client.DB
ScriptDatabase = "mnfapp_mnfscriptdatabase"
script_info = db[ScriptDatabase].find_one({"script_id": script_id})
print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>",script_info)
script_file_path = script_info.get("script_file_path")
print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>",script_file_path)
data_for_blockchain = []
data_for_blockchain.append(script_file_path)
# raise ValueError #-----to test for payment refund commentout
update_progress(userId=request.user.id, progress=30)
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check1.txt","a") as file01:
file01.write("6.INSIDE pitch_creation function : vector id is -->" + str(script_id)+ "\n")
#-----------------modified audit
script_id_audit = request.session["script_id_audit"]
check_status_and_trigger_vector(script_id_audit,script_id)
# audit_vector_integration_pitchdeck(script_id_audit,script_id)
print(":>:>:>complete")
# audit_vector_integration(script_file_path,script_id,request)
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check1.txt","a") as file01:
file01.write("7.Vectors generated succesfully" + "\n")
# try:
# print("vector started in pitchcretatio")
# # from scriptAudit.views import generate_script_id
# # generate_script_id(script_file_path, request)
# print("vector:",script_id)
# # vector_generation.vector_gen(script_file_path, script_id)
# audit_vector_integration(script_file_path,script_id,request)
# print("vector:","Vectors generated succesfully")
# with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","w+") as file01:
# file01.write("Vectors generated succesfully")
# # audit_vector_integration(script_file_path,script_id,request)
# update_progress(userId=request.user.id, progress=50)
# except Exception as e:
# update_progress(userId=request.user.id, progress=0)
# time.sleep(20)
# delet_user_progress(userId=request.user.id)
# sys.exit(e)
# print("vector:","outside vector generation")
script_info = db[ScriptDatabase].find_one({"script_id": script_id})
VectorDatabase = "mnfapp_pitchvector"
vector_info = db[VectorDatabase].find_one({"script_id": script_id})
# Blockchain data
# script_info1 = converted_dict["MNFScriptDatabase1"]
# vector_info1 = converted_dict["pitchvector1"]
# try:
print("vector:","outside vector generation")
MNFScriptDatabase1 = eval(request.session["MNFScriptDatabase1"])
pitchvector1 = eval(request.session["pitchvector1"])
if script_info != None:
# Code to convert docx to pdf
"""
str1 = "unoconv -f pdf"
str2 = script_info.get("script_file_path")
str3 = str1 + " " + str2
print("Filpath:", script_info.get("script_file_path"))
os.system(str3)
print("File converted")
temp = script_info.get("script_file_path").split("/")
temp = temp[-1].split(".")
# print(rf"{basePath}/MNF/media/PdfFiles/{temp} + '.pdf'")
"""
document_name = script_info["document_name"][0:-5]
script_info[
"script_file_pdf_path"
] = rf"{basePath}/media/PdfFiles/{document_name}.pdf"
print("Pitch Creation", script_info)
script_info["narration_video_path"] = ""
script_info["line_by_line_narration_video_path"] = ""
script_info["script_genre"] = ""
# MNFScriptDatabase1["script_file_pdf_path"] = rf"{basePath}/media/PdfFiles/{document_name}.pdf"
# Blockchain
# pdf = PdfFileReader(open(script_info.get("script_file_pdf_path"), "rb"))
# number_of_pages = pdf.getNumPages()
# print("No. of pages in PDF:", number_of_pages)
# script_info["number_of_pages"] = int(number_of_pages)
# /////////////
db[ScriptDatabase].save(script_info)
else:
print(" Entry for script id not found")
# restrict = request.GET["restrict_to_five"]
# narration_generation.narration_function(script_id, restrict)
# narration_generation.narration_function(script_id)
# linebyline_narration.line_by_line_narration(script_id) #changed 12th March
print(
"**************************************************************************************************************"
)
print(
"******************************_______*************************************************************************"
)
# screenplay_main.screenplay_function(script_id)
# pitch_function.pitch_function(script_id)
print("________start here______")
script_title = script_info.get("script_title")
print("$$")
# manoj
service_name_list = []
videopath_for_email=[]
if script_info["characterwise_narration"] == "True":
"""
access selected_characters here from database
run characterwise script generation function
"""
try:
print("________characterwise_narration______")
selected_character = vector_info["selected_characters"]
# selected_character = script_info["selected_characters"]
input_dir = request.session.get("script_dir_url")
input_filename = request.session["script_name"]
selected_character = json.loads(
selected_character) # json string to list
#-----------------------------------------------------------modified audit
print("SELECTED CHARACTER",selected_character)
script_id_audit = request.session["script_id_audit"]
print("yameen script_id_audit",script_id_audit)
# script_audit_obj = NeutralAudit(script_id_audit)
# dic_of_chr_path = script_audit_obj.get_character_subset(selected_character)
neutral_aud = NeutralAudit(script_id_audit)
char_sub = neutral_aud.get_character_subset(selected_character)
print("CHARACTER SUBSET",char_sub)
# dic_of_chr_path = mnf_ss.get_subset_character_script(
# input_dir, input_filename, selected_character
# )
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("8." +str(char_sub) + "\n")
dic_of_chr_path = char_sub
#-------------------------------------------------------------------end
logging.debug(f"slected_charcter {selected_character}")
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("selected characters list----------" +str(selected_character) + "\n")
print("Out of Mohit Function")
path_list = []
# character_pagecount=[]
for i in selected_character:
print("Entering loop of character ,", i)
c = MNFScriptDatabase()
c.script_id = "scr_" + str(int(time.time()))
print("script neha","scr_" + str(int(time.time())))
# logging.debug(f"slected_charcter {f"script neha scr_{str(int(time.time()))}")
# c.main_script_id = script_info["main"]
print("script_info connecting_id",
script_info["connecting_id"])
# c.connecting_id = script_id
c.connecting_id = script_info
print("Printing Script id of first character", c.script_id)
c.script_title = script_title + \
"_" + str(i) # session variable
url = dic_of_chr_path[i]
pdfname = url.split("/")[-1][0:-5] + ".pdf"
c.script_file_path = url
str1 = "unoconv -f pdf"
# str2 = script_info.get("script_file_path")
# str2 = url.replace(" ","_")
str2 = url
str3 = str1 + " " + '"' + str2 + '"'
print("Filpath:", url)
os.system(str3)
print("File converted")
temp = url.split("/")
# name.docx
temp = temp[-1].split(".")
# c.script_file_pdf_path = rf"{basePath}/media/PdfFiles/{temp[0]}"+ ".pdf"
c.script_file_pdf_path = rf"{url[:-5]}" + ".pdf"
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("9. script file pdf path"+ str(c.script_file_pdf_path) + "\n")
print("printing script path", c.script_file_pdf_path)
print("printing url", url)
print(
"************************",
rf"{basePath}/media/PdfFiles/{temp[0]}" + ".pdf",
)
# pdf = PdfFileReader(open(rf"{basePath}/media/PdfFiles/{temp[0]}"+ ".pdf", "rb"))
pdf = PdfFileReader(open(rf"{c.script_file_pdf_path}", "rb"))
# number_of_pages = countPages(
# url, pdfname) # get the page count
print("1")
number_of_pages = pdf.getNumPages()
# character_pagecount.append(number_of_pages)
print("1")
c.numPages = number_of_pages
# print("1")
# c.script_file_path = url
print("1")
c.actionline_language = request.session["non_dial_src_lang"]
print("1")
c.actionline_script_language = request.session["non_dial_src_script"]
print("1")
c.dialogues_script_language = request.session["dial_src_script"]
print("1")
c.dialogues_language = request.session["dial_src_lang"]
if "author_name" in request.session:
c.author_name = request.session["author_name"]
print("1")
# c.user_id = script_info["user_id_id"]
# c.user_id = request.user
print("1")
c.save()
print("Vector Creating for Character")
print("script path", c.script_file_path)
print("script id", c.script_id)
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("9." + str(i) + str(c.script_file_path)+str(c.script_id) + "\n")
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("10.generated vectors for" + str(i) + "\n")
vector_generation.vector_gen(c.script_file_path, c.script_id)
print(f"Vector Created for {script_title}")
# c.save()
print(i)
path = char_function(script_id,i)
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("11.path of character " + str(path) + "\n")
print("path neehhhhaa",path)
linebyline_narration.line_by_line_narration(
c.script_id,True, path) # error here
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("12. line by line complete " + "\n")
print("Characterwise Video Created")
c.line_by_line_narration_video_path = (
rf"{basePath}/media/videos/Narrated_Videos/{c.script_title}.webm"
)
# lst.append()
path_list.append(
rf"{basePath}/media/videos/Narrated_Videos/{c.script_title}.webm"
)
print(path_list,"######################## path list ########################")
data_for_blockchain.append(rf"{basePath}/media/videos/Narrated_Videos/{c.script_title}.webm")
# exit()
script_info["selected_characters"] = json.dumps(selected_character)
script_info["characterwise_video_path"] = json.dumps(path_list)
MNFScriptDatabase1["selected_characters"] = json.dumps(selected_character)
MNFScriptDatabase1["characterwise_video_path"] = json.dumps(path_list)
# data_for_blockchain.append(json.dumps(path_list))
db[ScriptDatabase].save(script_info)
print("Characterwise Narration Video Created")
#----------use for email path
email_path=script_info["characterwise_video_path"]
videopath_for_email.append(email_path)
# manoj
service_name_list.append("Characterwise Narration")
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("11.END of characterwise Narration" +"\n")
except Exception as e:
update_progress(userId=request.user.id, progress=0)
time.sleep(10)
delet_user_progress(userId=request.user.id)
sys.exit(e)
# print("will this work",dic_of_chr_path)
if script_info["onepager"] == "True":
try:
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check1.txt","a") as file01:
file01.write("one pager started" +"\n")
print("Before pager_function", script_id)
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt1","a") as file01:
file01.write("one pager started" +str(script_id)+"\n")
Pager_function.pager_function(script_id)
script_info[
"onepager_pdf_path"
] = rf"{basePath}/media/Onepager/{script_title}.pdf"
data_for_blockchain.append(
rf"{basePath}/media/Onepager/{script_title}.pdf")
# db[ScriptDatabase].save(script_info)
print("One Pager generated sucessfully")
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check1.txt","a") as file01:
file01.write("One Pager generated sucessfully" + str(script_info["onepager_pdf_path"]) + "\n")
# Blockchain
MNFScriptDatabase1["onepager_pdf_path"] = rf"{basePath}/media/Onepager/{script_title}.pdf"
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check1.txt","a") as file01:
file01.write("After mnfblockchain" + "\n")
temp_dir = tempfile.mkdtemp()
short_path = os.path.join(temp_dir, "file.pdf")
Onepagerfile = rf"{basePath}/media/Onepager/{script_title}.pdf"
with open(Onepagerfile, 'rb') as source_file, open(short_path, 'wb') as target_file:
target_file.write(source_file.read())
hash = uploadDataToIPFSNode(short_path)
os.remove(short_path)
os.rmdir(temp_dir)
MNFScriptDatabase1["Onepager_Script_fileHash"] = hash
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check1.txt","a") as file01:
file01.write("After mnfblockchain" +hash+ "\n")
# hash = response.json()["hash"]
# with open("/home/user/mnf/project/MNF/Pitchdeck/error_check1.txt","a") as file01:
# file01.write("Blockchainfile: " + str(hash) + "\n")
# #use for email path
email_path=script_info["onepager_pdf_path"]
videopath_for_email.append(email_path)
# manoj
service_name_list.append("One Pager")
except Exception as e:
update_progress(userId=request.user.id, progress=0)
time.sleep(10)
delet_user_progress(userId=request.user.id)
sys.exit(e)
if script_info["screenplay_analysis"] == "True":
try:
print("Rohit before")
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("Screenplay started" + "\n")
screenplay_main.screenplay_function(script_id)
print("Rohit after")
script_info[
"screenplay_analysis_video_path"
] = rf"{basePath}/media/Screenplay/{script_title}_screenplay.webm"
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write('path of screenplay'+str(script_info["screenplay_analysis_video_path"])+"\n")
data_for_blockchain.append(
rf"{basePath}/media/Screenplay/{script_title}_screenplay.webm"
)
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write('blockchain'+"\n")
db[ScriptDatabase].save(script_info)
print("Screenplay generated sucessfully")
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write('screenplay generated'+"\n")
# blockchain
temp_dir = tempfile.mkdtemp()
short_path = os.path.join(temp_dir, "file.pdf")
MNFScriptDatabase1["screenplay_analysis_video_path"] = rf"{basePath}/media/Screenplay/{script_title}_screenplay.webm"
Screenplayfile = rf"{basePath}/media/Screenplay/{script_title}_screenplay.webm"
with open(Screenplayfile, 'rb') as source_file, open(short_path, 'wb') as target_file:
target_file.write(source_file.read())
hash = uploadDataToIPFSNode(short_path)
os.remove(short_path)
os.rmdir(temp_dir)
print("HASH>>>",hash)
MNFScriptDatabase1["Screenplayh_Script_fileHash"] = hash
#use for email path
email_path= script_info["screenplay_analysis_video_path"]
videopath_for_email.append(email_path)
# manoj
service_name_list.append("Screenplay Analysis")
except Exception as e:
update_progress(userId=request.user.id, progress=0)
time.sleep(10)
delet_user_progress(userId=request.user.id)
sys.exit(e)
if script_info["elevator_pitch"] == "True":
try:
print("Entering ElevatorPitch: ")
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("Elevator started" + "\n")
pitch_function.pitch_function(script_id)
script_info["elevator_pitch_video_path"] = (
rf"{basePath}/media/Pitch/" +
str(script_title) + "_pitchdeck.webm"
)
#Blockchain
temp_dir = tempfile.mkdtemp()
short_path = os.path.join(temp_dir, "file.pdf")
MNFScriptDatabase1["elevator_pitch_video_path"] = rf"{basePath}/media/Pitch/" +str(script_title) + "_pitchdeck.webm"
ElevatorPitchfile = rf"{basePath}/media/Pitch/" +str(script_title) + "_pitchdeck.webm"
with open(ElevatorPitchfile, 'rb') as source_file, open(short_path, 'wb') as target_file:
target_file.write(source_file.read())
hash = uploadDataToIPFSNode(short_path)
os.remove(short_path)
os.rmdir(temp_dir)
MNFScriptDatabase1["ElevatorPitch_Script_fileHash"] = hash
data_for_blockchain.append(
rf"{basePath}/media/Pitch/" +
str(script_title) + "_pitchdeck.webm"
)
print("ElevatorPitch generated sucessfully")
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("ElevatorPitch generated sucessfully" + str(script_info["elevator_pitch_video_path"]) + "\n")
db[ScriptDatabase].save(script_info)
print("Rohit2")
#use for email path
email_path= script_info["elevator_pitch_video_path"]
videopath_for_email.append(email_path)
# manoj
service_name_list.append("Elevator Pitch")
except Exception as e:
update_progress(userId=request.user.id, progress=0)
time.sleep(10)
delet_user_progress(userId=request.user.id)
sys.exit(e)
if script_info["character_intro"] == "True":
try:
print("----Entering character introduction-----")
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("character introduction started" + "\n")
# obj = TestingC.Char_video_class(script_id)
# characterdata = obj.char_data_written()
# for i in characterdata:
# obj.first_intro_page(i)
Char_function.char_function(script_id)
script_info["character_intro_video_path"] = rf'{basePath}/media/character_Intro/{str(script_title)}.webm'
# # # data_for_blockchain.append(rf"{basePath}/media/Pitch/" + str(script_title) + "_pitchdeck.webm")
print("character introduction generated sucessfully")
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("Character introduction generated sucessfully" + str(script_info["character_intro_video_path"]) + "\n")
db[ScriptDatabase].save(script_info)
print("Rohit2")
#Blockchain
temp_dir = tempfile.mkdtemp()
short_path = os.path.join(temp_dir, "file.pdf")
MNFScriptDatabase1["character_intro_video_path"] = rf"{basePath}/media/Screenplay/{script_title}_screenplay.webm"
Characterfile = rf'{basePath}/media/character_Intro/{str(script_title)}.webm'
with open(Characterfile, 'rb') as source_file, open(short_path, 'wb') as target_file:
target_file.write(source_file.read())
hash = uploadDataToIPFSNode(short_path)
os.remove(short_path)
os.rmdir(temp_dir)
MNFScriptDatabase1["Characterfile_Script_fileHash"] = hash
#use for email path
email_path= script_info["character_intro_video_path"]
videopath_for_email.append(email_path)
# manoj
service_name_list.append("Character Introduction")
except Exception as e:
update_progress(userId=request.user.id, progress=0)
time.sleep(10)
delet_user_progress(userId=request.user.id)
sys.exit(e)
if script_info["linebyline"] == "True":
try:
print("Rohit3")
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check1.txt","a") as file01:
file01.write("Line by line started" + "\n")
linebyline_narration.line_by_line_narration(script_id)
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check1.txt","a") as file01:
file01.write("line by line complete" +"\n")
print("Narration generated sucessfully")
script_title = script_info.get("script_title")
# script_info[
# 'narration_video_path'] = rf"{basePath}/media/videos/Narrated_Videos/{script_title}.webm"
script_info[
"line_by_line_narration_video_path"
] = rf"{basePath}/media/videos/Narrated_Videos/{script_title}.webm"
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check1.txt","a") as file01:
file01.write("Line by line path" + str(script_info["line_by_line_narration_video_path"])+ "\n")
script_info["narration_video_path"] = script_info[
"line_by_line_narration_video_path"
]
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("Line by line generated sucessfully-----------------" + str(script_info["narration_video_path"]) + "\n")
#Blockchain
temp_dir = tempfile.mkdtemp()
short_path = os.path.join(temp_dir, "file.pdf")
MNFScriptDatabase1["line_by_line_narration_video_path"] = rf"{basePath}/media/Screenplay/{script_title}_screenplay.webm"
narrationfile = rf"{basePath}/media/videos/Narrated_Videos/{script_title}.webm"
with open(narrationfile, 'rb') as source_file, open(short_path, 'wb') as target_file:
target_file.write(source_file.read())
hash = uploadDataToIPFSNode(short_path)
os.remove(short_path)
os.rmdir(temp_dir)
MNFScriptDatabase1["narration_Script_fileHash"] = hash
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("Line by line generated sucessfully" + str(script_info["narration_video_path"]) + "\n")
#use for email path
email_path= script_info["line_by_line_narration_video_path"]
videopath_for_email.append(email_path)
# manoj
service_name_list.append("Line by line")
except Exception as e:
update_progress(userId=request.user.id, progress=0)
time.sleep(10)
delet_user_progress(userId=request.user.id)
sys.exit(e)
# data_for_blockchain.append(script_info["narration_video_path"])
# Blockchain
print("/n/n/n/n/nn/n/ngenarate all servies/n/n/n/n")
if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user)
MNFDatabase = {}
MNFDatabase["MNFScriptDatabase1"] = MNFScriptDatabase1
MNFDatabase["pitchvector1"] = pitchvector1
key1= "MyNextFilm"
UserId = blockchain_obj.user_id
project = request.session["blockchainscript_id"]
Data = str(MNFDatabase)
userPrivateKey = blockchain_obj.privateKey
userkey =decryptionOfPrivate(userPrivateKey)
hash = NarrationData(userkey.decode('utf-8'),UserId, project,Data)
print("my_tx_hash",hash)
context = {
"status": "Success",
}
user = request.user
email = user.email
# ------------------------------------------------------blockchain
# script_path = str(rf"{basePath}/media/scripts/{script_title}")
print("list ", data_for_blockchain)
# data = [script_path, data_for_blockchain ]
# print("All Files ",data)
print("Function 11")
update_progress(userId=request.user.id, progress=85)
try:
files, timestamp = upload_zipfile_to_ipfs(
data_for_blockchain, str(script_title), "pitchdeck", email
)
script_info["timestamp"] = timestamp
print("timestamp of blockchain", files, timestamp)
script_info["uploaded_script_encoded"] = files
# script_info["translated_script_encoded"] = files[1]
db[ScriptDatabase].save(script_info)
except Exception as e:
update_progress(userId=request.user.id, progress=0)
time.sleep(10)
delet_user_progress(userId=request.user.id)
sys.exit(e)
# ---------------------------------------------------------------------------
#use for email click here path
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("videopath_for_email." +str(videopath_for_email) + "\n")
click_for_email= ""
if len(videopath_for_email) == 1:
click_for_email = str(videopath_for_email[0])
print(click_for_email)
else:
click_for_email= ", ".join(videopath_for_email[:-1]) + " and " + videopath_for_email[-1]
print(click_for_email)
current_site = get_current_site(request)
context = {
"domain": current_site.domain,
"serviceName": "Pitch Creation",
"name": email,
"amount": request.POST.get("total_amount"),
# "click_email":click_for_email,
# "timestamp":timestamp,
# "key":script_title
}
# manoj for creating new subject according to services they used
subject_accordingto_service_list = ""
if len(service_name_list) == 1:
subject_accordingto_service_list = str(service_name_list[0])
else:
subject_accordingto_service_list = ", ".join(service_name_list[:-1]) + " and " + service_name_list[-1]
# manoj new subject line
# subject_accordingto_service_list += " narrated successfully"
num_pages = request.session["numPages"]
if num_pages > 5: # ----------------neha
request.session["pages_greater_than_five"] == "true"
to_email = [request.user.email]
email_code = 'TN1'
sendmail(to_email=to_email , email_code=email_code ,key_value={'service_name':subject_accordingto_service_list})
# message = render_to_string("narration/MR31.html", context)
# text_content = strip_tags(message)
# msg = EmailMultiAlternatives(
# subject_accordingto_service_list,
# text_content,
# settings.EMAIL_HOST_USER,
# [email],
# )
# msg.attach_alternative(message, "text/html")
# msg.send()
else:
# send mail only for confirmation hjgjh
request.session["pages_greater_than_five"] = "false" # --------neha
to_email = [request.user.email]
email_code = 'TN1'
sendmail(to_email=to_email , email_code=email_code )
# message = render_to_string("narration/MR31.html", context)
# text_content = strip_tags(message)
# msg = EmailMultiAlternatives(
# subject_accordingto_service_list,
# text_content,
# settings.EMAIL_HOST_USER,
# [email],
# )
# msg.attach_alternative(message, "text/html")
# msg.send()
del request.session["pages_greater_than_five"]
var = Notifications(
user_id=request.user,
notification=str(
"Narration generated successfully for " + script_title),
)
var.save()
update_progress(userId=request.user.id, progress=100)
time.sleep(10)
delet_user_progress(userId=request.user.id)
return JsonResponse(context)
# except Exception as e:
print("error is ", e)
payment_intent_id = script_info.get("payment_intent_id")
print("thisisgonnabeaRefund")
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)
try:
c = CurrencyRates()
rate = c.get_rate("USD", "INR")
except Exception as e:
print("pich creation", 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)
user = request.user
email = user.email
context = {
"serviceName": "Pitch Creation",
"name": email,
}
message = render_to_string("narration/MR28.html", context)
text_content = strip_tags(message)
msg = EmailMultiAlternatives(
"Incovenience is regretted",
text_content,
settings.EMAIL_HOST_USER,
[email],
)
msg.attach_alternative(message, "text/html")
msg.send()
user = request.user
email = user.email
context = {
"serviceName": "Pitch Creation",
"name": email,
}
message = render_to_string("narration/MR23.html", context)
text_content = strip_tags(message)
# create the email, and attach the HTML version as well.
msg = EmailMultiAlternatives(
"We are investigating the reason",
text_content,
settings.EMAIL_HOST_USER,
[email],
)
msg.attach_alternative(message, "text/html")
msg.send()
return JsonResponse({}, status=500)
def progress_sender(request):
# Simulating a long-running task
print("Reached Progress_sender")
userId = request.user.id
progress = progress_dict.get(userId)
if userId in progress_dict:
if progress is not None:
old_progress = old_progress_dict.get(userId)
while old_progress == progress:
# Add a small delay to reduce CPU usage
time.sleep(1)
progress = progress_dict.get(userId)
print("New Value send --->>", progress)
if progress == 0:
old_progress_dict[userId] = progress
data = {'status': 'error', 'progress': progress}
return JsonResponse(data)
if progress == 100:
old_progress_dict[userId] = progress
data = {'status': 'completed', 'progress': progress}
return JsonResponse(data)
old_progress_dict[userId] = progress
data = {'status': 'in_progress', 'progress': progress}
return JsonResponse(data)
data = {'status': 'no_update'}
return JsonResponse(data)
# # Get the progress value from the task (replace with your logic)
# progress = get_progress()
# # Check if the progress has reached 100% or not
# if progress >= 100:
# # If the progress is complete, return the final result
# data = {'status': 'completed', 'progress': 100, 'result': 'Task completed successfully'}
# else:
# # If the progress is not complete, return the progress value
# data = {'status': 'in_progress', 'progress': progress}
# return JsonResponse(data)
# progress_dict = {}
# old_progress_dict = {}
# except Exception as e:
# print("error is ", e)
# payment_intent_id = script_info.get("payment_intent_id")
# print("thisisgonnabeaRefund")
# 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)
# try:
# c = CurrencyRates()
# rate = c.get_rate("USD", "INR")
# except Exception as e:
# print("pich creation", 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)
# user = request.user
# email = user.email
# context = {
# "serviceName": "Pitch Creation",
# "name": email,
# }
# message = render_to_string("narration/MR28.html", context)
# text_content = strip_tags(message)
# msg = EmailMultiAlternatives(
# "Incovenience is regretted",
# text_content,
# settings.EMAIL_HOST_USER,
# [email],
# )
# msg.attach_alternative(message, "text/html")
# msg.send()
# user = request.user
# email = user.email
# context = {
# "serviceName": "Pitch Creation",
# "name": email,
# }
# message = render_to_string("narration/MR23.html", context)
# text_content = strip_tags(message)
# # create the email, and attach the HTML version as well.
# msg = EmailMultiAlternatives(
# "We are investigating the reason",
# text_content,
# settings.EMAIL_HOST_USER,
# [email],
# )
# msg.attach_alternative(message, "text/html")
# msg.send()
# return JsonResponse({}, status=500)
# class PostStreamView(View):
# def get(self, request):
# obj = ProgressNarration.objects.filter(user_id=request.user.id).last()
# if obj:
# print("Processing Chal Rahi hai", obj.progress)
# if obj.progress == 100:
# return JsonResponse({"status": "success", "progress": obj.progress}, status=200)
# if obj.progress == 0:
# return JsonResponse({"status": "Failed"}, status=500)
# else:
# return JsonResponse({"status": "pending", "progress": obj.progress}, status=202)
# else:
# return JsonResponse({"status": "Do nothing"}, status=203)
# def my_process(progress):
# progress_updated.send(sender=None, progress=progress)
# class ProgressConsumer(AsyncWebsocketConsumer):
# async def connect(self):
# await self.accept()
# await self.send(json.dumps({'progress': 0}))
# progress_updated.connect(self.progress_updated_handler)
# async def disconnect(self, close_code):
# progress_updated.disconnect(self.progress_updated_handler)
# async def progress_updated_handler(self, event):
# progress = event['progress']
# await self.send(json.dumps({'progress': progress}))
# class ProgressConsumer(WebsocketConsumer):
# def connect(self):
# self.room_name = "test"
# self.room_group_name = "test group"
# async_to_sync(self.channel_layers.group_send)(
# self.room_name, self.room_group_name
# )
# self.accept()
# self.send(text_data = json.dumps({"status":"finally Ran"}))
# def disconnect(self, close_code):
# pass
# def receive(self, text_data):
# pass
# def update_progress(self, event):
# progress = event['progress']
# await self.send(text_data=progress)
# def send_progress_to_client(sender, instance, **kwargs):
# if instance.user_id.id == kwargs['user_id']:
# print("######## Instance Found ###########")
# return instance.progress, instance.user_id.id
# else:
# return None
# SSE Yameen Progress Bar
# def event_stream(userId=None):
# while True:
# progress = progress_dict.get(userId)
# print("In stream, progress", progress)
# if progress is not None:
# print("In stream", old_progress_dict.get(userId), progress)
# if old_progress_dict.get(userId) != progress:
# if progress == 0:
# data = {'progress': progress}
# yield f"data: {json.dumps(data)}\n\n"
# time.sleep(2)
# print("data send ->>>>>", data)
# delet_user_progress(userId=userId)
# break
# elif progress == 100:
# data = {'progress': progress}
# yield f"data: {json.dumps(data)}\n\n"
# time.sleep(2)
# print("data send ->>>>>", data)
# break
# else:
# data = {'progress': progress}
# yield f"data: {json.dumps(data)}\n\n"
# time.sleep(2)
# print("data send ->>>>>", data)
# old_progress_dict[userId] = progress
# else:
# yield 'event: ping\ndata: {}\n\n'
# time.sleep(2)
def update_progress(userId, progress):
if userId in progress_dict:
progress_dict[userId] = progress
print(f"############# Progress Updated {progress} ###########")
time.sleep(3)
def update_old_progress(userId, progress):
if userId in old_progress_dict:
old_progress_dict[userId] = progress
print(f"############# OLD Progress Updated {progress} ###########")
time.sleep(3)
def reset_progress_dict(userId):
if userId in progress_dict and userId in old_progress_dict:
del progress_dict[userId]
del old_progress_dict[userId]
progress_dict[userId] = 20
old_progress_dict[userId] = 0
print("new value intialized",
progress_dict[userId], old_progress_dict[userId])
time.sleep(3)
else:
progress_dict[userId] = 20
old_progress_dict[userId] = 0
print("new value intialized",
progress_dict[userId], old_progress_dict[userId])
time.sleep(3)
def delet_user_progress(userId):
if userId in progress_dict and userId in old_progress_dict:
del progress_dict[userId]
del old_progress_dict[userId]
time.sleep(3)
# @csrf_exempt
# def progress_sender(request):
# user_id = request.user.id
# response = StreamingHttpResponse(event_stream(
# userId=user_id), content_type='text/event-stream')
# response['Cache-Control'] = 'no-cache'
# response['Connection'] = 'keep-alive'
# return response
# @receiver(post_save, sender=ProgressNarration)
# def progress_narration_post_save(sender, instance, **kwargs):
# print("######################### update ##################################")
# print(sender,instance)
# print(instance.progress)
# print(instance.user_id.id)
# progress, userId = send_progress_to_client(sender, instance, user_id=instance.user_id.id)
# if progress:
# print("@@@@@@@@@@@@@@@@@@@@@@@@ New Progress Updated dict #############################")
# print("progress", progress)
# progress_dict[userId] = progress
# update_model(request=None, progress = progress)
# channel_layer = get_channel_layer()
# async_to_sync(channel_layer.group_send)(
# 'progress_group', {'type': 'update_progress', 'progress': progress})
# def stream(request):
# oldProgress = 10
# while True:
# obj = ProgressNarration.objects.filter(user_id=request.user.id).last()
# if obj:
# print("::::::::OBJ:::::::::::")
# print(obj.progress)
# if oldProgress != obj.progress:
# message = {"progress": obj.progress}
# yield f"data: {json.dumps(message)}\n\n"
# print("@@@@@ Data Send @@@@@", obj.progress)
# time.sleep(2)
# oldProgress = obj.progress
# print("oldProgress",oldProgress)
# else:
# yield " " * 1024
# time.sleep(1)
# del oldProgress
# # # @csrf_exempt
# # # @require_GET
# class PostStreamView(View):
# def get(self, request):
# response = StreamingHttpResponse(stream(request))
# response['Content-Type'] = 'text/event-stream'
# response["Cache-Control"] = "no-cache"
# response["Connection"] = "keep-alive"
# response['X-Accel-Buffering'] = 'no'
# response['Timeout'] = '86400'
# return response
# global PROGRESS
# old_counter = PROGRESS
# PROGRESS += 1
# new_counter = PROGRESS
# if old_counter != new_counter:
# # print("progress", new_counter)
# # else:
# # # counter has not been updated
# # pass
# obj = MNFScriptDatabase.objects.filter(user_id=request.user.id, progress__gt=0)
# print("::::::::::::Processing Chal Rahi hai########################################################", obj)
# # if old_counter != new_counter:
# # print("progress", new_counter)
# # if obj.progress == 100:
# # return JsonResponse({"status": "success"}, status=200)
# # elif obj.progress == 0:
# # return JsonResponse({"status": "failed"}, status=500)
# # else:
# # return JsonResponse({"status": "pending", "progress": new_counter}, status=202)
# message = {"progress": new_counter}
# response.write(f"data: {json.dumps(message)}\n\n")
# return JsonResponse({"status": "pending", "progress": new_counter}, status=202)
# else:
# obj = MNFScriptDatabase.objects.filter(user_id=request.user.id, progress__gt=0).first()
# print("::::::::::::Processing Chal Rahi hai########################################################", obj.progress)
# return JsonResponse({"status": "pending", "progress": 20}, status=202)
# yameen on update progress:
# def send_progress_to_client(sender, instance, **kwargs):
# print("######## send_progress_to_client ###########")
# print(instance.user_id, kwargs['user_id'])
# if instance.user_id.id == kwargs['user_id']:
# print("######## Instance Found ###########")
# message = {"progress": instance.progress}
# print("PostStreamView.responses", PostStreamView.responses)
# for response in PostStreamView.responses:
# print("######## Message send ###########")
# print("response", response)
# response.queue.put(f"data: {json.dumps(message)}\n\n")
# class PostStreamView(View):
# responses = []
# def get(self, request):
# print("######## Responce Send ###########")
# response = StreamingHttpResponse(self.stream(request))
# response['Content-Type'] = 'text/event-stream'
# response['Cache-Control'] = 'no-cache'
# response['Connection'] = 'keep-alive'
# response.queue = Queue()
# self.responses.append(response)
# print("response", response)
# return response
# def stream(self, request):
# print("######## In Stream ###########")
# message = {"progress": 0}
# old_data = f"data: {json.dumps(message)}\n\n"
# while True:
# rlist, _, _ = select.select([self.responses[-1].queue.reader], [], [], 1)
# if rlist:
# data = self.responses[-1].queue.get()
# if data:
# old_data = data.encode()
# yield data.encode()
# else:
# pass
# @receiver(post_save, sender=ProgressNarration)
# def progress_narration_post_save(sender, instance, **kwargs):
# print("######################### update ##################################")
# print(sender,instance)
# print(instance.progress)
# print(instance.user_id.id)
# send_progress_to_client(sender, instance, user_id=instance.user_id.id)
from centralizePayment.views import callback, create_indent
def narrationCheckout1(request,script_id):
amount_charged = request.session["amount_charged"]
total_amount = request.session["total_amount"]
discount = request.session["discount"]
service_count=request.session["service_use"]
context = create_indent(request,"pitchdeck",script_id,service_count,"",total_amount,amount_charged,discount)
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check1.txt","a") as file01:
file01.write("narration checkout--------- -->" + str(context)+ "\n")
narration_instance = PitchVector.objects.get(id=script_id) # get object from your service database
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check1.txt","a") as file01:
file01.write("narration checkout--------- -->" + str(narration_instance)+ "\n")
# handle razor pay gateway →
if "orderId" in context:
narration_instance.order_id = context["orderId"]
narration_instance.cp_id = context["central_pay_id"]
narration_instance.save() # save central payment details in your database
# handle stripe gateway →
elif "client_secret" in context:
narration_instance.order_id = context["client_secret"]
narration_instance.cp_id = context["central_pay_id"]
narration_instance.save() # save central payment details in your database
# handle corporate profile →
elif "corporate" in context:
narration_instance.order_id = "corporate profile"
narration_instance.cp_id = "corporate profile"
narration_instance.save() # save central payment details in your database
# # run service in thread →
# # thread = Thread(target=run_subtitle, args=(payment_object,))
# # thread.start()
return render(request, "template.html", {"message":"bill added to the corporate profile"})
else:
# # handle errors →
return render(request, "template.html", {"message":"invalid request!"})
# handle success →
return render(request, "template.html", context)
def post(request):
response = request.POST.data # Get payment response
# call central payment callback function →
data = callback(response, request)
# handle success status →
if data["payment_status"] == "success":
# get object
payment_object =PitchVector.objects.get(cp_id=data["central_pay_id"])
payment_object.transaction_id = data["payment_id"]
payment_object.isPaid = True
payment_object.save() # save payment information
# run service in thread → demo
# thread = Thread(target=run_subtitle, args=(payment_object,))
# thread.start()
return render(request,"template.html",{"status": "Payment Done"})
# handle errors →
else:
render(request,"template.html",{"error_data": "Payment Failed"})
def narrationCheckout(request):
set_payment_token(request)
keyID = request.session["keyID"]
keySecret = request.session["keySecret"]
# num_pages = request.session["numPages"]
# print(funcname)
narration_instance = PitchVector.objects.get(script_id=request.session["script_id"])
if request.method == "POST":
# if num_pages > 5 :
total_amount = request.session["amount_charged"]
# script_id=request.session["script_id"]
# narrationCheckout1(request,script_id)
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
request.session["pay_with_wallet"] = "no"
if request.POST["pay_with_wallet"] == "yes":
request.session["pay_with_wallet"] = "yes"
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_charged"] = payable
total_amount = request.session["amount_charged"]
amtINR = round((float(total_amount) * rate), 2)
print("pitamtch:", total_amount, type(total_amount))
if request.session["indent_context"]:
client = razorpay.Client(auth=(keyID, keySecret))
if "orderId" in request.session["indent_context"]:
# client = razorpay.Client(auth=(keyID, keySecret))
request.session["payment_order_id"] = request.session["indent_context"]["orderId"]
request.session["central_payment_id"] = request.session["indent_context"]["central_pay_id"]
centralPayment_instance = CentralPayment.objects.get(id=request.session["indent_context"]["central_pay_id"])
pid = centralPayment_instance.order_id
amtINR = centralPayment_instance.amount_charged * rate
context = {
"pk": keyID,
"amtINR": amtINR,
"pid": pid,
"amount": centralPayment_instance.amount_charged,
}
return render(
request,
"Pitchdeck/checkoutN_RazorPay.html",
context
)
elif "client_secret" in request.session["indent_context"]:
request.session["payment_order_id"] = request.session["indent_context"]["client_secret"] # save central payment details in your database
request.session["central_payment_id"] = request.session["indent_context"]["central_pay_id"]
amtINR = centralPayment_instance.amount_charged * rate
context = {
"pk": STRIPE_PUB_KEY,
"total_amount": centralPayment_instance.amount_charged,
"secret_key":request.session["indent_context"]["client_secret"],
"amtINR": amtINR,
"STRIPE_PUBLISHABLE_KEY": STRIPE_PUB_KEY,
}
return render(request, "Pitchdeck/checkoutNnew.html", context)
elif "corporate" in request.session["indent_context"]:
script_id=request.session["script_id"]
numPages = request.session["numPages"]
actionline_language = request.session["actionline_language"]
actionline_script_language = request.session["actionline_script_language"]
dialogues_language = request.session["dialogues_language"]
dialogues_script_language = request.session["dialogues_script_language"]
script_title = request.session["script_title"]
script_file_path = request.session["script_file_path"]
request.session["payment_order_id"] = "corporate profile"
request.session["central_payment_id"] = "corporate profile"
return render(request, "Pitchdeck/PitchnarratedVideos.html", context)
else:
# return render(request, "payments/failed.html")
to_email = [request.user.email]
email_code = 'TN4'
sendmail(to_email=to_email , email_code=email_code )
return render(request, "payments/failed.html")
return render(request, "Pitchdeck/Pitchnarrate1.html")
@login_required(login_url="/")
def narrationcard(request):
if request.method == "POST":
# print("thisispayment_intent_id::", request.POST["payment_intent_id"])
# payment_intent_id = request.POST["payment_intent_id"]
# payment_method_id = request.POST["payment_method_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={}
# context = {
# "payment_intent_secret": pi.client_secret,
# "id": pi.id,
# "pk": STRIPE_PUB_KEY,
# }
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,
}
return render(request, "Pitchdeck/3dsecuredNarration.html", context)
# return render(request, "payments/paymentdone.html")
else:
return render(request, "Pitchdeck/Pitchnarrate1.html")
@login_required(login_url="/")
def paymentDoneN_RazorPay(request):
# keyID = request.session["keyID"]
# keySecret = request.session["keySecret"]
# razorpay_order_id = request.POST["razorpay_order_id"]
# print(razorpay_order_id)
if request.method == 'POST':
callback_payment = callback(request.POST, request)
if callback_payment['payment_status'] == 'success':
# print("manoj#45454")
# print(request.POST["razorpay_order_id"])
# 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:
# user = request.user
# email = user.email
# context = {
# "serviceName": "Pitch Creation",
# "name": email,
# }
# message = render_to_string("narration/MR24.html", context)
# text_content = strip_tags(message)
# # create the email, and attach the HTML version as well.
# msg = EmailMultiAlternatives(
# "Something really went wrong",
# text_content,
# settings.EMAIL_HOST_USER,
# [email],
# )
# msg.attach_alternative(message, "text/html")
# msg.send()
# to_email = [request.user.email]
# email_code = 'TN4'
# sendmail(to_email=to_email , email_code=email_code )
# return render(request, "payments/failed.html")
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
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()
else:
pass
total_amount = round(float((request.session["total_amount"]) * rate), 2)
# paydetail = client.payment.fetch(razorpay_payment_id)
# user_id = request.user
# payment_id = razorpay_payment_id
amount_charged = round(float((request.session["amount_charged"]) * rate), 2)
discount = round((total_amount - amount_charged), 2)
# gateway_fee = paydetail["fee"] / 100 # to convert from paise to rupees
# currency = paydetail["currency"]
# pay_method = paydetail["method"]
# services_used = "Pitchdeck"
# payment_status = "Success"
# payment_gateway = "RazorPay"
# number_of_pages = request.session["numPages"]
# script_in = MNFScriptDatabase.objects.get(
# script_id=request.session["script_id"]
# )
# with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
# file01.write('Detailed complete'+"\n")
# PaymentData.objects.create(
# user_id=user_id,
# payment_id=payment_id,
# services_used=services_used,
# discount=discount,
# number_of_pages=number_of_pages,
# total_amount=total_amount,
# amount_charged=amount_charged,
# gateway_fee=gateway_fee,
# script_info=script_in,
# currency=currency,
# pay_method=pay_method,
# payment_status=payment_status,
# payment_gateway=payment_gateway,
# )
# with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
# file01.write('PaymentData created'+"\n")
# #------------------------------------neha
# # update priviledged user razorpay
# if request.session["UpdatePriviledgedUser"]:
# with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
# file01.write('Reached Condition request.session["UpdatePriviledgedUser"]'+"\n")
# print("manoj#re343")
# if privilegedUser1.objects.filter(user=request.user).exists():
# with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
# file01.write('Privilegeduser hai'+"\n")
# obj = privilegedUser1.objects.get(user=request.user)
# else:
# with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
# file01.write('Privilegeduser Nahi hai'+"\n")
# obj = privilegedUser1()
# obj.user = request.user
# lasto = privilegedUser1.objects.last()
# obj.id = int(lasto.id) + 1
# obj.memberType = "normal"
# obj.is_active = "yes"
# obj.months = 1
# obj.chargeId = razorpay_order_id
# obj.transactionId = razorpay_payment_id
# obj.razorpaySign = razorpay_signature
# obj.status = payment_status
# obj.amount_captured = total_amount
# with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
# file01.write('Privilegeduser object '+str(obj)+"\n")
# obj.save()
# with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
# file01.write('Privilegeduser save hoa'+"\n")
# print("manoj*9998ha")
# del request.session["UpdatePriviledgedUser"]
# manoj
s=PitchVector()
# s.transaction_id = callback_payment["payment_id"] # save central payment details in your database
# s.isPaid = True # save central payment details in your database
# s.save()
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"]
s.save()
print("manoj454545454545")
print(amount_charged)
print(request.user.email)
current_site = get_current_site(request)
context2 = {
"domain": current_site.domain,
"serviceName": "Pitch Creation",
"name": request.user.email,
"amount": amount_charged,
"razorpay": True
}
# message = render_to_string("narration/MR25.html", context2)
# text_content = strip_tags(message)
# msg = EmailMultiAlternatives(
# "Every penny of yours is valuable",
# text_content,
# settings.EMAIL_HOST_USER,
# [request.user.email],
# )
# msg.attach_alternative(message, "text/html")
# msg.send()
to_email = [request.user.email]
email_code = 'TN3'
sendmail(to_email=to_email , email_code=email_code )
# manoj end
context = {
"script_id": request.session["script_id"],
"script_file_path": request.session["script_file_path"],
"restrict_to_five": "no",
}
return render(request, "Pitchdeck/PitchnarratedVideos.html", context)
# except:
else:
print("manoj1450")
print(traceback.format_exc())
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write('Privilegeduser in exeception aya hai'+str(ex)+"\n")
# subject = "Something really went wrong"
# from_email = settings.EMAIL_HOST_USER
# to = request.user.email
# context_2 = {
# "Name": request.user.email,
# "service_name": "Pitch Creation",
# }
# mnfnsendemail(
# to, subject, "payment/templates/payments/MR24.html", context_2, from_email
# )
to_email = [request.user.email]
email_code = 'TN4'
sendmail(to_email=to_email , email_code=email_code )
return render(request, "payments/failed.html")
else:
return HttpResponse("You don't have an access to use this.")
@login_required(login_url="/")
def paymentDoneN(request):
if request.method == "GET":
script_id = request.session["script_id"]
num_pages = request.session["numPages"]
actionline_language = request.session["actionline_language"]
actionline_script_language = request.session["actionline_script_language"]
dialogues_language = request.session["dialogues_language"]
dialogues_script_language = request.session["dialogues_script_language"]
document_name = request.session["document_name"]
script_title = request.session["script_title"]
total_amount= request.session["total_amount"]
amount_charged = request.session["amount_charged"]
discount = request.session["discount"]
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)
walls = Wallet.objects.get(user=request.user)
walls.balance = request.session["fbalance"]
walls.save()
else:
pass
s = MNFScriptDatabase()
p=PitchVector()
s.user_id = request.user
s.script_id = script_id
s.script_title = script_title
# s.script_file_path = script_file_path
p.payment_order_id = request.session["payment_order_id"] # save central payment details in your database
p.central_payment_id = request.session["central_payment_id"]
# s.payment_intent_id = payment_intent_id
s.save()
context = {
"script_id": script_id,
"script_title": script_title,
"num_pages":num_pages,
"actionline_language":actionline_language,
"actionline_script_language":actionline_script_language,
"dialogues_language":dialogues_language,
"dialogues_script_language":dialogues_script_language,
"total_amount": total_amount,
"amount_charged":amount_charged,
"discount":discount,
}
to_email = [request.user.email]
email_code = 'TN3'
sendmail(to_email=to_email , email_code=email_code )
# message = render_to_string("narration/MR25.html", context2)
# text_content = strip_tags(message)
# msg = EmailMultiAlternatives(
# "Every penny of yours is valuable",
# text_content,
# settings.EMAIL_HOST_USER,
# [request.user.email],
# )
# msg.attach_alternative(message, "text/html")
# msg.send()
# manoj end
return render(request, "Pitchdeck/PitchnarratedVideos.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": "Pitch Creation",
# }
# mnfnsendemail(
# to,
# subject,
# "payment/templates/payments/MR24.html",
# context_2,
# from_email,
# )
to_email = [request.user.email]
email_code = 'TN4'
context_2 = {
"Name": to_email,
"service_name": "Pitch Creation",
}
sendmail(to_email=to_email , email_code=email_code )
return render(request, "payments/failed.html")
@login_required(login_url="/")
def my_narrations(request):
# obj = MNFScriptDatabase.objects.filter(user_id=request.user).order_by("-date_at").exclude(connecting_id="")
if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user)
videos_path = []
pq= 0
projectIds = getUserprojectIds(blockchain_obj.user_id)
for i in range(len(projectIds) - 1, -1, -1):
print(projectIds[i])
key1= "MyNextFilm"
privatekey = blockchain_obj.privateKey
user_id =blockchain_obj.user_id
Project= projectIds[i]
private_Key = decryptionOfPrivate(privatekey)
status,getData = getNarrationData(private_Key.decode('utf-8'),user_id,Project)
if status == True:
data1 = getData[1]
converted_dict = eval(data1)
if converted_dict.get('MNFScriptDatabase1', {}).get('one_pager') == "True":
hash = converted_dict["MNFScriptDatabase1"]["Onepager_Script_fileHash"]
output_file_path = converted_dict["MNFScriptDatabase1"]["onepager_pdf_path"]
# Save the video to a local file with a progress bar
download_file_System(hash,output_file_path)
if converted_dict.get('MNFScriptDatabase1', {}).get('elevator_pitch') == "True":
hash = converted_dict["MNFScriptDatabase1"]["ElevatorPitch_Script_fileHash"]
output_file_path = converted_dict["MNFScriptDatabase1"]["elevator_pitch_video_path"]
download_file_System(hash,output_file_path)
if converted_dict.get('MNFScriptDatabase1', {}).get('linebyline') == "True":
hash = converted_dict["MNFScriptDatabase1"]["narration_Script_fileHash"]
output_file_path = converted_dict["MNFScriptDatabase1"]["line_by_line_narration_video_path"]
download_file_System(hash,output_file_path)
if converted_dict.get('MNFScriptDatabase1', {}).get('character_intro') == "True":
hash = converted_dict["MNFScriptDatabase1"]["Characterfile_Script_fileHash"]
output_file_path = converted_dict["MNFScriptDatabase1"]["character_intro_video_path"]
download_file_System(hash,output_file_path)
# Save the video to a local file with a progress bar
if converted_dict.get('MNFScriptDatabase1', {}).get('screenplay_analysis') == "True":
hash = converted_dict["MNFScriptDatabase1"]["Screenplayh_Script_fileHash"]
output_file_path = converted_dict["MNFScriptDatabase1"]["screenplay_analysis_video_path"]
# Save the video to a local file with a progress bar
download_file_System(hash,output_file_path)
# if converted_dict.get('MNFScriptDatabase1', {}).get('characterwise_narration') == "True":
# hash = converted_dict["MNFScriptDatabase1"]["Onepager_Script_fileHash"]
# output_file_path = converted_dict["MNFScriptDatabase1"]["onepager_pdf_path"]
# download_file_System(hash,output_file_path)
print(converted_dict["MNFScriptDatabase1"])
videos_path.append(converted_dict["MNFScriptDatabase1"])
converted_dict = converted_dict["MNFScriptDatabase1"]
pq += 1
else:
pass
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check1.txt","a") as file01:
file01.write("Blockchainfile: " + str(videos_path) + "\n")
return render(
request, "Pitchdeck/bundle_videos.html", {
"videos_path": videos_path, "pq": pq }
)
else:
obj = MNFScriptDatabase.objects.filter(
user_id=request.user).order_by("-date_at")
videos_path = obj
print("videos_path-??", videos_path)
pq = 0
for i in obj:
if i.elevator_pitch_video_path or i.onepager_pdf_path or i.screenplay_analysis_video_path or i.character_intro_video_path or i.line_by_line_narration_video_path or i.selected_characters or i.characterwise_video_path or i.characterwise_narration:
pq += 1
return render(
request, "Pitchdeck/bundle_videos.html", {
"videos_path": videos_path, "pq": pq}
) # many to many field or foreign key (characterwise_intro)
# pravesh-->
@login_required(login_url="/")
def view_demo_narrations(request, lang):
selected_option = lang
if selected_option is not None:
if selected_option in ["en", "hi", "mr", "fr"]:
context = {
"data": demo_files[selected_option],
"demolist": list(demo_files[selected_option])
}
return render(request, "Pitchdeck/viewDemoSampleScript.html", context)
context = {
"data": demo_files["en"],
"demolist": list(demo_files["en"])
}
t = loader.get_template('Pitchdeck/viewDemoSampleScript.html')
rendered_html = t.render({"context": context}, request)
# Extract HTML string using StringIO
html_string = StringIO()
html_string.write(rendered_html)
html_string.seek(0)
# with open('/home/user/mnf/project/MNF/Pitchdeck/yameen_html.html', 'w') as file:
# file.write(html_string.read())
# Process HTML string using BeautifulSoup
soup = BeautifulSoup(html_string, 'html.parser')
# text_elements = [element for element in soup.find_all(text=is_user_visible)]
# for i, text in enumerate(text_elements):
# print("text", text)
# trans_text = translate_comparison(text,"en", "it")
# text_elements[i].replace_with(trans_text)
modified_html = soup.prettify()
return HttpResponse(modified_html, content_type='text/html')
# return render(request, 'Pitchdeck/viewDemoSampleScript.html', context)
# def narration(request):
# sample=MNFScriptDatabase.objects.all()
# title_list = []
# path_list = []
# for i in sample:
# title_list.append(i.script_title)
# path_list.append(str(i.script_file_path.split('scripts/')[1]))
# return render(request, 'narration/narration.html',)
def delete_script(request, id):
MNFScriptDatabase.objects.get(id=id).delete()
return HttpResponseRedirect("/narration/narrations")
def demo(request):
return render(request, "narration/demo.html", {})
def Onepagerdemo(request):
return render(request, "Pitchdeck/Onepagerdemo.html", {})
def elevatorpitchdemo(request):
return render(request, "Pitchdeck/elevatorpitchdemo.html", {})
def screenplaydemo(request):
return render(request, "Pitchdeck/screenplaydemo.html", {})
def linebylinedemo(request):
return render(request, "Pitchdeck/linebylinedemo.html", {})
def Characterwisedemo(request):
return render(request, "Pitchdeck/Characterwisedemo.html", {})
def characterintrodemo(request):
return render(request, "Pitchdeck/characterintrodemo.html", {})
def narratescriptdemo(request):
return render(request, "Pitchdeck/narratescriptdemo.html", {})
def narrationroomdemo(request):
return render(request, "Pitchdeck/narrationroomdemo.html", {})
def char_function(script_id,character):
obj = Char_audio_class.char_audio(script_id, flag=True)
audio_data = obj.char_audioTTS()
obj_i =TestingC.Char_video_class(script_id)
characterdata = obj_i.char_data_written()
obj_i.new_logo()
for i in characterdata:
obj_i.first_intro_page(i)
objAV = audio_video.audio_video(audio_data,script_id,characterdata,True)
objAV.make_character_introduction(flag=True)
path = objAV.make_dialogue_clip(character)
return path
def uploadData(request):
if request.method == "POST":
# if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
# blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user)
# print("blockchain_obj.privateKe",blockchain_obj.privateKey)
# url = "http://127.0.0.1:8005/Write/onlyOwner"
# uploadFiles = "http://127.0.0.1:5000/upload"
# data ={
# "file": request.FILES['uploadfile']
# }
# # request.FILES.get
# response =requests.post(uploadFiles,files=data)
# hash = response.json()["hash"]
# Module= "narration"
# servicesName = "PitchdeckCreation"
# print(hash)
# data1 ={
# "user_id":blockchain_obj.user_id,
# "Module": Module,
# "Services": servicesName,
# "Data": request.POST.get('textdata') ,
# "File":[hash],
# "userPrivateKey":blockchain_obj.privateKey
# }
# response =requests.post(url,json=data1)
# # video_url = decryptionOfUrl(hash)
# # response = requests.get(video_url, stream=True)
MongoDBUrl = "mongodb+srv://mynextfilm:mnf123@cluster0.ojasb.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"
client = MongoClient(MongoDBUrl)
db = client.DB
users = db["auth_user"].find()
for user in users:
if "id" in user:
print(user["id"])
if UserCredentialsForBlockchain.objects.filter(user_id=user["id"]).exists():
print("user is alrady exists")
else:
accountDetail = walletCreation()
binaryToHex = accountDetail[1]
blockchain_obj = UserCredentialsForBlockchain()
blockchain_obj.user_id = user["id"]
blockchain_obj.privateKey = binaryToHex
blockchain_obj.publicKey = accountDetail[0]
blockchain_obj.save()
return render(request,"Pitchdeck/getPostdata.html")
return render(request,"Pitchdeck/getPostdata.html")
def getData(request):
if UserCredentialsForBlockchain.objects.filter(user=request.user).exists():
blockchain_obj = UserCredentialsForBlockchain.objects.get(user=request.user)
print("blockchain_obj.privateKe",blockchain_obj.privateKey)
Module= "narration"
servicesName = "PitchdeckCreation"
data ={
"private_key": blockchain_obj.privateKey,
"user_id": blockchain_obj.user_id,
"Module": Module,
"Services": servicesName,
"Project": 0,
}
response =requests.get(GET_OWNER,params=data)
getData = response.json()
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("form data>>>>>>>>>>2: " + str(getData) + "\n")
# data = getData["getData"]
data1 = getData.get("getData")[1]
hash = getData.get("getData")[2][0]
_url = decryptionOfUrl(hash)
with open("/home/user/mnf/project/MNF/Pitchdeck/error_check.txt","a") as file01:
file01.write("form data>>>>>>>>>>1: " + str(data1 ) + "\n")
response11 = requests.get(_url, stream=True)
# Check if the request was successful
if response11.status_code == 200:
# Get the total size of the video in bytes
total_size = int(response11.headers.get('content-length', 0))
# Replace 'video.mp4' with the desired file path and name
output_file_path = '/home/user/mnf/project/MNF/media/Blockchaainscripts/storage.pdf'
# Save the video to a local file with a progress bar
with open(output_file_path, 'wb') as video_file, tqdm(
desc=output_file_path,
total=total_size,
unit='B',
unit_scale=True,
unit_divisor=1024,
) as progress_bar:
for data in response11.iter_content(chunk_size=1024):
video_file.write(data)
progress_bar.update(len(data))
print("Video saved successfully.")
else:
print("Failed to download the video. Status code:", response11.status_code)
url ="http://115.245.192.138/media/Blockchaainscripts/storage.docx"
return render(request,"Pitchdeck/getPostdata.html", {"url": url, "data" :data1})
# from tqdm import tqdm
# def test(request):
# data = Pitch_creation()
# result = []
# progress = 0
# total = len(data)
# for item in tqdm(data, total=total):
# result.append(process_item(item))
# progress = int(100 * len(result) / total)
# tqdm.update(progress)
# return render(request, "Pitchdeck/testfile.html",{'result': result, 'progress': progress})
# def get_samescript_data(user, script_name):
# mnf_script = MNFScriptDatabase.objects.filter(user_id=user, script_name=script_name).first()
# if mnf_script.exists():
# for i in mnf:
# if i.elevator_pitch_video_path or i.onepager_pdf_path or i.screenplay_analysis_video_path or i.character_intro_video_path or i.line_by_line_narration_video_path or i.selected_characters or i.characterwise_video_path or i.characterwise_narration:
# pitchvector_data = PitchVector.objects.filter(user_id=user, id=mnf_script.id).first()
# return pitchvector_data
# return None