import streamlit as st
import os
from PyPDF2 import PdfReader
import docx
from langchain.chat_models import ChatOpenAI
from langchain.vectorstores import Qdrant
import random
from datetime import datetime
from langchain import PromptTemplate
from langchain.chains import RetrievalQA
import string
from qdrant_client import QdrantClient
from dotenv import load_dotenv
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from streamlit_chat import message
from langchain.callbacks import get_openai_callback
from langchain.docstore.document import Document
openapi_key = st.secrets["OPENAI_API_KEY"]
qdrant_url = st.secrets["QDRANT_URL"]
qdrant_api_key = st.secrets["QDRANT_API_KEY"]
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")

# "with" notation
def main():
    load_dotenv()
    st.set_page_config(page_title="Q/A with your file")
    st.header("Retrieval QA Chain")

    if "conversation" not in st.session_state:
        st.session_state.conversation = None
    if "chat_history" not in st.session_state:
        st.session_state.chat_history = []
    if "processComplete" not in st.session_state:
        st.session_state.processComplete = None

    with st.sidebar:
        uploaded_files =  st.file_uploader("Upload your file",type=['pdf'],accept_multiple_files=True)
        openai_api_key = openapi_key
        # openai_api_key = st.text_input("OpenAI API Key", key=openapi_key , type="password")
        process = st.button("Process")
    if process:
        if not openai_api_key:
            st.info("Please add your OpenAI API key to continue.")
            st.stop()

        text_chunks_list = []
        for uploaded_file in uploaded_files:
            file_name = uploaded_file.name
            file_text = get_files_text(uploaded_file)
            # get text chunks
            text_chunks = get_text_chunks(file_text, file_name )
            text_chunks_list.extend(text_chunks)
            # create vetore stores
        curr_date = str(datetime.now())
        collection_name = "".join(random.choices(string.ascii_letters, k=4)) + curr_date.split('.')[0].replace(':', '-').replace(" ", 'T')
        vectorestore = get_vectorstore(text_chunks_list, collection_name)
        st.write("Vectore Store Created...")
        # create qa chain
        num_chunks = 4
        st.session_state.conversation = get_qa_chain(vectorestore,num_chunks) #for openAI

        st.session_state.processComplete = True

    if  st.session_state.processComplete == True:
        user_question = st.chat_input("Ask Question about your files.")
        if user_question:
            handel_userinput(user_question)

# Function to get the input file and read the text from it.
def get_files_text(uploaded_file):
    text = ""
    split_tup = os.path.splitext(uploaded_file.name)
    file_extension = split_tup[1]
    if file_extension == ".pdf":
        text += get_pdf_text(uploaded_file)
    elif file_extension == ".docx":
        text += get_docx_text(uploaded_file)
    else:
        pass
    return text

# Function to read PDF Files
def get_pdf_text(pdf):
    pdf_reader = PdfReader(pdf)
    text = ""
    for page in pdf_reader.pages:
        text += page.extract_text()
    return text

def get_docx_text(file):
    doc = docx.Document(file)
    allText = []
    for docpara in doc.paragraphs:
        allText.append(docpara.text)
    text = ' '.join(allText)
    return text

def get_text_chunks(text, filename):
    # spilit ito chuncks
    text_splitter = CharacterTextSplitter(
        separator="\n",
        chunk_size=80,
        chunk_overlap=20,
        length_function=len
    )
    chunks = text_splitter.split_text(text)
    doc_list = []
    for chunk in chunks:
        metadata = {"source": filename}
        doc_string = Document(page_content=chunk, metadata=metadata)
        doc_list.append(doc_string)
    return doc_list

def get_vectorstore(text_chunks, COLLECTION_NAME):
    # Using the hugging face embedding models
    try:
        # creating the Vectore Store using Facebook AI Semantic search
        knowledge_base = Qdrant.from_documents(
            documents = text_chunks,
            embedding = embeddings,
            url=qdrant_url,
            prefer_grpc=True,
            api_key=qdrant_api_key,
            collection_name=COLLECTION_NAME,
        )
    except Exception as e:
        st.write(f"Error: {e}")
    return knowledge_base

def get_qa_chain(vectorstore,num_chunks):
    # prompt_template = """
    # You are trained to extract Answer from the given Context and Question. Then, precise the Answer in less than 20 words. If the Answer is not found in the Context, then return "N/A", otherwise return the precise Answer.
    # Context: {context}
    # Question: {question}"""
    # mprompt_url = PromptTemplate(
    #     template=prompt_template, input_variables=["context", "question"], validate_template=False)
    # chain_type_kwargs = {"prompt": mprompt_url}

    # qa = RetrievalQA.from_chain_type(llm=ChatOpenAI(model = "gpt-3.5-turbo"), chain_type="stuff",
    #                             retriever=vectorstore.as_retriever(search_type="similarity",
    #                                                         search_kwargs={"k": num_chunks}), chain_type_kwargs=chain_type_kwargs, return_source_documents=True)
    qa = RetrievalQA.from_chain_type(llm=ChatOpenAI(model = "gpt-3.5-turbo"), chain_type="stuff",
                                retriever=vectorstore.as_retriever(search_type="similarity",
                                                            search_kwargs={"k": num_chunks}),  return_source_documents=True)
    return qa

def handel_userinput(user_question):
    with st.spinner('Generating response...'):
        result = st.session_state.conversation({"query": user_question})
        response = result['result']
        source = result['source_documents'][0].metadata['source']
    st.session_state.chat_history.append(user_question)
    st.session_state.chat_history.append(f"{response} \n Source Document: {source}")

    # Layout of input/response containers
    response_container = st.container()

    with response_container:
        for i, messages in enumerate(st.session_state.chat_history):
            if i % 2 == 0:
                message(messages, is_user=True, key=str(i))
            else:
                message(messages, key=str(i))

if __name__ == '__main__':
    main()

Lecture#32 QA chain chatbot code/Lecture#32 QA chain chatbot code/app.py


import torch
import numpy as np
from tutils import trans_args, trans_init, dump_yaml, tfilename, save_script
import argparse
from utils.tester_ssl import Tester
from models.network_emb_study import UNet_Pretrained

def dump_labels_from_ssl(logger, config, model):
    tester = Tester(logger, config)
    tester.test(model, dump_label=True)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--config", default="configs/ssl/ssl.yaml")
    parser.add_argument("--experiment", default="dump_labels")
    args = trans_args(parser)
    logger, config = trans_init(args, file=__file__)

    ckpt = config['training']['ckpt'] = "/home1/quanquan/code/landmark/code/runs/ssl/ssl/debug2/ckpt/best_model_epoch_890.pth"
    model = UNet_Pretrained(3, emb_len=config['training']['emb_len'], non_local=config['training']['non_local'])
    state_dict = torch.load(ckpt)
    model.load_state_dict(state_dict)
    model.cuda()

    dump_labels_from_ssl(logger, config, model)
    dump_yaml(logger, config)


import json
from itertools import accumulate

class FixedWidthSpec:
    """
    Spec class representing a FixedWidthSpec. Accepts a dictionary with the fixed file metadata specification:
    {
       "ColumnNames":"f1, f2, f3, f4, f5, f6, f7, f8, f9, f10",
       "Offsets":"3,12,3,2,13,1,10,13,3,13",
       "InputEncoding":"windows-1252",
       "IncludeHeader":"True",
       "OutputEncoding":"utf-8"
    }
    """
    def __init__(self, config: dict):
        if any([x not in config.keys() for x in
                ("ColumnNames", "Offsets", "InputEncoding", "IncludeHeader", "OutputEncoding")]):
            raise ValueError("Wrong spec provided")

        self.__dict__ = config
        self.Offsets = [0] + [int(x) for x in self.Offsets.split(',')]
        self.ColumnNames = self.ColumnNames.split(',')
        self.ColumnNames = [x.lstrip().rstrip() for x in self.ColumnNames]
        self.IncludeHeader = True if self.IncludeHeader == 'True' else False

class FixedWidthParser:
    """
    FixedWidthParser parses a fixed input file and write it to a delimiter file according to a FixedWidthSpec.
    """
    def __init__(self, spec: FixedWidthSpec, delimiter: str):
        self.spec = spec
        self.delimiter = delimiter

    def _parse_line(self, line, idx) -> str:
        """Parse one fixes input line according to a list of offset tuples"""
        return [line.rstrip()[l:h] for l, h in idx]

    def _parse_file(self, the_input, the_output, idx: list, spec: FixedWidthSpec) -> None:
        """Parses a file line by line and writes the converted delimited file"""
        if spec.IncludeHeader:
            the_output.write(self.delimiter.join(spec.ColumnNames) + "\n")

        for line in the_input:
            parsed_line = self._parse_line(line, idx)
            the_output.write(self.delimiter.join(parsed_line) + "\n")

    def parse(self, input_file, output_file) -> None:
        """Main parse method"""
        acum = list(accumulate(self.spec.Offsets))
        idx = list(zip(acum[:-1], acum[1:]))

        with open(input_file, "r", encoding=self.spec.InputEncoding) as the_input, \
                open(output_file, 'w', encoding=self.spec.OutputEncoding) as the_output:
            self._parse_file(the_input, the_output, idx, self.spec)


#!/usr/bin/env python
'''Script to pull latest Firefox version string from Mozilla'''

import re

from bs4 import BeautifulSoup
import requests

def is_firefox(items):
    '''Check if list of li tags refers to Firefox'''
    for item in items:
        # One of the list items in the div contains the GUID
        if re.search('ec8030f7-c20a-464f-9b0e-13a3a9e97384', item.get_text()):
            return True

    return False

def get_versions(items):
    '''Get list of version from li tags referring to Firefox'''
    for item in items:
        # The list item with the versions starts with "Versions:"
        if re.match('Versions:', item.get_text()):
            versions_str = item.code.get_text()
            return [v.strip() for v in versions_str.split(',')]

def main():
    '''Main logic'''
    req = requests.get(
        'https://addons.mozilla.org/en-US/firefox/pages/appversions/')
    soup = BeautifulSoup(req.content, 'html.parser')

    # Blocks with valid versions are divs of class appversion prose
    version_sets = [s for s in soup.find_all('div', 'appversion prose')]

    for ver_set in version_sets:
        items = ver_set('li')
        if is_firefox(items):
            version_list = get_versions(items)

    # Versions ordered oldest to newest
    version_list.reverse()
    for version in version_list:
        # Match newest version without prerelease characters in string
        if re.match(r'^[0-9\.]+$', version):
            if int(version.split('.')[0]) < 57:
                # Get the latest release lest than 57
                print(version)
                return

    raise RuntimeError('No version strings found')

if __name__ == '__main__':
    main()


from games import TicTacToe
from algorithms import MCTS
import numpy as np
import tqdm

## 10000 searches per move is pretty strong. Vary the quality of
## decision making by changing number of searches from 10000 to
## something else. Or, try changing the board size and playing a game.

# Create environment
env = TicTacToe(3)
# Reset
obs = env.reset()
# whose turn? True if you want to play first
human_play = True
player = 'x'
other_player = 'o'
while True:
	# Print board and check if game over
	env.print_board()
	if env.won('x'):
		print('Game over, x wins')
		break
	if env.won('o'):
		print('Game over, o wins')
		break
	if env.draw():
		print('Draw')
		break
	if human_play:
		# ask for action
		i, j = map(int, input('Enter position:').split())
		action = (i, j)
	else:
		# MCTS
		mcts = MCTS(env, other_player)
		print('Thinking ...')
		for traversal_num in tqdm.tqdm(range(10000)): mcts.search(obs)
		# Ask for best action from obs
		# Uncertainty constant = 0
		mcts.reset()
		action = mcts.best_action(mcts.tree.root, 0)
	# step
	next_obs, r, _, _ = env.step(action, player=player if human_play \
		else other_player)
	obs = next_obs
	# next turn
	human_play = not human_play


import shutil
import os
import webbrowser
from catalog.models import *
from submission_grader.models import *
import zipfile

# CURRENTLY: This is just a test script to see just how we
# can actually find locations of the testcases and stuff.

# get test case
test_case = TestCase.objects.all()[0]
test_case_location = test_case.get_abs_path()
print(test_case_location)

# get submission
submission = Submission.objects.all()[0]
submission_location = submission.files.path
print(submission_location)

# # create new dir
new_dir_name = "compiler/" + str(submission)
if not os.path.isdir(new_dir_name):
	os.mkdir(new_dir_name)

# # move to new dir && create gradle locations.
os.chdir(new_dir_name)
os.system("gradle init")
# We need to edit the build file, so that it has the correct dependencies.
with open('./build.gradle', 'w') as build_file:
	build_file.write("apply plugin: 'java'\n")
	build_file.write("repositories {\nmavenCentral()\n}\n")
	build_file.write("dependencies {\ntestCompile group: 'junit', name: 'junit', version: '4+'\n}")

os.mkdir("src/")
os.mkdir("src/main/")
os.mkdir("src/test/")
shutil.copy(submission_location, "./src/main/")
shutil.copy(test_case_location, "./src/test/")

# Unzip these bad bois
zip_file = zipfile.ZipFile("./src/main/" + submission.file_name(), 'r')
zip_file.extractall('./src/main/')
zip_file = zipfile.ZipFile("./src/test/" + test_case.file_name(), 'r')
zip_file.extractall('./src/test/')
zip_file.close()

#...let's run this son of a gun.
print(os.listdir('.'))
os.system("gradle build")
os.chdir("/")
os.system("gradle build")


import util
import sqlite3
FILE_NAME = 'yuja.sqlite'

def main() -> None:
    connection = sqlite3.connect(FILE_NAME)
    cursor = connection.cursor()
    s = util.csv_streams().merge_stream

    annotations = {
        f: {int: "integer", str: "string"}.get(t, '')
        for f, t in util.csv_struct.__annotations__.items()
    }
    annotations['video_id'] += ' primary key'
    annotations['creation'] = 'timestamp'
    annotations['modification'] = 'timestamp'

    annotation_keys = list(annotations.keys())
    create_names = [f'{f} {t}' for f, t in annotations.items()]
    cursor.execute("DROP TABLE yuja")
    cursor.execute(f'CREATE TABLE IF NOT EXISTS yuja ({",".join(create_names)})')
    cursor.execute('''
    CREATE VIEW IF NOT EXISTS url_view as
    select video_id,title,
    (
        "https://"||
        coalesce(nullif(institution,""),"my")||
        ".yuja.com/P/Data/VideoSource?video=/P/VideoCaptures/a/1/"||
        broadcast_id||
        "/"||
        auth_code||
        "&videoPID="||
        video_id||
        "&mp4Only=false"
    ) as url
    from yuja
    ''')
    cursor.execute('''
    CREATE VIEW IF NOT EXISTS "video_id_gaps" as
    select coalesce(lag(video_id) over (order by video_id),-1)+1 as start_id,video_id as stop_id
    from yuja
    order by stop_id-start_id desc
    ''')
    insert_records = f"REPLACE INTO yuja({','.join(annotation_keys)}) VALUES ({','.join(f':{n}' for n in annotation_keys)})"
    cursor.executemany(insert_records, s)
    connection.commit()
    connection.close()

if __name__ == '__main__':
    main()


#https://www.kaggle.com/benhamner/popular-datasets-over-time

# --------------------
# Importando librerias
# --------------------

# Keras model module
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.utils import np_utils
# MNIST data
from keras.datasets import mnist
# Plotter
from matplotlib import pyplot

# ----------------------
# Cargando dataset MNIST
# ----------------------

# input image dimensions
img_rows, img_cols = 28, 28

# /Applications/Python 3.6/Install Certificates.command
# conda update openssl
# Load pre-shuffled MNIST data into train and test sets
(X_train, y_train), (X_test, y_test) = mnist.load_data()

# Plotting first sample of X_train
pyplot.imshow(X_train[0], cmap='gray')

print(X_train.shape)
print(X_test.shape)

# -------------------------------------------
# Preprocesando la data de entrada para Keras
# -------------------------------------------
# Reshape input data
X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1)
X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)

print(X_train.shape)
print(X_test.shape)

print ("Data sin normalizar:\n", X_train[0][14])

# Normalizando la data --> decimal y el el rango de 0-1
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
print ("Data Normalizada:\n", X_train[0][14])

# ----------------------------------------
# Categorizando las salidas: Clases de 0-9
# ----------------------------------------

# Preprocess class labels
# Convert 1-dimensional class arrays to 10-dimensional class matrices
y_train_cat = np_utils.to_categorical(y_train, 10)
y_test_cat = np_utils.to_categorical(y_test, 10)

print (y_train[0], " categorizado es:\n ", y_train_cat[0])

# --------------------------------------
# Definiendo la Arquitectura del modelo
# --------------------------------------

#Declare Sequential model
model = Sequential()

# CNN input layer
model.add(Conv2D(filters=32, kernel_size=(3, 3), padding="same", strides=(1,1), input_shape = (img_rows, img_cols, 1)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))

# Adding more CNN layers
model.add(Conv2D(filters=64, kernel_size=(3, 3), padding="valid", strides=(1,1)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))

# Adding more CNN layers
model.add(Conv2D(filters=128, kernel_size=(3, 3), padding="valid", strides=(1,1)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))

# Fully connected Dense layers
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dense(10, activation='softmax'))

model.summary()

# --------------------------------
# Compilando y entenando el modelo
# --------------------------------

# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

# Fit Keras model
model.fit(X_train, y_train_cat, batch_size=128, epochs=5, verbose=1)

# -------------------
# Evaluando el modelo
# -------------------

# Evaluate Keras model
print('\nEvaluando el modelo:')

score = model.evaluate(X_test, y_test_cat, verbose=1)
print('\nTest loss:', score[0])
print('Test accuracy:', score[1])

# ----------------------------------------------------
# Ejercicio: Predecir una imagen creada por el usuario
# ----------------------------------------------------
from keras.preprocessing import image
test_image_path = './images/numberTest2.jpg'
test_image_original = image.load_img(test_image_path)
pyplot.imshow(test_image_original)
pyplot.show()

test_image = image.load_img(test_image_path,target_size = (28, 28), grayscale = True)
test_image = image.img_to_array(test_image)
test_image = test_image.reshape(1,28,28,1)
test_image = test_image.astype('float32')
test_image /= 255

predicions = model.predict(test_image)
print("\nPredictions:\n", predicions)

predicion_class = model.predict_classes(test_image)
print("\nPredictions Class: ", predicion_class)


import time
import sys
import random

from css_matrix_completion.errors.errors import rmse_omega, nmae_omega, rmse, snr

from css_matrix_completion.css import uniform
from css_matrix_completion.cssmc import CSSMC, CSSMC_N
from css_matrix_completion.mc.soft_impute import SoftImpute, SoftImpute_N
from css_matrix_completion.mc.nn_completion import NuclearNormMin
from css_matrix_completion.transform import cx, cx_torch
from utils.data_generation import create_rank_k_dataset
from utils.linear_algebra import matrix_coherence
from utils.log import log
import numpy as np
from functools import wraps
from fancyimpute import SoftImpute, IterativeSVD, MatrixFactorization

n_rows = 300
n_cols = 1000

ranks = [5, 10]

n_trials = 20

c_rates = [i * 0.1 for i in range(1, 10)]
c_rates = [0.1, 0.2, 0.3]
# missing_rates = [i * 0.1 for i in range(1, 10)]
missing_rates = [0.8]
lib = 'numpy'

log_name = 'synthetic_benchmark_all'
def evaluate(M_filled, M, missing_mask):
    rmse_omega_ = rmse_omega(M_filled, M, missing_mask, numlib=lib)
    nmae_omega_ = nmae_omega(M_filled, M, missing_mask, numlib=lib)
    rmse_ = rmse(M_filled, M, numlib=lib)
    success = int(rmse_ <= 10 ** -2)
    snr_ = snr(M_filled, M, numlib=lib)
    return [rmse_omega_, nmae_omega_, success, snr_]

for trial in range(20):
    print(f'Starting trial {trial}')
    for fraction_missing in missing_rates:
        for rank in ranks:
            print(f'Rank {rank}')
            M, M_incomplete, omega, ok_mask = create_rank_k_dataset(n_rows=n_rows, n_cols=n_cols, k=rank,
                                                                    gaussian=True,
                                                                    fraction_missing=fraction_missing,
                                                                    noise=0.3)
            M_incomplete_tmp = np.copy(M_incomplete)
            M_incomplete_tmp[~ok_mask] = 0
            lambda_max = SoftImpute_N._max_singular_value(
                M_incomplete_tmp)

            missing_mask = ~ok_mask
            base_log_data = [trial, n_rows, n_cols, rank, fraction_missing]
            for c_rate in c_rates:
                n_selected_cols = int(c_rate * n_cols)
                solver = CSSMC_N(col_number=n_selected_cols, solver=NuclearNormMin, col_select=uniform,
                                 transform=cx_torch,
                                 fill_method='zero')
                solver.get_cols_matrix(M_incomplete, np.isnan(M_incomplete))
                C = M[:, solver.cols_indices]
                mc = matrix_coherence(C)
                start = time.perf_counter()
                M_filled = solver.fit_transform(M_incomplete)
                elapsed_time = time.perf_counter() - start
                print(elapsed_time)
                try:
                    metrics = evaluate(M_filled, M, missing_mask)
                except:
                    metrics = evaluate(M_filled.numpy(), M, missing_mask)
                print(metrics)
                log_data = base_log_data + [c_rate, elapsed_time, mc, f'CSNN_{c_rate}'] + metrics
                log(log_data, file_name=log_name)

            # max_ranks = [3, 5, 10, 15, 20]
            # for alg in [MatrixFactorization, IterativeSVD]:
            #     if isinstance(alg(),  MatrixFactorization):
            #         True
            #
            #     for r in max_ranks:
            #         solver = alg(rank=r, verbose=False)
            #         start = time.perf_counter()
            #         M_filled = solver.fit_transform(M_incomplete)
            #         elapsed_time = time.perf_counter() - start
            #         metrics = evaluate(M_filled, M, missing_mask)
            #         log_data = base_log_data + [c_rate, elapsed_time, mc, alg.__name__] + metrics
            #         log(log_data, file_name=log_name)

            # lambda_grid = np.linspace(0.1, lambda_max - 1, 10)
            # for alg in [SoftImpute_N]:
            #     for lam in lambda_grid:
            #         solver = alg(lambda_=lam)
            #         start = time.perf_counter()
            #         M_filled = solver.fit_transform(M_incomplete, missing_mask=~ok_mask)
            #         elapsed_time = time.perf_counter() - start
            #         metrics = evaluate(M_filled, M, missing_mask)
            #         log_data = base_log_data + [c_rate, elapsed_time, mc, 'PGD'] + metrics
            #         log(log_data, file_name=log_name)

            solver = NuclearNormMin(M_incomplete)
            start = time.perf_counter()
            M_filled = solver.fit_transform(M_incomplete, missing_mask)
            elapsed_time = time.perf_counter() - start
            rmse_omega_ = rmse_omega(M_filled, M, missing_mask, numlib=lib)
            nmae_omega_ = nmae_omega(M_filled, M, missing_mask, numlib=lib)
            rmse_ = rmse(M_filled, M, numlib=lib)
            print(rmse_, elapsed_time)
            snr_ = snr(M_filled, M, numlib=lib)
            success = int(rmse_ <= 10 ** -2)
            log_data = base_log_data + [1, elapsed_time, rmse_, rmse_omega_,
                                        nmae_omega_, snr_, success, mc, 'NN']

            log(log_data, file_name=log_name)

print('Finished benchmark')


import os
import sys
from deeplake.constants import KB, MB
from deeplake.util.exceptions import (
    SampleAppendError,
    TensorMetaMissingRequiredValue,
    TensorMetaMutuallyExclusiveKeysError,
    UnsupportedCompressionError,
)
import pytest
from deeplake.core.tensor import Tensor
from deeplake.tests.common import TENSOR_KEY, assert_images_close
import numpy as np

import deeplake
from deeplake.core.dataset import Dataset

def _populate_compressed_samples(tensor: Tensor, cat_path, flower_path, count=1):
    for _ in range(count):
        tensor.append(deeplake.read(cat_path))
        tensor.append(deeplake.read(flower_path))
        tensor.append(np.ones((100, 100, 4), dtype="uint8"))
        tensor.append(
            np.ones((100, 100, 4), dtype=int).tolist()
        )  # test safe downcasting of python scalars

        tensor.extend(
            [
                deeplake.read(flower_path),
                deeplake.read(cat_path),
            ]
        )

@pytest.mark.slow
def test_populate_compressed_samples(local_ds, cat_path, flower_path):
    images = local_ds.create_tensor(
        TENSOR_KEY,
        htype="image",
        sample_compression="png",
        max_chunk_size=2 * MB,
        tiling_threshold=1 * MB,
    )

    assert images.meta.dtype == None
    assert images.meta.sample_compression == "png"

    _populate_compressed_samples(images, cat_path, flower_path)

    expected_shapes = [
        (900, 900, 3),
        (513, 464, 4),
        (100, 100, 4),
        (100, 100, 4),
        (513, 464, 4),
        (900, 900, 3),
    ]

    assert len(images) == 6

    for img, exp_shape in zip(images, expected_shapes):
        arr = img.numpy()
        assert arr.shape == exp_shape
        assert arr.dtype == "uint8"

    assert images.shape == (6, None, None, None)
    assert images.shape_interval.lower == (6, 100, 100, 3)
    assert images.shape_interval.upper == (6, 900, 900, 4)

@pytest.mark.slow
def test_iterate_compressed_samples(local_ds, cat_path, flower_path):
    images = local_ds.create_tensor(TENSOR_KEY, htype="image", sample_compression="png")

    assert images.meta.dtype == None
    assert images.meta.sample_compression == "png"

    _populate_compressed_samples(images, cat_path, flower_path)

    expected_shapes = [
        (900, 900, 3),
        (513, 464, 4),
        (100, 100, 4),
        (100, 100, 4),
        (513, 464, 4),
        (900, 900, 3),
    ]

    assert len(images) == len(expected_shapes)
    for image, expected_shape in zip(images, expected_shapes):
        x = image.numpy()

        assert (
            type(x) == np.ndarray
        ), "Check is necessary in case a `PIL` object is returned instead of an array."
        assert x.shape == expected_shape
        assert x.dtype == "uint8"

def test_uncompressed(local_ds):
    images = local_ds.create_tensor(TENSOR_KEY, sample_compression=None)

    images.append(np.ones((100, 100, 100)))
    images.extend(np.ones((3, 101, 2, 1)))
    local_ds.clear_cache()
    np.testing.assert_array_equal(images[0].numpy(), np.ones((100, 100, 100)))
    np.testing.assert_array_equal(images[1:4].numpy(), np.ones((3, 101, 2, 1)))

def test_byte_sample_compression(memory_ds):
    with memory_ds as ds:
        ds.create_tensor("xyz", sample_compression="lz4")
        for i in range(10):
            ds.xyz.append(i * np.ones((100, 100, 100)))

    for i in range(10):
        np.testing.assert_array_equal(ds.xyz[i].numpy(), i * np.ones((100, 100, 100)))

@pytest.mark.xfail(raises=SampleAppendError, strict=True)
@pytest.mark.parametrize(
    "bad_shape",
    [
        # raises OSError: cannot write mode LA as JPEG
        (100, 100, 2),
        # raises OSError: cannot write mode RGBA as JPE
        (100, 100, 4),
    ],
)
def test_jpeg_bad_shapes(memory_ds: Dataset, bad_shape):
    # jpeg allowed shapes:
    # ---------------------
    # (100) works!
    # (100,) works!
    # (100, 100) works!
    # (100, 100, 1) works!
    # (100, 100, 2) raises   | OSError: cannot write mode LA as JPEG
    # (100, 100, 3) works!
    # (100, 100, 4) raises   | OSError: cannot write mode RGBA as JPEG
    # (100, 100, 5) raises   | TypeError: Cannot handle this data type: (1, 1, 5), |u1
    # (100, 100, 100) raises | TypeError: Cannot handle this data type: (1, 1, 100), |u1

    tensor = memory_ds.create_tensor(TENSOR_KEY, sample_compression="jpeg")
    tensor.append(np.ones(bad_shape, dtype="uint8"))

def test_compression_aliases(memory_ds: Dataset):
    tensor = memory_ds.create_tensor("jpeg_tensor", sample_compression="jpeg")
    assert tensor.meta.sample_compression == "jpeg"

    tensor = memory_ds.create_tensor("jpg_tensor", sample_compression="jpg")
    assert tensor.meta.sample_compression == "jpeg"

    tensor = memory_ds.create_tensor("tiff_tensor", sample_compression="tiff")
    assert tensor.meta.sample_compression == "tiff"

    tensor = memory_ds.create_tensor("tif_tensor", sample_compression="tif")
    assert tensor.meta.sample_compression == "tiff"

@pytest.mark.xfail(raises=UnsupportedCompressionError, strict=True)
def test_unsupported_compression(memory_ds: Dataset):
    memory_ds.create_tensor(TENSOR_KEY, sample_compression="bad_compression")
    # TODO: same tests but with `dtype`

@pytest.mark.xfail(raises=TensorMetaMissingRequiredValue, strict=True)
def test_missing_sample_compression_for_image(memory_ds: Dataset):
    memory_ds.create_tensor("tensor", htype="image")

@pytest.mark.xfail(raises=TensorMetaMutuallyExclusiveKeysError, strict=True)
def test_sample_chunk_compression_mutually_exclusive(memory_ds: Dataset):
    memory_ds.create_tensor(
        "tensor", htype="image", sample_compression="png", chunk_compression="lz4"
    )

@pytest.mark.slow
def test_chunkwise_compression(memory_ds, cat_path, flower_path):
    ds = memory_ds
    im_ct = 5
    chunk_size = 600 * KB
    with ds:
        images = ds.create_tensor(
            "images",
            htype="image",
            chunk_compression="jpg",
            max_chunk_size=chunk_size,
            tiling_threshold=chunk_size,
        )
        images.extend([deeplake.read(cat_path)] * im_ct)
        expected_arr = np.random.randint(0, 10, (500, 450, 3)).astype("uint8")
        images.append(expected_arr)
        images.extend([deeplake.read(cat_path)] * im_ct)
        expected_img = np.array(deeplake.read(cat_path))
    ds.clear_cache()
    for i, img in enumerate(images):
        if i == im_ct:
            assert_images_close(img.numpy(), expected_arr)
        else:
            assert_images_close(img.numpy(), expected_img)
    with ds:
        images = ds.create_tensor(
            "images2",
            htype="image",
            chunk_compression="png",
            max_chunk_size=chunk_size,
            tiling_threshold=chunk_size,
        )
        images.extend([deeplake.read(flower_path)] * im_ct)
        expected_arr = np.random.randint(0, 256, (200, 250, 4)).astype("uint8")
        images.append(expected_arr)
        images.extend([deeplake.read(flower_path)] * im_ct)
        expected_img = np.array(deeplake.read(flower_path))
    ds.clear_cache()
    for i, img in enumerate(images):
        if i == im_ct:
            assert_images_close(img.numpy(), expected_arr)
        else:
            assert_images_close(img.numpy(), expected_img)
    with ds:
        labels = ds.create_tensor(
            "labels",
            chunk_compression="lz4",
            max_chunk_size=chunk_size,
            tiling_threshold=chunk_size,
        )
        data = [
            np.random.randint(0, 256, (150, 150)).astype("uint8") for _ in range(20)
        ]
        labels.extend(data)
    ds.clear_cache()
    for row, label in zip(data, labels):
        np.testing.assert_array_equal(row, label.numpy())

    data = np.random.randint(0, 256, (5, 1500, 1500)).astype("uint8")
    with ds:
        ds.labels.extend(data)  # type: ignore
    ds.clear_cache()
    assert len(ds.labels) == 25
    for i in range(5):
        np.testing.assert_array_equal(data[i], ds.labels[20 + i].numpy())

def _decompress_audio_helper(path):
    import av  # type: ignore

    container = av.open(path)
    for frame in container.decode(audio=0):
        if not frame.is_corrupt:
            audio = frame.to_ndarray().astype("<f4")
            break

    for frame in container.decode(audio=0):
        audio = np.concatenate((audio, frame.to_ndarray().astype("<f4")), axis=1)

    return np.transpose(audio)

@pytest.mark.skipif(
    os.name == "nt" and sys.version_info < (3, 7), reason="requires python 3.7 or above"
)
@pytest.mark.parametrize("compression", deeplake.compression.AUDIO_COMPRESSIONS)
def test_audio(local_ds, compression, audio_paths):
    path = audio_paths[compression]
    arr = _decompress_audio_helper(path)
    local_ds.create_tensor("audio", htype="audio", sample_compression=compression)
    with local_ds:
        for _ in range(10):
            local_ds.audio.append(deeplake.read(path))  # type: ignore
    for i in range(10):
        decompressed = local_ds.audio[i].numpy()
        np.testing.assert_array_equal(decompressed[: len(arr), :], arr)  # type: ignore

@pytest.mark.slow
def test_exif(memory_ds, compressed_image_paths):
    ds = memory_ds
    with ds:
        ds.create_tensor("images", htype="image", sample_compression="jpeg")
        for path in compressed_image_paths["jpeg"]:
            ds.images.append(deeplake.read(path))
    for image in ds.images:
        assert isinstance(image.sample_info["exif"], dict), (
            type(image.sample_info["exif"]),
            path,
        )

def test_forced_htypes(
    memory_ds, grayscale_image_paths, color_image_paths, flower_path
):
    with memory_ds as ds:
        gray = ds.create_tensor("gray", htype="image.gray", sample_compression="jpeg")
        rgb = ds.create_tensor("rgb", htype="image.rgb", sample_compression="jpeg")

        gray.append(deeplake.read(grayscale_image_paths["jpeg"]))
        gray.append(deeplake.read(color_image_paths["jpeg"]))
        gray.append(deeplake.read(flower_path))
        gray.extend(np.ones((4, 10, 10, 3), dtype=np.uint8))
        gray.extend(
            [
                deeplake.read(color_image_paths["jpeg"]),
                np.ones((10, 10), dtype=np.uint8),
            ]
        )

        rgb.append(deeplake.read(grayscale_image_paths["jpeg"]))
        rgb.append(deeplake.read(color_image_paths["jpeg"]))
        rgb.append(deeplake.read(flower_path))
        rgb.extend(np.ones((4, 10, 10), dtype=np.uint8))
        rgb.extend(
            [
                deeplake.read(grayscale_image_paths["jpeg"]),
                np.ones((10, 10, 3), dtype=np.uint8),
            ]
        )

        gray_png = ds.create_tensor(
            "gray_png", htype="image.gray", sample_compression="png"
        )
        rgb_png = ds.create_tensor(
            "rgb_png", htype="image.rgb", sample_compression="png"
        )

        gray_png.append(deeplake.read(flower_path))
        gray_png.append(np.ones((10, 10, 4), dtype=np.uint8))

        rgb_png.append(deeplake.read(flower_path))
        rgb_png.append(np.ones((10, 10, 4), dtype=np.uint8))

        with pytest.raises(SampleAppendError):
            rgb_png.append(1)

        with pytest.raises(TensorMetaMissingRequiredValue):
            ds.create_tensor("abc", htype="image.rgb")

        with pytest.raises(TensorMetaMissingRequiredValue):
            ds.create_tensor("abc", htype="image.gray")

    for sample in gray:
        assert len(sample.shape) == 3

    for sample in rgb:
        assert len(sample.shape) == 3

    for sample in gray_png:
        assert len(sample.shape) == 3

    for sample in rgb_png:
        assert len(sample.shape) == 3


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
import numpy as np
from pylfi.utils.stats import iqr
from scipy import optimize, special

def histplot(data, ax=None, bins=10, **kwargs):
    """
    Histogram plot

    Parameters
    ----------
    data : array_like
        data
    ax : Axes, optional
        Axes object. Default is None.
    """
    if ax is None:
        ax = plt.gca()
    counts, bins = histogram(data, bins=bins)
    ax.hist(bins[:-1], bins=bins, weights=counts, histtype='bar',
            edgecolor=None, color='steelblue', alpha=0.9, **kwargs)

def rugplot(data, ax=None, pos=-0.005, **kwargs):
    """
    Rug plot
    """
    if ax is None:
        ax = plt.gca()
    ax.plot(data,
            np.full_like(data, pos),
            '|k',
            markeredgewidth=1,
            **kwargs
            )

def densityplot(x, density, ax=None, fill=True, **kwargs):
    """
    Density plot
    """
    if ax is None:
        ax = plt.gca()

    if fill:
        ax.fill_between(x, density, alpha=0.5, **kwargs)
    else:
        ax.plot(x, density, **kwargs)

def histogram(data, bins=10, density=True, **kwargs):
    """
    """
    bins = calculate_bins(data, bins=bins)
    return np.histogram(data, bins=bins, density=density, **kwargs)

def calculate_bins(data, bins):
    """
    """
    if isinstance(bins, str):
        data = np.asarray(data).ravel()

        if bins == "sqrt":
            bins = square_root_rule(data)
        elif bins == "sturges":
            bins = sturges_rule(data)
        elif bins == "scott":
            bins = scotts_rule(data)
        elif bins == "freedman":
            bins = freedman_diaconis_rule(data)
        elif bins == "knuth":
            bins = knuths_rule(data)
        else:
            msg = (f"Unrecognized bin rule: '{bins}'. Supported rules are: "
                   "'sqrt', 'sturges', 'scott', 'freedman', 'knuth'")
            raise ValueError(msg)

    return bins

def square_root_rule(data):
    """
    Calculate number of histogram bins using the Square-root rule.
    """
    data = np.asarray(data)
    check_1D_data(data)
    n = data.size
    return int(np.ceil(np.sqrt(n)))

def sturges_rule(data):
    """
    Calculate number of histogram bins using Sturges' rule.
    """
    data = np.asarray(data)
    check_1D_data(data)
    check_number_of_entries(data, n_entries=1)
    n = data.size
    return int(np.ceil(np.log2(n)) + 1)

def scotts_rule(data):
    """
    Calculate the optimal histogram bin width using Scott's rule.

    References
    ----------
    Scott, David W. (1979).
    "On optimal and data-based histograms".
    Biometricka 66 (3): 605-610
    """
    data = np.asarray(data)
    check_1D_data(data)
    check_number_of_entries(data, n_entries=1)

    n = data.size
    dmin, dmax = data.min(), data.max()
    h = 3.49 * np.std(data) * n**(-1 / 3)
    k = int(np.ceil((dmax - dmin) / h))
    bins = dmin + h * np.arange(k + 1)

    return bins

def freedman_diaconis_rule(data):
    """
    Calculate the optimal histogram bin width using the Freedman-Diaconis rule.

    References
    ----------
    D. Freedman & P. Diaconis. (1981).
    "On the histogram as a density estimator: L2 theory".
    Probability Theory and Related Fields 57 (4): 453-476
    """
    data = np.asarray(data)
    check_1D_data(data)
    check_number_of_entries(data, n_entries=3)

    n = data.size
    dmin, dmax = data.min(), data.max()
    h = 2 * iqr(data) * n**(-1 / 3)

    if h == 0:
        bins = scotts_rule(data)
    else:
        k = int(np.ceil((dmax - dmin) / h))
        bins = dmin + h * np.arange(k + 1)

    return bins

def knuths_rule(data):
    """
    Knuth’s rule chooses a constant bin size which minimizes the error of the
    histogram’s approximation to the data

    Based on the implementation in astropy:
    https://docs.astropy.org/en/stable/_modules/astropy/stats/histogram.html#knuth_bin_width

    References
    ----------
    Knuth, K.H. (2006).
    "Optimal Data-Based Binning for Histograms".
    arXiv:0605197
    """
    data = np.array(data, copy=True)
    check_1D_data(data)
    check_number_of_entries(data, n_entries=3)

    n = data.size
    data.sort()

    def knuth_func(M):
        """Evaluate the negative Knuth likelihood function => smaller values optimal"""
        M = int(M)

        if M <= 0:
            return np.inf

        bins = np.linspace(data[0], data[-1], int(M) + 1)
        nk, bins = np.histogram(data, bins)

        return -(n * np.log(M) +
                 special.gammaln(0.5 * M) -
                 M * special.gammaln(0.5) -
                 special.gammaln(n + 0.5 * M) +
                 np.sum(special.gammaln(nk + 0.5)))

    bins0 = freedman_diaconis_rule(data)
    M = optimize.fmin(knuth_func, len(bins0), disp=False)[0]
    bins = np.linspace(data[0], data[-1], int(M) + 1)

    return bins

def check_1D_data(data):
    """Check that data is one-dimensional"""
    if data.ndim != 1:
        msg = ("data must be one-dimensional")
        raise ValueError(msg)

def check_number_of_entries(data, n_entries=1):
    """Check that data has more than specified number of entries"""
    if not data.size > n_entries:
        msg = (f"Data should have more than {n_entries} entries")
        raise ValueError(msg)

if __name__ == "__main__":
    from matplotlib import gridspec

    def make_data(N, f=0.3, rseed=1):
        rand = np.random.RandomState(rseed)
        x = rand.randn(N)
        x[int(f * N):] += 5
        return x

    data = make_data(500)

    rules = [30, 'sqrt', 'sturges', 'scott', 'freedman', 'knuth']

    fig = plt.figure(figsize=(10, 6), tight_layout=True, dpi=120)
    gs = gridspec.GridSpec(ncols=3, nrows=2, figure=fig)

    for i, rule in enumerate(rules):
        ax = fig.add_subplot(gs[i])
        histplot(data, ax, bins=rule, label=f"bins = {rule}")
        rugplot(data, ax)
        ax.set_xlabel("$x$")
        ax.set_ylabel("Density")
        ax.legend(loc="upper left")

    plt.show()


# coding: utf-8
"""smp_graphs thesis batch learning vs. online learning

Make illustrative plot that describes the transition from standard
batch learning to single time step incremental learning.
"""
import numpy as np
import matplotlib.pyplot as plt

durs = np.logspace(1, 10, 4, base=2)[::-1]
# fig = plt.figure(figsize=(12, 6))
fig = plt.figure(figsize=(6, 12))
episodes = []
for j, dur in enumerate(durs):
    episodes.append(np.random.uniform(-1, 1, (int(dur), 2)))
    episodes[-1][0,:] = 0.
    for i, t_i in enumerate(episodes[-1][1:]):
        episodes[-1][i+1] = episodes[-1][i] + np.random.normal(0, 0.1, episodes[-1][i].shape)
        # np.putmask(episodes[-1][i+1], np.abs(episodes[-1][i+1]) > np.array([1, 1]), episodes[-1][i+1] + 2 * (1 - np.abs(episodes[-1][i+1])))
        res_ = episodes[-1][i+1] - np.clip(episodes[-1][i+1], -1, 1)
        episodes[-1][i+1] -= 2*res_
    # ax = fig.add_subplot(2, 4, j+1)
    ax = fig.add_subplot(4, 2, (j*2)+1)
    ax.plot(episodes[-1][:,0], episodes[-1][:,1], 'b-', marker=',', alpha=0.5)
    ax.plot(episodes[-1][-1,0], episodes[-1][-1,1], 'bo', marker='o', alpha=0.8)
    ax.set_xlim((-1.1, 1.1))
    ax.set_ylim((-1.1, 1.1))
    # ax.set_title('Episode of %d steps' % (dur-1))
    ax.set_ylabel('Episode of %d steps' % (dur-1), fontsize=8)
    ax.set_aspect(1)
    # ax.set_axis_off()
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_frame_on(False)
    # ax = fig.add_subplot(2, 4, 4+j+1)
    ax = fig.add_subplot(4, 2, (j*2)+2)
    ax.plot(episodes[-1])
    ax.set_xlim((-10, 1033))
    ax.set_ylim((-1.1, 1.1))
    ax.set_aspect(400)
    # ax.set_axis_off()
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_frame_on(False)

# fig.subplots_adjust(wspace=0.1, hspace=0.05)
fig.subplots_adjust(wspace=0.05, hspace=0.2)
fig.show()
fig.savefig('im-batch-to-single.pdf', bbox_inches='tight')

plt.show()


#!/usr/bin/env python3
"""
File: isc_viewzone.py

Clause: view, zone

Title: Statements Used Only By view And zone Clauses

Description: isc_viewzone contains all parse elements pertaining
             to both options and zone (but not view)
"""
from pyparsing import CaselessKeyword, OneOrMore, Keyword
from bind9_parser.isc_utils import semicolon, database_name_type
from bind9_parser.isc_clause_dlz import dlz_name_type

viewzone_stmt_database = (
    Keyword('database').suppress()
    - database_name_type('database')
    + semicolon
)

#  dlz <dlz_name>;  [ View Zone ]
#  See isc_dlz.clause_stmt_dlz_series for full DLZ-clause syntax in
#      which views/zones' DLZ references to.
viewzone_stmt_dlz = (
    CaselessKeyword('dlz').suppress()
    - dlz_name_type('dlz')
    + semicolon
)

# Keywords are in dictionary-order, but with longest pattern as
# having been listed firstly
#
# This statement set is to be used by either 'view' or 'zone' clause
viewzone_statements_set = (
    viewzone_stmt_database
    | viewzone_stmt_dlz
)

viewzone_statements_series = OneOrMore(viewzone_statements_set)


from selenium import webdriver
import os

class Test():
   def Testmethod(self):
#
        driverLocation = "C:\\Users\\adiwakar\Documents\\Selenium Browser files\Library\\IEDriverServer.exe"
        os.environ["webdriver.driver.ie"]= driverLocation
        driver= webdriver.Ie(driverLocation)
        driver.get("https://google.com")
TT=Test()
TT.Testmethod()


#!/usr/bin/env python3
import os
import requests

# Setup directories to process and upload the fruit descriptions
url = "http://[linux-instance-external-IP]/fruits/"
home = os.path.expanduser("~")
directory = home + "/supplier-data/descriptions"
fl_lst = os.listdir(directory)
lst_desc = []

# Loop through the files to process the fruit descriptions
for file in fl_lst:
    file_dir = os.path.join(directory, file)
    with open(file_dir, 'rb') as desc:
        # Populate list with the fruit descriptions organized into
        # dictionaries for JSON conversion
        txt = []
        fruit_desc = {}
        for line in desc:
            txt.append(str(line.rstrip(), 'UTF-8'))
        fruit_desc["name"] = txt[0]
        weight = int(txt[1].split()[0])
        fruit_desc["weight"] = weight
        fruit_desc["description"] = txt[2]
        image_name = file.split(".")[0] + ".jpeg"
        fruit_desc["image_name"] = image_name
        lst_desc.append(fruit_desc)

# Send each fruit description to the local website as a json file
for fruit in lst_desc:
    r = requests.post(url, json=fruit)


import random
from tkinter import *
from tkinter import messagebox
from openpyxl import load_workbook
# -*- coding: UTF-8 -*-

class supermarket:
    def __init__(self, root):
        self.root = root
        self.root.geometry('1250x690+60+2')
        self.root.title('Supermarket System')
        self.root.resizable(False, False)
        title = Label(self.root, text='SuperMarket System', fg='white', bg='#0B2F3A', font=('tajawal', 16))
        title.pack(fill=X)
        # ============ V Customer =========
        self.name = StringVar()
        self.phone = StringVar()
        self.bill = StringVar()
        x = random.randint(1, 100)
        self.bill.set(str(x))

        self.x = IntVar()

        # =========== V section 1 ========
        self.s1 = IntVar()
        self.s2 = IntVar()
        self.s3 = IntVar()
        self.s4 = IntVar()
        self.s5 = IntVar()
        self.s6 = IntVar()
        self.s7 = IntVar()
        self.s8 = IntVar()
        self.s9 = IntVar()
        self.s10 = IntVar()
        self.s11 = IntVar()
        self.s12 = IntVar()
        self.s13 = IntVar()
        self.s14 = IntVar()
        self.s15 = IntVar()

        # =========== V section 2 ========
        self.ss1 = IntVar()
        self.ss2 = IntVar()
        self.ss3 = IntVar()
        self.ss4 = IntVar()
        self.ss5 = IntVar()
        self.ss6 = IntVar()
        self.ss7 = IntVar()
        self.ss8 = IntVar()
        self.ss9 = IntVar()
        self.ss10 = IntVar()
        self.ss11 = IntVar()
        self.ss12 = IntVar()
        self.ss13 = IntVar()
        self.ss14 = IntVar()
        self.ss15 = IntVar()

        # =========== V section 3 ========
        self.sss1 = IntVar()
        self.sss2 = IntVar()
        self.sss3 = IntVar()
        self.sss4 = IntVar()
        self.sss5 = IntVar()
        self.sss6 = IntVar()
        self.sss7 = IntVar()
        self.sss8 = IntVar()
        self.sss9 = IntVar()
        self.sss10 = IntVar()
        self.sss11 = IntVar()
        self.sss12 = IntVar()
        self.sss13 = IntVar()
        self.sss14 = IntVar()
        self.sss15 = IntVar()

        # =========== V total =============
        self.section1 = StringVar()
        self.section2 = StringVar()
        self.section3 = StringVar()

        # ============custumer Data===============#
        F1 = Frame(root, bd=2, width=310, height=170, bg='#0B4C5f')
        F1.place(x=938, y=31)
        txt1 = Label(F1, text='CUSTOMER INFO', font=('tajawal', 13, 'bold'), fg='white', bg='#0B4C5f')
        txt1.place(x=100, y=0)
        cust_name = Label(F1, text='Name', font=('tajawal', 12), fg='white', bg='#0B4C5f')
        cust_name.place(x=5, y=40)
        cust_phone = Label(F1, text='Phone', font=('tajawal', 12), fg='white', bg='#0B4C5f')
        cust_phone.place(x=5, y=70)
        cust_bill = Label(F1, text='Bill Num', font=('tajawal', 12), fg='white', bg='#0B4C5f')
        cust_bill.place(x=5, y=100)

        En_name = Entry(F1, textvariable=self.name, justify='center')
        En_name.place(x=104, y=40)
        En_phone = Entry(F1, textvariable=self.phone, justify='center')
        En_phone.place(x=104, y=70)
        En_bill = Entry(F1, textvariable=self.bill, justify='center')
        En_bill.place(x=104, y=100)

        btn_cust = Button(F1, text='search', font=('tajawal', 10), width=17, height=1, bg='silver', fg='black')
        btn_cust.place(x=104, y=130)

        # ==============BILL=================#
        F2 = Frame(root, bd=2, width=309, height=320, bg='silver')
        F2.place(x=938, y=205)
        scrol_y = Scrollbar(F2, orient=VERTICAL)
        self.txtarea = Text(F2, yscrollcommand=scrol_y.set)
        scrol_y.pack(side=LEFT, fill=Y)
        scrol_y.config(command=self.txtarea.yview)
        self.txtarea.pack(fill=BOTH, expand=1)

        # ===============PRICE=================#
        F3 = Frame(root, bd=2, width=605, height=130, bg='#0B4C5f')
        F3.place(x=642, y=558)
        total = Button(F3, text='TOTAL', width=8, height=1, fg='black', bg='silver', font=('tajawal', 10),
                       command=self.total)
        total.place(x=500, y=5)
        bill = Button(F3, text='EXPORT', width=8, height=1, fg='black', bg='silver', font=('tajawal', 10),
                      command=self.billl)
        bill.place(x=500, y=44)
        clear = Button(F3, text='CLEAR', width=8, height=1, fg='black', bg='silver', font=('tajawal', 10),
                       command=self.clear)
        clear.place(x=500, y=83)

        txt2 = Label(F3, text='Section 1', font=('tajawal', 15, 'bold'), bg='#0B4C5f', fg='silver')
        txt2.place(x=5, y=10)
        txt3 = Label(F3, text='Section 2', font=('tajawal', 15, 'bold'), bg='#0B4C5f', fg='silver')
        txt3.place(x=5, y=50)
        txt4 = Label(F3, text='Section 3', font=('tajawal', 15, 'bold'), bg='#0B4C5f', fg='silver')
        txt4.place(x=5, y=90)

        En_1 = Entry(F3, textvariable=self.section1, width=24, justify='center')
        En_1.place(x=280, y=10)
        En_2 = Entry(F3, textvariable=self.section2, width=24, justify='center')
        En_2.place(x=280, y=50)
        En_3 = Entry(F3, textvariable=self.section3, width=24, justify='center')
        En_3.place(x=280, y=90)

        # ===================ITems[1]=====================
        F4 = Frame(root, width=318, height=660, bg='#0B4C5f')
        F4.place(x=1, y=31)
        text4 = Label(F4, text="( Juices and frozen )", font=('tajawal', 15, 'bold'), bg='#0B4C5f', fg='silver')
        text4.place(x=60, y=0)

        l1 = Label(F4, text='Burger', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        l1.place(x=10, y=50)
        l2 = Label(F4, text='Mozzarella', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        l2.place(x=10, y=95)
        l3 = Label(F4, text='Element 3', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        l3.place(x=10, y=140)
        l4 = Label(F4, text='Element 4', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        l4.place(x=10, y=178)
        l5 = Label(F4, text='Element 5', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        l5.place(x=10, y=220)
        l6 = Label(F4, text='Element 6', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        l6.place(x=10, y=260)
        l7 = Label(F4, text='Element 7', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        l7.place(x=10, y=305)
        l8 = Label(F4, text='Element 8', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        l8.place(x=10, y=345)
        l9 = Label(F4, text='Element 9', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        l9.place(x=10, y=385)
        l10 = Label(F4, text='Element 1', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        l10.place(x=10, y=425)
        l11 = Label(F4, text='Element 2', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        l11.place(x=10, y=465)
        l12 = Label(F4, text='Element 3', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        l12.place(x=10, y=505)
        l13 = Label(F4, text='Element 4', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        l13.place(x=10, y=545)
        l14 = Label(F4, text='Element 6', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        l14.place(x=10, y=585)
        l15 = Label(F4, text='Element 7', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        l15.place(x=10, y=625)

        # ( Button )
        lEnt1 = Entry(F4, textvariable=self.s1, width=12, justify='center')
        lEnt1.place(x=105, y=50)

        lBlus1 = Button(F4, text="+", width=1, bd=3, bg="silver", activebackground="silver", command=self.addS1)
        lBlus1.place(x=270, y=45)

        lMin1 = Button(F4, text="-", width=1, bd=3, bg="silver", activebackground="silver", command=self.subS1)
        lMin1.place(x=220, y=45)

        lEnt2 = Entry(F4, textvariable=self.s2, width=12, justify='center')
        lEnt2.place(x=105, y=95)

        lBlus2 = Button(F4, text="+", width=1, bd=3, bg="silver", command=self.addS2)
        lBlus2.place(x=270, y=90)

        lMin2 = Button(F4, text="-", width=1, bd=3, bg="silver", command=self.subS2)
        lMin2.place(x=220, y=90)

        lEnt3 = Entry(F4, textvariable=self.s3, width=12, justify='center')
        lEnt3.place(x=105, y=140)

        lBlus3 = Button(F4, text="+", width=1, bd=3, bg="silver", command=self.addS3)
        lBlus3.place(x=270, y=133)

        lMin3 = Button(F4, text="-", width=1, bd=3, bg="silver", command=self.subS3)
        lMin3.place(x=220, y=133)

        lEnt4 = Entry(F4, textvariable=self.s4, width=12, justify='center')
        lEnt4.place(x=105, y=178)

        lBlus4 = Button(F4, text="+", width=1, bd=3, bg="silver", command=self.addS4)
        lBlus4.place(x=270, y=175)

        lMin4 = Button(F4, text="-", width=1, bd=3, bg="silver", command=self.subS4)
        lMin4.place(x=220, y=175)

        lEnt5 = Entry(F4, textvariable=self.s5, width=12, justify='center')
        lEnt5.place(x=105, y=220)

        lBlus5 = Button(F4, text="+", width=1, bd=3, bg="silver", command=self.addS5)
        lBlus5.place(x=270, y=215)

        lMin5 = Button(F4, text="-", width=1, bd=3, bg="silver", command=self.subS5)
        lMin5.place(x=220, y=215)

        lEnt6 = Entry(F4, textvariable=self.s6, width=12, justify='center')
        lEnt6.place(x=105, y=260)

        lBlus6 = Button(F4, text="+", width=1, bd=3, bg="silver", command=self.addS6)
        lBlus6.place(x=270, y=255)

        lMin6 = Button(F4, text="-", width=1, bd=3, bg="silver", command=self.subS6)
        lMin6.place(x=220, y=255)

        lEnt7 = Entry(F4, textvariable=self.s7, width=12, justify='center')
        lEnt7.place(x=105, y=305)

        lBlus7 = Button(F4, text="+", width=1, bd=3, bg="silver", command=self.addS7)
        lBlus7.place(x=270, y=298)

        lMin7 = Button(F4, text="-", width=1, bd=3, bg="silver", command=self.subS7)
        lMin7.place(x=220, y=298)

        lEnt8 = Entry(F4, textvariable=self.s8, width=12, justify='center')
        lEnt8.place(x=105, y=345)

        lBlus8 = Button(F4, text="+", width=1, bd=3, bg="silver", command=self.addS8)
        lBlus8.place(x=270, y=340)

        lMin8 = Button(F4, text="-", width=1, bd=3, bg="silver", command=self.subS8)
        lMin8.place(x=220, y=340)

        lEnt9 = Entry(F4, textvariable=self.s9, width=12, justify='center')
        lEnt9.place(x=105, y=385)

        lBlus9 = Button(F4, text="+", width=1, bd=3, bg="silver", command=self.addS9)
        lBlus9.place(x=270, y=380)

        lMin9 = Button(F4, text="-", width=1, bd=3, bg="silver", command=self.subS9)
        lMin9.place(x=220, y=380)

        lEnt10 = Entry(F4, textvariable=self.s10, width=12, justify='center')
        lEnt10.place(x=105, y=425)

        lBlus10 = Button(F4, text="+", width=1, bd=3, bg="silver", command=self.addS10)
        lBlus10.place(x=270, y=420)

        lMin10 = Button(F4, text="-", width=1, bd=3, bg="silver", command=self.subS10)
        lMin10.place(x=220, y=420)

        lEnt11 = Entry(F4, textvariable=self.s11, width=12, justify='center')
        lEnt11.place(x=105, y=465)

        lBlus11 = Button(F4, text="+", width=1, bd=3, bg="silver", command=self.addS11)
        lBlus11.place(x=270, y=460)

        lMin11 = Button(F4, text="-", width=1, bd=3, bg="silver", command=self.subS11)
        lMin11.place(x=220, y=460)

        lEnt12 = Entry(F4, textvariable=self.s12, width=12, justify='center')
        lEnt12.place(x=105, y=505)

        lBlus12 = Button(F4, text="+", width=1, bd=3, bg="silver", command=self.addS12)
        lBlus12.place(x=270, y=500)

        lMin12 = Button(F4, text="-", width=1, bd=3, bg="silver", command=self.subS12)
        lMin12.place(x=220, y=500)

        lEnt13 = Entry(F4, textvariable=self.s13, width=12, justify='center')
        lEnt13.place(x=105, y=545)

        lBlus13 = Button(F4, text="+", width=1, bd=3, bg="silver", command=self.addS13)
        lBlus13.place(x=270, y=540)

        lMin13 = Button(F4, text="-", width=1, bd=3, bg="silver", command=self.subS13)
        lMin13.place(x=220, y=540)

        lEnt14 = Entry(F4, textvariable=self.s14, width=12, justify='center')
        lEnt14.place(x=105, y=585)

        lBlus14 = Button(F4, text="+", width=1, bd=3, bg="silver", command=self.addS14)
        lBlus14.place(x=270, y=580)

        lMin14 = Button(F4, text="-", width=1, bd=3, bg="silver", command=self.subS14)
        lMin14.place(x=220, y=580)

        lEnt15 = Entry(F4, textvariable=self.s15, width=12, justify='center')
        lEnt15.place(x=105, y=625)

        lBlus15 = Button(F4, text="+", width=1, bd=3, bg="silver", command=self.addS15)
        lBlus15.place(x=270, y=620)

        lMin15 = Button(F4, text="-", width=1, bd=3, bg="silver", command=self.subS15)
        lMin15.place(x=220, y=620)

        # ==========Items[2]=========================
        F5 = Frame(root, width=320, height=660, bg='#0B4C5f')
        F5.place(x=320, y=31)
        text5 = Label(F5, text='Section 2', font=('tajawal', 15, 'bold'), bg='#0B4C5f', fg='silver')
        text5.place(x=110, y=0)

        h1 = Label(F5, text='Element 1', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        h1.place(x=10, y=50)
        h2 = Label(F5, text='Element 2', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        h2.place(x=10, y=95)
        h3 = Label(F5, text='Element 3', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        h3.place(x=10, y=140)
        h4 = Label(F5, text='Element 4', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        h4.place(x=10, y=178)
        h5 = Label(F5, text='Element 5', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        h5.place(x=10, y=220)
        h6 = Label(F5, text='Element 6', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        h6.place(x=10, y=260)
        h7 = Label(F5, text='Element 7', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        h7.place(x=10, y=305)
        h8 = Label(F5, text='Element 8', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        h8.place(x=10, y=345)
        h9 = Label(F5, text='Element 9', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        h9.place(x=10, y=385)
        h10 = Label(F5, text='Element 1', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        h10.place(x=10, y=425)
        h11 = Label(F5, text='Element 2', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        h11.place(x=10, y=465)
        h12 = Label(F5, text='Element 3', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        h12.place(x=10, y=505)
        h13 = Label(F5, text='Element 4', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        h13.place(x=10, y=545)
        h14 = Label(F5, text='Element 5', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        h14.place(x=10, y=586)
        h15 = Label(F5, text='Element 6', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        h15.place(x=10, y=625)

        # Button
        hEnt1 = Entry(F5, textvariable=self.ss1, width=12, justify='center')
        hEnt1.place(x=105, y=50)

        hBlus1 = Button(F5, text="+", width=1, bd=3, bg="silver", activebackground="silver", command=self.addSS1)
        hBlus1.place(x=270, y=45)

        hMin1 = Button(F5, text="-", width=1, bd=3, bg="silver", activebackground="silver", command=self.subSS1)
        hMin1.place(x=220, y=45)

        hEnt2 = Entry(F5, textvariable=self.ss2, width=12, justify='center')
        hEnt2.place(x=105, y=95)

        hBlus2 = Button(F5, text="+", width=1, bd=3, bg="silver", command=self.addSS2)
        hBlus2.place(x=270, y=90)

        hMin2 = Button(F5, text="-", width=1, bd=3, bg="silver", command=self.subSS2)
        hMin2.place(x=220, y=90)

        hEnt3 = Entry(F5, textvariable=self.ss3, width=12, justify='center')
        hEnt3.place(x=105, y=140)

        hBlus3 = Button(F5, text="+", width=1, bd=3, bg="silver", command=self.addSS3)
        hBlus3.place(x=270, y=133)

        hMin3 = Button(F5, text="-", width=1, bd=3, bg="silver", command=self.subSS3)
        hMin3.place(x=220, y=133)

        hEnt4 = Entry(F5, textvariable=self.ss4, width=12, justify='center')
        hEnt4.place(x=105, y=178)

        hBlus4 = Button(F5, text="+", width=1, bd=3, bg="silver", command=self.addSS4)
        hBlus4.place(x=270, y=175)

        hMin4 = Button(F5, text="-", width=1, bd=3, bg="silver", command=self.subSS4)
        hMin4.place(x=220, y=175)

        hEnt5 = Entry(F5, textvariable=self.ss5, width=12, justify='center')
        hEnt5.place(x=105, y=220)

        hBlus5 = Button(F5, text="+", width=1, bd=3, bg="silver", command=self.addSS5)
        hBlus5.place(x=270, y=215)

        hMin5 = Button(F5, text="-", width=1, bd=3, bg="silver", command=self.subSS5)
        hMin5.place(x=220, y=215)

        hEnt6 = Entry(F5, textvariable=self.ss6, width=12, justify='center')
        hEnt6.place(x=105, y=260)

        hBlus6 = Button(F5, text="+", width=1, bd=3, bg="silver", command=self.addSS6)
        hBlus6.place(x=270, y=255)

        hMin6 = Button(F5, text="-", width=1, bd=3, bg="silver", command=self.subSS6)
        hMin6.place(x=220, y=255)

        hEnt7 = Entry(F5, textvariable=self.ss7, width=12, justify='center')
        hEnt7.place(x=105, y=305)

        hBlus7 = Button(F5, text="+", width=1, bd=3, bg="silver", command=self.addSS7)
        hBlus7.place(x=270, y=298)

        hMin7 = Button(F5, text="-", width=1, bd=3, bg="silver", command=self.subSS7)
        hMin7.place(x=220, y=298)

        hEnt8 = Entry(F5, textvariable=self.ss8, width=12, justify='center')
        hEnt8.place(x=105, y=345)

        hBlus8 = Button(F5, text="+", width=1, bd=3, bg="silver", command=self.addSS8)
        hBlus8.place(x=270, y=340)

        hMin8 = Button(F5, text="-", width=1, bd=3, bg="silver", command=self.subSS8)
        hMin8.place(x=220, y=340)

        hEnt9 = Entry(F5, textvariable=self.ss9, width=12, justify='center')
        hEnt9.place(x=105, y=385)

        hBlus9 = Button(F5, text="+", width=1, bd=3, bg="silver", command=self.addSS9)
        hBlus9.place(x=270, y=380)

        hMin9 = Button(F5, text="-", width=1, bd=3, bg="silver", command=self.subSS9)
        hMin9.place(x=220, y=380)

        hEnt10 = Entry(F5, textvariable=self.ss10, width=12, justify='center')
        hEnt10.place(x=105, y=425)

        hBlus10 = Button(F5, text="+", width=1, bd=3, bg="silver", command=self.addSS10)
        hBlus10.place(x=270, y=420)

        hMin10 = Button(F5, text="-", width=1, bd=3, bg="silver", command=self.subSS10)
        hMin10.place(x=220, y=420)

        hEnt11 = Entry(F5, textvariable=self.ss11, width=12, justify='center')
        hEnt11.place(x=105, y=465)

        hBlus11 = Button(F5, text="+", width=1, bd=3, bg="silver", command=self.addSS11)
        hBlus11.place(x=270, y=460)

        hMin11 = Button(F5, text="-", width=1, bd=3, bg="silver", command=self.subSS11)
        hMin11.place(x=220, y=460)

        hEnt12 = Entry(F5, textvariable=self.ss12, width=12, justify='center')
        hEnt12.place(x=105, y=505)

        hBlus12 = Button(F5, text="+", width=1, bd=3, bg="silver", command=self.addSS12)
        hBlus12.place(x=270, y=500)

        hMin12 = Button(F5, text="-", width=1, bd=3, bg="silver", command=self.subSS12)
        hMin12.place(x=220, y=500)

        hEnt13 = Entry(F5, textvariable=self.ss13, width=12, justify='center')
        hEnt13.place(x=105, y=545)

        hBlus13 = Button(F5, text="+", width=1, bd=3, bg="silver", command=self.addSS13)
        hBlus13.place(x=270, y=540)

        hMin13 = Button(F5, text="-", width=1, bd=3, bg="silver", command=self.subSS13)
        hMin13.place(x=220, y=540)

        hEnt14 = Entry(F5, textvariable=self.ss14, width=12, justify='center')
        hEnt14.place(x=105, y=585)

        hBlus14 = Button(F5, text="+", width=1, bd=3, bg="silver", command=self.addSS14)
        hBlus14.place(x=270, y=580)

        hMin14 = Button(F5, text="-", width=1, bd=3, bg="silver", command=self.subSS14)
        hMin14.place(x=220, y=580)

        hEnt15 = Entry(F5, textvariable=self.ss15, width=12, justify='center')
        hEnt15.place(x=105, y=625)

        hBlus15 = Button(F5, text="+", width=1, bd=3, bg="silver", command=self.addSS15)
        hBlus15.place(x=270, y=620)

        hMin15 = Button(F5, text="-", width=1, bd=3, bg="silver", command=self.subSS15)
        hMin15.place(x=220, y=620)

        # =============ITEMS[3]============================
        F6 = Frame(root, width=295, height=525, bg='#0B4C5f')
        F6.place(x=642, y=31)
        text6 = Label(F6, text='Section 3', font=('tajawal', 15, 'bold'), bg='#0B4C5f', fg='silver')
        text6.place(x=110, y=0)

        e1 = Label(F6, text='Element 1', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        e1.place(x=5, y=50)
        e2 = Label(F6, text='Element 2', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        e2.place(x=5, y=95)
        e3 = Label(F6, text='Element 3', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        e3.place(x=5, y=140)
        e4 = Label(F6, text='Element 4', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        e4.place(x=5, y=178)
        e5 = Label(F6, text='Element 5', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        e5.place(x=5, y=220)
        e6 = Label(F6, text='Element 6', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        e6.place(x=5, y=260)
        e7 = Label(F6, text='Element 7', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        e7.place(x=5, y=305)
        e8 = Label(F6, text='Element 8', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        e8.place(x=5, y=345)
        e9 = Label(F6, text='Element 9', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        e9.place(x=5, y=385)
        e10 = Label(F6, text='Element 1', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        e10.place(x=5, y=425)
        e11 = Label(F6, text='Element 2', font=('tajawal', 12), bg='#0B4C5f', fg='white')
        e11.place(x=5, y=465)

        # Button
        eEnt1 = Entry(F6, textvariable=self.sss1, width=12, justify='center')
        eEnt1.place(x=95, y=50)

        eBlus1 = Button(F6, text="+", width=1, bd=3, bg="silver", activebackground="silver", command=self.addSSS1)
        eBlus1.place(x=250, y=45)

        eMin1 = Button(F6, text="-", width=1, bd=3, bg="silver", activebackground="silver", command=self.subSSS1)
        eMin1.place(x=205, y=45)

        eEnt2 = Entry(F6, textvariable=self.sss2, width=12, justify='center')
        eEnt2.place(x=95, y=95)

        eBlus2 = Button(F6, text="+", width=1, bd=3, bg="silver", activebackground="silver", command=self.addSSS2)
        eBlus2.place(x=250, y=90)

        eMin2 = Button(F6, text="-", width=1, bd=3, bg="silver", activebackground="silver", command=self.subSSS2)
        eMin2.place(x=205, y=90)

        eEnt3 = Entry(F6, textvariable=self.sss3, width=12, justify='center')
        eEnt3.place(x=95, y=140)

        eBlus3 = Button(F6, text="+", width=1, bd=3, bg="silver", activebackground="silver", command=self.addSSS3)
        eBlus3.place(x=250, y=135)

        eMin3 = Button(F6, text="-", width=1, bd=3, bg="silver", activebackground="silver", command=self.subSSS3)
        eMin3.place(x=205, y=135)

        eEnt4 = Entry(F6, textvariable=self.sss4, width=12, justify='center')
        eEnt4.place(x=95, y=178)

        eBlus4 = Button(F6, text="+", width=1, bd=3, bg="silver", activebackground="silver", command=self.addSSS4)
        eBlus4.place(x=250, y=175)

        eMin4 = Button(F6, text="-", width=1, bd=3, bg="silver", activebackground="silver", command=self.subSSS4)
        eMin4.place(x=205, y=175)

        eEnt5 = Entry(F6, textvariable=self.sss5, width=12, justify='center')
        eEnt5.place(x=95, y=220)

        eBlus5 = Button(F6, text="+", width=1, bd=3, bg="silver", activebackground="silver", command=self.addSSS5)
        eBlus5.place(x=250, y=215)

        eMin5 = Button(F6, text="-", width=1, bd=3, bg="silver", activebackground="silver", command=self.subSSS5)
        eMin5.place(x=205, y=215)

        eEnt6 = Entry(F6, textvariable=self.sss6, width=12, justify='center')
        eEnt6.place(x=95, y=260)

        eBlus6 = Button(F6, text="+", width=1, bd=3, bg="silver", activebackground="silver", command=self.addSSS6)
        eBlus6.place(x=250, y=255)

        eMin6 = Button(F6, text="-", width=1, bd=3, bg="silver", activebackground="silver", command=self.subSSS6)
        eMin6.place(x=205, y=255)

        eEnt7 = Entry(F6, textvariable=self.sss7, width=12, justify='center')
        eEnt7.place(x=95, y=305)

        eBlus7 = Button(F6, text="+", width=1, bd=3, bg="silver", activebackground="silver", command=self.addSSS7)
        eBlus7.place(x=250, y=300)

        eMin7 = Button(F6, text="-", width=1, bd=3, bg="silver", activebackground="silver", command=self.subSSS7)
        eMin7.place(x=205, y=300)

        eEnt8 = Entry(F6, textvariable=self.sss8, width=12, justify='center')
        eEnt8.place(x=95, y=345)

        eBlus8 = Button(F6, text="+", width=1, bd=3, bg="silver", activebackground="silver", command=self.addSSS8)
        eBlus8.place(x=250, y=340)

        eMin8 = Button(F6, text="-", width=1, bd=3, bg="silver", activebackground="silver", command=self.subSSS8)
        eMin8.place(x=205, y=340)

        eEnt9 = Entry(F6, textvariable=self.sss9, width=12, justify='center')
        eEnt9.place(x=95, y=385)

        eBlus9 = Button(F6, text="+", width=1, bd=3, bg="silver", activebackground="silver", command=self.addSSS9)
        eBlus9.place(x=250, y=380)

        eMin9 = Button(F6, text="-", width=1, bd=3, bg="silver", activebackground="silver", command=self.subSSS9)
        eMin9.place(x=205, y=380)

        eEnt10 = Entry(F6, textvariable=self.sss10, width=12, justify='center')
        eEnt10.place(x=95, y=425)

        eBlus10 = Button(F6, text="+", width=1, bd=3, bg="silver", activebackground="silver", command=self.addSSS10)
        eBlus10.place(x=250, y=420)

        eMin10 = Button(F6, text="-", width=1, bd=3, bg="silver", activebackground="silver", command=self.subSSS10)
        eMin10.place(x=205, y=420)

        eEnt11 = Entry(F6, textvariable=self.sss11, width=12, justify='center')
        eEnt11.place(x=95, y=465)

        eBlus11 = Button(F6, text="+", width=1, bd=3, bg="silver", activebackground="silver", command=self.addSSS11)
        eBlus11.place(x=250, y=460)

        eMin11 = Button(F6, text="-", width=1, bd=3, bg="silver", activebackground="silver", command=self.subSSS11)
        eMin11.place(x=205, y=460)

        self.welcome()

    def total(self):
        self.ts1 = self.s1.get() * 1.5
        self.ts2 = self.s2.get() * 2
        self.ts3 = self.s3.get() * 1.5
        self.ts4 = self.s4.get() * 2
        self.ts5 = self.s5.get() * 1.5
        self.ts6 = self.s6.get() * 2
        self.ts7 = self.s7.get() * 1.5
        self.ts8 = self.s8.get() * 2
        self.ts9 = self.s9.get() * 1.5
        self.ts10 = self.s10.get() * 2
        self.ts11 = self.s11.get() * 1.5
        self.ts12 = self.s12.get() * 2
        self.ts13 = self.s13.get() * 1.5
        self.ts14 = self.s14.get() * 2
        self.ts15 = self.s15.get() * 1.5

        self.tsec1 = float(
            self.ts1 +
            self.ts2 +
            self.ts3 +
            self.ts4 +
            self.ts5 +
            self.ts6 +
            self.ts7 +
            self.ts8 +
            self.ts9 +
            self.ts10 +
            self.ts11 +
            self.ts12 +
            self.ts13 +
            self.ts14 +
            self.ts15
        )
        self.section1.set(str(self.tsec1) + " $ ")

        self.tss1 = self.ss1.get() * 1.5
        self.tss2 = self.ss2.get() * 2
        self.tss3 = self.ss3.get() * 1.5
        self.tss4 = self.ss4.get() * 2
        self.tss5 = self.ss5.get() * 1.5
        self.tss6 = self.ss6.get() * 2
        self.tss7 = self.ss7.get() * 1.5
        self.tss8 = self.ss8.get() * 2
        self.tss9 = self.ss9.get() * 1.5
        self.tss10 = self.ss10.get() * 2
        self.tss11 = self.ss11.get() * 1.5
        self.tss12 = self.ss12.get() * 2
        self.tss13 = self.ss13.get() * 1.5
        self.tss14 = self.ss14.get() * 2
        self.tss15 = self.ss15.get() * 1.5

        self.tsec2 = float(
            self.tss1 +
            self.tss2 +
            self.tss3 +
            self.tss4 +
            self.tss5 +
            self.tss6 +
            self.tss7 +
            self.tss8 +
            self.tss9 +
            self.tss10 +
            self.tss11 +
            self.tss12 +
            self.tss13 +
            self.tss14 +
            self.tss15
        )
        self.section2.set(str(self.tsec2) + " $ ")

        self.tsss1 = self.sss1.get() * 1.5
        self.tsss2 = self.sss2.get() * 2
        self.tsss3 = self.sss3.get() * 1.5
        self.tsss4 = self.sss4.get() * 2
        self.tsss5 = self.sss5.get() * 1.5
        self.tsss6 = self.sss6.get() * 2
        self.tsss7 = self.sss7.get() * 1.5
        self.tsss8 = self.sss8.get() * 2
        self.tsss9 = self.sss9.get() * 1.5
        self.tsss10 = self.sss10.get() * 2
        self.tsss11 = self.sss11.get() * 1.5
        self.tsec3 = float(
            self.tsss1 +
            self.tsss2 +
            self.tsss3 +
            self.tsss4 +
            self.tsss5 +
            self.tsss6 +
            self.tsss7 +
            self.tsss8 +
            self.tsss9 +
            self.tsss10 +
            self.tsss11
        )
        self.section3.set(str(self.tsec3) + " $ ")
        self.all = float(self.tsec1 + self.tsec2 + self.tsec3)

    def welcome(self):
        # self.txtarea.delete('1.0', END)
        self.txtarea.insert(END, "   Welcome in your SuperMarket")
        self.txtarea.insert(END, "\n===============================")
        self.txtarea.insert(END, f"\n\t B.NUM    : {self.bill.get()}")
        self.txtarea.insert(END, f"\n\t Name     : {self.name.get()}")
        self.txtarea.insert(END, f"\n\t PHONE    : {self.name.get()}")
        self.txtarea.insert(END, "\n===============================")
        self.txtarea.insert(END, f"\nPrice\t    Conter\t       Purchases")
        self.txtarea.insert(END, "\n==============================")

    def clear(self):
        self.s1.set(0)
        self.s2.set(0)
        self.s3.set(0)
        self.s4.set(0)
        self.s5.set(0)
        self.s6.set(0)
        self.s7.set(0)
        self.s8.set(0)
        self.s9.set(0)
        self.s10.set(0)
        self.s11.set(0)
        self.s12.set(0)
        self.s13.set(0)
        self.s14.set(0)
        self.s15.set(0)

        self.ss1.set(0)
        self.ss2.set(0)
        self.ss3.set(0)
        self.ss4.set(0)
        self.ss5.set(0)
        self.ss6.set(0)
        self.ss7.set(0)
        self.ss8.set(0)
        self.ss9.set(0)
        self.ss10.set(0)
        self.ss11.set(0)
        self.ss12.set(0)
        self.ss13.set(0)
        self.ss14.set(0)
        self.ss15.set(0)

        self.sss1.set(0)
        self.sss2.set(0)
        self.sss3.set(0)
        self.sss4.set(0)
        self.sss5.set(0)
        self.sss6.set(0)
        self.sss7.set(0)
        self.sss8.set(0)
        self.sss9.set(0)
        self.sss10.set(0)
        self.sss11.set(0)
        self.sss12.set(0)
        self.sss13.set(0)
        self.sss14.set(0)
        self.sss15.set(0)

        self.section1.set('')
        self.section2.set('')
        self.section3.set('')

        self.name.set('')
        self.phone.set('')
        self.bill.set('')

    def close(self):
        self.root.destroy()

    def save(self):
        op = messagebox.askyesno(" Save ", " Do you want save the bill ? ")
        if op > 0:
            self.bb = self.txtarea.get("1.0", END)
            f1 = open('majidsaqr' + str(self.bill.get()) + ".txt", "w", encoding="utf-8")
            f1.write(self.bb)
            f1.close()
        else:
            return

    def billl(self):

        #         self.welcome()
        if self.s1.get() != 0:
            self.txtarea.insert(END, f"\n {self.ts1}\t\t{self.s1.get()}\t\tElement1 ")

        if self.s2.get() != 0:
            self.txtarea.insert(END, f"\n {self.ts2}\t\t{self.s2.get()}\t\tElement2 ")

        if self.s3.get() != 0:
            self.txtarea.insert(END, f"\n {self.ts3}\t\t{self.s3.get()}\t\tElement3 ")

        if self.s4.get() != 0:
            self.txtarea.insert(END, f"\n {self.ts4}\t\t{self.s4.get()}\t\tElement4 ")

        if self.s5.get() != 0:
            self.txtarea.insert(END, f"\n {self.ts5}\t\t{self.s5.get()}\t\tElement5 ")

        if self.s6.get() != 0:
            self.txtarea.insert(END, f"\n {self.ts6}\t\t{self.s6.get()}\t\tElement6 ")

        if self.s7.get() != 0:
            self.txtarea.insert(END, f"\n {self.ts7}\t\t{self.s7.get()}\t\tElement7 ")

        if self.s8.get() != 0:
            self.txtarea.insert(END, f"\n {self.ts8}\t\t{self.s8.get()}\t\tElement8 ")

        if self.s9.get() != 0:
            self.txtarea.insert(END, f"\n {self.ts9}\t\t{self.s9.get()}\t\tElement9 ")

        if self.s10.get() != 0:
            self.txtarea.insert(END, f"\n {self.ts10}\t\t{self.s10.get()}\t\tElement10 ")

        if self.s11.get() != 0:
            self.txtarea.insert(END, f"\n {self.ts11}\t\t{self.s11.get()}\t\tElement11 ")

        if self.s12.get() != 0:
            self.txtarea.insert(END, f"\n {self.ts12}\t\t{self.s12.get()}\t\tElement12 ")

        if self.s13.get() != 0:
            self.txtarea.insert(END, f"\n {self.ts13}\t\t{self.s13.get()}\t\tElement13 ")

        if self.s14.get() != 0:
            self.txtarea.insert(END, f"\n {self.ts14}\t\t{self.s14.get()}\t\tElement14 ")

        if self.s15.get() != 0:
            self.txtarea.insert(END, f"\n {self.ts15}\t\t{self.s15.get()}\t\tElement15 ")

        if self.ss1.get() != 0:
            self.txtarea.insert(END, f"\n {self.tss1}\t\t{self.ss1.get()}\t\tElement1 ")

        if self.ss2.get() != 0:
            self.txtarea.insert(END, f"\n {self.tss2}\t\t{self.ss2.get()}\t\tElement2 ")

        if self.ss3.get() != 0:
            self.txtarea.insert(END, f"\n {self.tss3}\t\t{self.ss3.get()}\t\tElement3 ")

        if self.ss4.get() != 0:
            self.txtarea.insert(END, f"\n {self.tss4}\t\t{self.ss4.get()}\t\tElement4 ")

        if self.ss5.get() != 0:
            self.txtarea.insert(END, f"\n {self.tss5}\t\t{self.ss5.get()}\t\tElement5 ")

        if self.ss5.get() != 0:
            self.txtarea.insert(END, f"\n {self.tss5}\t\t{self.ss5.get()}\t\tElement5 ")

        if self.ss6.get() != 0:
            self.txtarea.insert(END, f"\n {self.tss6}\t\t{self.ss6.get()}\t\tElement6 ")

        if self.ss7.get() != 0:
            self.txtarea.insert(END, f"\n {self.tss7}\t\t{self.ss7.get()}\t\tElement7 ")

        if self.ss8.get() != 0:
            self.txtarea.insert(END, f"\n {self.tss8}\t\t{self.ss8.get()}\t\tElement8 ")

        if self.ss9.get() != 0:
            self.txtarea.insert(END, f"\n {self.tss9}\t\t{self.ss9.get()}\t\tElement9 ")

        if self.ss10.get() != 0:
            self.txtarea.insert(END, f"\n {self.tss10}\t\t{self.ss10.get()}\t\tElement10 ")

        if self.ss11.get() != 0:
            self.txtarea.insert(END, f"\n {self.tss11}\t\t{self.ss11.get()}\t\tElement11 ")

        if self.ss12.get() != 0:
            self.txtarea.insert(END, f"\n {self.tss12}\t\t{self.ss12.get()}\t\tElement12 ")

        if self.ss13.get() != 0:
            self.txtarea.insert(END, f"\n {self.tss13}\t\t{self.ss13.get()}\t\tElement13 ")

        if self.ss14.get() != 0:
            self.txtarea.insert(END, f"\n {self.tss14}\t\t{self.ss14.get()}\t\tElement14 ")

        if self.ss15.get() != 0:
            self.txtarea.insert(END, f"\n {self.tss15}\t\t{self.ss15.get()}\t\tElement15 ")

        if self.sss1.get() != 0:
            self.txtarea.insert(END, f"\n {self.tsss1}\t\t{self.sss1.get()}\t\tElement1 ")

        if self.sss2.get() != 0:
            self.txtarea.insert(END, f"\n {self.tsss2}\t\t{self.sss2.get()}\t\tElement2 ")

        if self.sss3.get() != 0:
            self.txtarea.insert(END, f"\n {self.tsss3}\t\t{self.sss3.get()}\t\tElement3 ")

        if self.sss4.get() != 0:
            self.txtarea.insert(END, f"\n {self.tsss4}\t\t{self.sss4.get()}\t\tElement4 ")

        if self.sss5.get() != 0:
            self.txtarea.insert(END, f"\n {self.tsss5}\t\t{self.sss5.get()}\t\tElement5 ")

        if self.sss6.get() != 0:
            self.txtarea.insert(END, f"\n {self.tsss6}\t\t{self.sss6.get()}\t\tElement6 ")

        if self.sss7.get() != 0:
            self.txtarea.insert(END, f"\n {self.tsss7}\t\t{self.sss7.get()}\t\tElement7 ")

        if self.sss8.get() != 0:
            self.txtarea.insert(END, f"\n {self.tsss8}\t\t{self.sss8.get()}\t\tElement8 ")

        if self.sss9.get() != 0:
            self.txtarea.insert(END, f"\n {self.tsss9}\t\t{self.sss9.get()}\t\tElement9 ")

        if self.sss10.get() != 0:
            self.txtarea.insert(END, f"\n {self.tsss10}\t\t{self.sss10.get()}\t\tElement10 ")

        if self.sss11.get() != 0:
            self.txtarea.insert(END, f"\n {self.tsss11}\t\t{self.sss11.get()}\t\tElement11 ")

        self.txtarea.insert(END, "\n.......................................")
        self.txtarea.insert(END, f"\nTotal Price $\t             {self.all}")
        self.txtarea.insert(END, "\n.......................................")
        self.save()

    # ( FUNCTIONS ADD & MIN SECTION 1)
    def addS1(self):
        value = self.s1.get()
        value = value + 1
        self.s1.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A1'] = value
        wb.save("sample_file.xlsx")

    def subS1(self):
        value = self.s1.get()
        if value > 0:
            value = value - 1
        self.s1.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A1'] = value
        wb.save("sample_file.xlsx")

    def addS2(self):
        value = self.s2.get()
        value = value + 1
        self.s2.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A2'] = value
        wb.save("sample_file.xlsx")

    def subS2(self):
        value = self.s2.get()
        if value > 0:
            value = value - 1
        self.s2.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A2'] = value
        wb.save("sample_file.xlsx")

    def addS3(self):
        value = self.s3.get()
        value = value + 1
        self.s3.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A3'] = value
        wb.save("sample_file.xlsx")

    def subS3(self):
        value = self.s3.get()
        if value > 0:
            value = value - 1
        self.s3.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A3'] = value
        wb.save("sample_file.xlsx")

    def addS4(self):
        value = self.s4.get()
        value = value + 1
        self.s4.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A4'] = value
        wb.save("sample_file.xlsx")

    def subS4(self):
        value = self.s4.get()
        if value > 0:
            value = value - 1
        self.s4.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A4'] = value
        wb.save("sample_file.xlsx")

    def addS5(self):
        value = self.s5.get()
        value = value + 1
        self.s5.set(value)

    def subS5(self):
        value = self.s5.get()
        if value > 0:
            value = value - 1
        self.s5.set(value)

    def addS6(self):
        value = self.s6.get()
        value = value + 1
        self.s6.set(value)

    def subS6(self):
        value = self.s6.get()
        if value > 0:
            value = value - 1
        self.s6.set(value)

    def addS7(self):
        value = self.s7.get()
        value = value + 1
        self.s7.set(value)

    def subS7(self):
        value = self.s7.get()
        if value > 0:
            value = value - 1
        self.s7.set(value)

    def addS8(self):
        value = self.s8.get()
        value = value + 1
        self.s8.set(value)

    def subS8(self):
        value = self.s8.get()
        if value > 0:
            value = value - 1
        self.s8.set(value)

    def addS9(self):
        value = self.s9.get()
        value = value + 1
        self.s9.set(value)

    def subS9(self):
        value = self.s9.get()
        if value > 0:
            value = value - 1
        self.s9.set(value)

    def addS10(self):
        value = self.s10.get()
        value = value + 1
        self.s10.set(value)

    def subS10(self):
        value = self.s10.get()
        if value > 0:
            value = value - 1
        self.s10.set(value)

    def addS11(self):
        value = self.s11.get()
        value = value + 1
        self.s11.set(value)

    def subS11(self):
        value = self.s11.get()
        if value > 0:
            value = value - 1
        self.s11.set(value)

    def addS12(self):
        value = self.s12.get()
        value = value + 1
        self.s12.set(value)

    def subS12(self):
        value = self.s12.get()
        if value > 0:
            value = value - 1
        self.s12.set(value)

    def addS13(self):
        value = self.s13.get()
        value = value + 1
        self.s13.set(value)

    def subS13(self):
        value = self.s13.get()
        if value > 0:
            value = value - 1
        self.s13.set(value)

    def addS14(self):
        value = self.s14.get()
        value = value + 1
        self.s14.set(value)

    def subS14(self):
        value = self.s14.get()
        if value > 0:
            value = value - 1
        self.s14.set(value)

    def addS15(self):
        value = self.s15.get()
        value = value + 1
        self.s15.set(value)

    def subS15(self):
        value = self.s15.get()
        if value > 0:
            value = value - 1
        self.s15.set(value)

    # ( FUNCTIONS ADD & MIN SECTION 2 )

    def addSS1(self):
        value = self.ss1.get()
        value = value + 1
        self.ss1.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A1'] = value
        wb.save("sample_file.xlsx")

    def subSS1(self):
        value = self.ss1.get()
        if value > 0:
            value = value - 1
        self.ss1.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A1'] = value
        wb.save("sample_file.xlsx")

    def addSS2(self):
        value = self.ss2.get()
        value = value + 1
        self.ss2.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A2'] = value
        wb.save("sample_file.xlsx")

    def subSS2(self):
        value = self.ss2.get()
        if value > 0:
            value = value - 1
        self.ss2.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A2'] = value
        wb.save("sample_file.xlsx")

    def addSS3(self):
        value = self.ss3.get()
        value = value + 1
        self.ss3.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A3'] = value
        wb.save("sample_file.xlsx")

    def subSS3(self):
        value = self.ss3.get()
        if value > 0:
            value = value - 1
        self.ss3.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A3'] = value
        wb.save("sample_file.xlsx")

    def addSS4(self):
        value = self.ss4.get()
        value = value + 1
        self.ss4.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A4'] = value
        wb.save("sample_file.xlsx")

    def subSS4(self):
        value = self.ss4.get()
        if value > 0:
            value = value - 1
        self.ss4.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A4'] = value
        wb.save("sample_file.xlsx")

    def addSS5(self):
        value = self.ss5.get()
        value = value + 1
        self.ss5.set(value)

    def subSS5(self):
        value = self.ss5.get()
        if value > 0:
            value = value - 1
        self.ss5.set(value)

    def addSS6(self):
        value = self.ss6.get()
        value = value + 1
        self.ss6.set(value)

    def subSS6(self):
        value = self.ss6.get()
        if value > 0:
            value = value - 1
        self.ss6.set(value)

    def addSS7(self):
        value = self.ss7.get()
        value = value + 1
        self.ss7.set(value)

    def subSS7(self):
        value = self.ss7.get()
        if value > 0:
            value = value - 1
        self.ss7.set(value)

    def addSS8(self):
        value = self.ss8.get()
        value = value + 1
        self.ss8.set(value)

    def subSS8(self):
        value = self.ss8.get()
        if value > 0:
            value = value - 1
        self.ss8.set(value)

    def addSS9(self):
        value = self.ss9.get()
        value = value + 1
        self.ss9.set(value)

    def subSS9(self):
        value = self.ss9.get()
        if value > 0:
            value = value - 1
        self.ss9.set(value)

    def addSS10(self):
        value = self.ss10.get()
        value = value + 1
        self.ss10.set(value)

    def subSS10(self):
        value = self.ss10.get()
        if value > 0:
            value = value - 1
        self.ss10.set(value)

    def addSS11(self):
        value = self.ss11.get()
        value = value + 1
        self.ss11.set(value)

    def subSS11(self):
        value = self.ss11.get()
        if value > 0:
            value = value - 1
        self.ss11.set(value)

    def addSS12(self):
        value = self.ss12.get()
        value = value + 1
        self.ss12.set(value)

    def subSS12(self):
        value = self.ss12.get()
        if value > 0:
            value = value - 1
        self.ss12.set(value)

    def addSS13(self):
        value = self.ss13.get()
        value = value + 1
        self.ss13.set(value)

    def subSS13(self):
        value = self.ss13.get()
        if value > 0:
            value = value - 1
        self.ss13.set(value)

    def addSS14(self):
        value = self.ss14.get()
        value = value + 1
        self.ss14.set(value)

    def subSS14(self):
        value = self.ss14.get()
        if value > 0:
            value = value - 1
        self.ss14.set(value)

    def addSS15(self):
        value = self.ss15.get()
        value = value + 1
        self.ss15.set(value)

    def subSS15(self):
        value = self.s15.get()
        if value > 0:
            value = value - 1
        self.ss15.set(value)

    # ( FUNCTIONS ADD & MIN SECTION 3 )

    def addSSS1(self):
        value = self.sss1.get()
        value = value + 1
        self.sss1.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A1'] = value
        wb.save("sample_file.xlsx")

    def subSSS1(self):
        value = self.sss1.get()
        if value > 0:
            value = value - 1
        self.sss1.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A1'] = value
        wb.save("sample_file.xlsx")

    def addSSS2(self):
        value = self.sss2.get()
        value = value + 1
        self.sss2.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A2'] = value
        wb.save("sample_file.xlsx")

    def subSSS2(self):
        value = self.sss2.get()
        if value > 0:
            value = value - 1
        self.sss2.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A2'] = value
        wb.save("sample_file.xlsx")

    def addSSS3(self):
        value = self.sss3.get()
        value = value + 1
        self.sss3.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A3'] = value
        wb.save("sample_file.xlsx")

    def subSSS3(self):
        value = self.sss3.get()
        if value > 0:
            value = value - 1
        self.sss3.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A3'] = value
        wb.save("sample_file.xlsx")

    def addSSS4(self):
        value = self.sss4.get()
        value = value + 1
        self.sss4.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A4'] = value
        wb.save("sample_file.xlsx")

    def subSSS4(self):
        value = self.sss4.get()
        if value > 0:
            value = value - 1
        self.sss4.set(value)
        wb = load_workbook("sample_file.xlsx")
        sheet = wb.active

        sheet['A4'] = value
        wb.save("sample_file.xlsx")

    def addSSS5(self):
        value = self.sss5.get()
        value = value + 1
        self.sss5.set(value)

    def subSSS5(self):
        value = self.sss5.get()
        if value > 0:
            value = value - 1
        self.sss5.set(value)

    def addSSS6(self):
        value = self.sss6.get()
        value = value + 1
        self.sss6.set(value)

    def subSSS6(self):
        value = self.sss6.get()
        if value > 0:
            value = value - 1
        self.sss6.set(value)

    def addSSS7(self):
        value = self.sss7.get()
        value = value + 1
        self.sss7.set(value)

    def subSSS7(self):
        value = self.sss7.get()
        if value > 0:
            value = value - 1
        self.sss7.set(value)

    def addSSS8(self):
        value = self.sss8.get()
        value = value + 1
        self.sss8.set(value)

    def subSSS8(self):
        value = self.sss8.get()
        if value > 0:
            value = value - 1
        self.sss8.set(value)

    def addSSS9(self):
        value = self.sss9.get()
        value = value + 1
        self.sss9.set(value)

    def subSSS9(self):
        value = self.sss9.get()
        if value > 0:
            value = value - 1
        self.sss9.set(value)

    def addSSS10(self):
        value = self.sss10.get()
        value = value + 1
        self.sss10.set(value)

    def subSSS10(self):
        value = self.sss10.get()
        if value > 0:
            value = value - 1
        self.sss10.set(value)

    def addSSS11(self):
        value = self.sss11.get()
        value = value + 1
        self.sss11.set(value)

    def subSSS11(self):
        value = self.sss11.get()
        if value > 0:
            value = value - 1
        self.sss11.set(value)

root = Tk()
window = supermarket(root)
root.mainloop()


import os
from PIL import Image

def makedir(path):
    if not os.path.exists(path):
        os.mkdir(path)
        print("The directory \"" + path + "\" creates success.")
    else:
        print("The directory \"" + path + "\" has already existed.")

base_path = "base"
mask_path = "mask"
makedir(base_path)
makedir(mask_path)

n = int(input("Please enter n, n^2 is the number of the pictures."))
print("Please put n^2 pictures to the forder \"base\".")
print("Please put one picture to the forder \"mask\".")
os.system("pause")
width = int(input("Please enter the width of the final picture."))
height = int(input("Please enter the height of the final picture."))
transparency = int(input("Please enter the transparency% of the mask."))

base_pictures = []
for root, dirs, files in os.walk(os.getcwd()+"\\"+base_path):
    for file in files:
        base_pictures.append(os.path.join(root, file))

num = 0
base = Image.new("RGBA", (width, height))
for i in range(0, n):

    for j in range(0, n):
        picture = Image.open(base_pictures[num])
        temp = picture.resize((int(width/n), int(height/n)))
        location = (int(i * width / n), int(j * height / n))
        base.paste(temp, location)
        num += 1

    if num >= len(base_pictures):
        break

    if num >= n*n:
        break

for root, files in os.walk(os.getcwd()+"\\"+mask_path):
    for file in files:
        mask_picture = Image.open(mask_path + "\\" + file)

mask = mask_picture.resize((width, height))
mask.putalpha(int(transparency/100 * 255))

result = Image.alpha_composite(base, mask)
result.save("result.png")