Sindbad~EG File Manager

Current Path : /home/numerotech/conference.numerotech.com/food_kit_scan_badges/core/library/
Upload File :
Current File : //home/numerotech/conference.numerotech.com/food_kit_scan_badges/core/library/helper.py

from core import app
from flask import url_for,render_template_string
from datetime import datetime, date, time, timedelta
import random
import math,random
import time
from num2words import num2words
from core.library.auth import Auth
import base64
import requests

import pyqrcode
import io
import png

import barcode 
from barcode import Code128
from barcode.writer import ImageWriter
from PIL import Image, ImageOps, ImageChops


#settime working as global variable but commented for easy identification of this variable using class name 
# global settime
# settime = 5

class Helper:

	# PaymentGatewayAppMasterID = 7 # IAGES23 razorpay
	# PaymentGatewayISTest      = 1 # testmode = 1

	DefaultCountryID          = 101 # for india country code
	AppType                   = "DELEGATE"
	
	def test_login(data):
		return "Virtual Conference - 1" 
	
	def footer_text():
		return "Virtual Conference - 1" 
	
	
	def date_diff(d1, d2):
		# fmt   = '%H:%M'
		d1      =   date(d1,'%Y, %m, %d')
		d2      =   date(d2,'%Y, %m, %d')           
		diff    =   str(d1) - str(d2)       
		# print(diff)
		return diff


	
	def random4digt():
		digits      = "123456789"
		otp_random  = ""
		for i in range(4) :
			random.seed(time.process_time())
			otp_random += digits[math.floor(random.random() * 9)]
		return otp_random

	def amountTowords(amount):
		words_in_amount = num2words(amount, lang='en_IN')
		return words_in_amount  

	def amountTodecimal(amount):
		num = int(amount)
		rs = f"{num:,}"
		return rs   


	def email_mask(email):
		if email:
			lo = email.find('@')
			if lo>0:
				mask_email =  email[0]+"*****"+email[lo-1:]
				return mask_email
		return email        

	def mobile_mask(mobile):
		if mobile:
			lo = len(mobile)
			if lo>0:
				mask =  mobile[:2]+"******"+mobile[lo-2:]
				return mask
		return mobile

	def formatINR(number):
		s, *d = str(number).partition(".")
		r = ",".join([s[x-2:x] for x in range(-3, -len(s), -2)][::-1] + [s[-3:]])
		return "".join([r] + d)
	
	def convert_html(data):
		temp = app.jinja_env.from_string("{{login_content|safe}}").render(**data)
		return render_template_string(temp,**data)

	def random_otp():
		digits      = "123456789"
		otp_random  = ""
		for i in range(4) :
			random.seed(time.process_time())
			otp_random += digits[math.floor(random.random() * 9)]
		return otp_random
		
	# Dec 23 ,2022 Siva To convert jinja tag to html 
	def convert_jinja_template(self,data1,data):
		temp = app.jinja_env.from_string(data1).render(data=data)
		return render_template_string(temp)	

	def base64encode(value):
		basevalue = value.encode("ascii")
		base64_bytes   = base64.b64encode(basevalue)
		return base64_bytes.decode("ascii")

	def convert_b64(encode_txt):
		sample_string = encode_txt
		sample_string_bytes = sample_string.encode("ascii")
		base64_bytes = base64.b64encode(sample_string_bytes)
		base64_string = base64_bytes.decode("ascii")
		return base64_string
	
	def split_delegate_ids(delegate_ids):
		if delegate_ids:
			delegate_id = delegate_ids.split(',')
			delegate_ids = len(delegate_id)
		else:
			delegate_ids = 0
			
		return delegate_ids		

	def merge_tags(text,values):
		for k, v in values.items():
			text = text.replace('*|'+k+'|*', v)
		return text

	def convert_html_for_mail_screen(data):
		temp = app.jinja_env.from_string("{{mail_content|safe}}").render(**data)
		return render_template_string(temp,**data)		
	
	def leftrightstrip(text):
		if text :
			ltext  = text.lstrip()
			rtext  = ltext.rstrip()
			striped_text  = rtext
			return striped_text
		else : 
			pass
			
	
	def getcurrenttimestamp():
		ct = datetime.now()
		ts = ct.timestamp()
		return ts 
	
	def ImageDecodeBase64(url):
		if url:
			bytes_string =  base64.b64encode(requests.get(url).content)
			aa = str(bytes_string, 'utf-8')
			return aa
		else :
			return " "	
			
	def getQRCode(delegate_no):
		c = pyqrcode.create(delegate_no)
		s = io.BytesIO()
		c.png(s,scale=6)
		encoded = base64.b64encode(s.getvalue()).decode("ascii")
		return encoded	

	def getQRCodeWithBg(delegate_no,color_code):
		c = pyqrcode.create(delegate_no)
		s = io.BytesIO()
		# c.png(s,scale=6) dcf2fb a2b2da
		c.png(s,scale=6,	background=color_code)
		# 
		encoded = base64.b64encode(s.getvalue()).decode("ascii")
		return encoded	
		
	def get_url_base64(url):
		return "data:image/jpg;base64," + base64.b64encode(requests.get(url).content).decode('ascii')	
		# return base64.b64encode(urlopen(url).read())
	
	def getcurrenttimestamp():
		ct = datetime.now()
		ts = ct.timestamp()
		return ts	

	def convert_html_for_badge_screen(badge_content,data):
# 		print("\nbadge_content -1 ",badge_content)
# 		print("\n\ndata ",data)
		temp = app.jinja_env.from_string(badge_content).render(**data)
		return render_template_string(temp,**data)

	def getQRCodeForBadge(scan_code_size,length_scale,qr_val,is_preview):
		demo_url 	= '/static/images/DEMO_QR_CODE.png'
		result 		= '' 
		img_src  	= None
		if is_preview == 1: 
			img_src = demo_url
		if qr_val:
			img_src  = f"data:image/png;base64,{Helper.getQRCodeWithBg(qr_val,'#fff')}"
			# img_src  = f"data:image/png;base64,{Helper.getQRCode(qr_val)}"

		if img_src:	
			result =f'<img style="width:{scan_code_size}{length_scale};height:{ scan_code_size}{length_scale};" src="{img_src}" >' 

		return result	

		
	def getBarCodeForBadge(scan_code_size,length_scale,bar_val,is_preview):
		demo_url 	= '/static/images/DEMO_QR_CODE.png'
		result 		= '' 
		img_src  	= None
		if is_preview == 1: 
			img_src = demo_url
		if bar_val:
			img_src  = f"data:image/png;base64,{Helper.getBARCode(bar_val)}"
			# img_src  = f"data:image/png;base64,{Helper.getQRCode(qr_val)}"

		if img_src:	
			result =f'<img style="height:{ scan_code_size}{length_scale};" src="{img_src}" >' 

		return result	



	def getQRCodeWithBg(delegate_no,color_code):
		c = pyqrcode.create(delegate_no)
		s = io.BytesIO()
		
		
		# c.png(s,scale=6) dcf2fb a2b2da
		if color_code:
			c.png(s,scale=6,	background=color_code)
		else:
			c.png(s,scale=6)
			
				# Customize options for the barcode
		options = {
			'write_text': False,    # Hide the text below the barcode
			'module_height': 8,     # Set the height of each module (barcode line)
			'module_width': 0.3,    # Set the width of each module (barcode line)
		}
		
		# Open the generated barcode image from BytesIO using Pillow
		barcode_image = Image.open(s)
		
		# Convert the image to RGBA mode (if not already in RGBA)
		barcode_image = barcode_image.convert("RGBA")
		
		# Create a mask for the white background
		background = Image.new("RGBA", barcode_image.size, (0, 0, 0, 0))
		diff = ImageChops.difference(barcode_image, background)
		diff = ImageOps.invert(diff.convert('L'))
		
		# Make the white background transparent
		barcode_image.putalpha(diff)
		
		# Save the barcode image to BytesIO
		output = io.BytesIO()
		barcode_image.save(output, format='PNG')
		
		# Encode the image as base64
		encoded_image = base64.b64encode(output.getvalue()).decode("ascii")
		
		return encoded_image
	
		
# 		encoded = base64.b64encode(s.getvalue()).decode("ascii")
# 		return encoded	
	# def getBARCode(delegate_no):
	# 	s = io.BytesIO()
	# 	options = {
	# 	    'write_text': False,  # This option hides the text below the barcode
	# 	     'module_height': 8,   # Set the height of each module (barcode line)
 #    		 'module_width': 0.3,   
 #    		 # 'background': 'transparent' # Set background color to transparent
	# 	}
	# 	Code128(f"delegate_no:04", writer=ImageWriter()).write(s, options)

	# 	encoded = base64.b64encode(s.getvalue()).decode("ascii")
	# 	return encoded	
	def getBARCode(delegate_no):
		s = io.BytesIO()
		
		# Customize options for the barcode
		options = {
			'write_text': False,    # Hide the text below the barcode
			'module_height': 8,     # Set the height of each module (barcode line)
			'module_width': 0.3,    # Set the width of each module (barcode line)
		}
		
		# Generate the barcode and write it to the BytesIO stream
		Code128(str(delegate_no).zfill(4), writer=ImageWriter()).write(s, options)
		
		# Open the generated barcode image from BytesIO using Pillow
		barcode_image = Image.open(s)
		
		# Convert the image to RGBA mode (if not already in RGBA)
		barcode_image = barcode_image.convert("RGBA")
		
		# Create a mask for the white background
		background = Image.new("RGBA", barcode_image.size, (0, 0, 0, 0))
		diff = ImageChops.difference(barcode_image, background)
		diff = ImageOps.invert(diff.convert('L'))
		
		# Make the white background transparent
		barcode_image.putalpha(diff)
		
		# Save the barcode image to BytesIO
		output = io.BytesIO()
		barcode_image.save(output, format='PNG')
		
		# Encode the image as base64
		encoded_image = base64.b64encode(output.getvalue()).decode("ascii")
		
		return encoded_image

	def getPhotoForBadge(photo_width,photo_height,length_scale,photo_val,is_preview):
		demo_url 	= '/static/images/empty_photo.png'
		result 		= '' 
		img_src  	= None
		if is_preview == 1: 
			img_src = demo_url
		if photo_val:
			img_src  = photo_val

		if img_src:	
			result =f'<img style="width:{photo_width}{length_scale};height:{ photo_height}{length_scale};-webkit-border-radius: 25% !important;border-radius: 25%;" src="{Helper.get_url_base64(img_src)}" >' 
			# result =f"<div  style=\"width: {photo_width}{length_scale};position: relative;margin-bottom: 2px;height: { photo_height}{length_scale};\"><div  style=\"position: absolute;background-image: url('{img_src}');background-repeat: no-repeat;text-align: center;background-size: cover;width: {photo_width}{length_scale};height: {photo_height}{length_scale};\"></div></div>"
			# result =f"<div  style=\"background-image: url('{img_src}');background-repeat: no-repeat;text-align: center;background-size: cover;width: {photo_width}{length_scale};height: {photo_height}{length_scale};\"></div>"

		return result		
	
	def getQRCodeForBadgeV1(scan_code_size,length_scale,qr_val,is_preview,bg_color,qr_color):
		demo_url 	= '/static/images/DEMO_QR_CODE.png'
		result 		= '' 
		img_src  	= None
		if is_preview == 1: 
			img_src = demo_url
		if qr_val:
			img_src  = f"data:image/png;base64,{Helper.getQRCodeWithBgV1(qr_val,bg_color,qr_color)}"
			# img_src  = f"data:image/png;base64,{Helper.getQRCode(qr_val)}"

		if img_src:	
			result =f'<img style="width:{scan_code_size}{length_scale};height:{ scan_code_size}{length_scale};" src="{img_src}" >' 

		return result		
	
	def getQRCodeWithBgV1(delegate_no,bg_color,qr_color):
		c = pyqrcode.create(delegate_no)
		s = io.BytesIO()

		qr_color  = qr_color if qr_color else "#000000"
		
		# c.png(s,scale=6) dcf2fb a2b2da
		if bg_color:
			c.png(s,scale=6, background=bg_color,module_color=qr_color)
			encoded = base64.b64encode(s.getvalue()).decode("ascii")
			return encoded
		else:
			c.png(s,scale=6,module_color=qr_color)
				# Customize options for the barcode
			options = {
				'write_text': False,    # Hide the text below the barcode
				'module_height': 8,     # Set the height of each module (barcode line)
				'module_width': 0.3,    # Set the width of each module (barcode line)
			}
			
			# Open the generated barcode image from BytesIO using Pillow
			barcode_image = Image.open(s)
			
			# Convert the image to RGBA mode (if not already in RGBA)
			barcode_image = barcode_image.convert("RGBA")
			
			# Create a mask for the white background
			background = Image.new("RGBA", barcode_image.size, (0, 0, 0, 0))
			diff = ImageChops.difference(barcode_image, background)
			diff = ImageOps.invert(diff.convert('L'))
			
			# Make the white background transparent
			barcode_image.putalpha(diff)
			
			# Save the barcode image to BytesIO
			output = io.BytesIO()
			barcode_image.save(output, format='PNG')
			
			# Encode the image as base64
			encoded_image = base64.b64encode(output.getvalue()).decode("ascii")
		
		return encoded_image	
app.jinja_env.globals.update(Helper=Helper) 

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists