import os
import base64
import requests
import json
import shutil
import time
from tqdm import tqdm
import numpy as np
np.random.seed()
url = "http://172.20.16.97:9015/aadhaarmaskws/aadhaarmask/maskapi"
data_dir = r"F:\task_17\2024-11-14_sbi_Documents\2024-11-14_sbi_Documents/"
save_dir = r"F:\task_17\2024-11-14_sbi_Documents_masked/"
start = time.time()
for root, dirs, files in os.walk(data_dir):
for filename in tqdm(files):
try:
fullPath = os.path.join(root, filename)
print(f"Processing file: {fullPath}")
file_type = filename.split('.')[-1]
print(f"File type is {file_type}")
code
Assistant
# Reading the file and encoding it to Base64
with open(fullPath, 'rb') as file_text:
file_read = file_text.read()
base64file = base64.b64encode(file_read)
payload = json.dumps({
"app_no": "manu",
"app_type": "manu",
"security_key": "",
"filename": str(filename),
"filedata": str(base64file, encoding='utf-8')
})
headers = {
'Authorization': 'Token 9869d49a7875f7b2c4b72c5bc6cf45c322f8ff8f',
'Content-Type': 'application/json'
}
print("I am here 1")
try:
response = requests.request("POST", url, headers=headers, data=payload).json()
print("I am here", response)
# Determine where to save the file
relative_path = os.path.relpath(fullPath, data_dir)
save_full_path = os.path.join(save_dir, relative_path)
save_folder = os.path.dirname(save_full_path)
# Create the subdirectory in save_dir if it does not exist
if not os.path.exists(save_folder):
os.makedirs(save_folder)
# If the response status is "P", save the processed (masked) file
if response.get('status') == 'P':
masked_file = response.get('result')
if file_type == "pdf":
with open(save_full_path, "wb") as pdf_file:
pdf_file.write(base64.b64decode(masked_file))
else:
with open(save_full_path, "wb") as img_file:
img_file.write(base64.b64decode(masked_file))
print(f"Masked file saved at {save_full_path}")
else:
# If status is not "P", save the original file as it is
shutil.copy2(fullPath, save_full_path)
print(f"Original file saved at {save_full_path}")
# After processing, remove the original file from data_dir
os.remove(fullPath)
print(f"Original file {fullPath} removed from data_dir")
except:
relative_path = os.path.relpath(fullPath, data_dir)
save_full_path = os.path.join(save_dir, relative_path)
save_folder = os.path.dirname(save_full_path)
shutil.copy2(fullPath, save_full_path)
print(f"Original file saved at {save_full_path}")
os.remove(fullPath)
print(f"Original file {fullPath} removed from data_dir")
except Exception as e:
print("EXCEPTION IN OUTER BLOCK")
print(e)
cost_time = (time.time() - start)
print("API hit cost time: {:.2f}s".format(cost_time))
hii i want to modify the code and i want to check on how much time each file takes to process and mention that in execl file can u pleaee modify the logic
Certainly! To measure how long each file takes to process and save that information into an Excel file, we can use the openpyxl library to create and manipulate Excel files. If you haven't already installed it, you can do so with pip install openpyxl.
The modified code below will time each file processing operation and write the results to an Excel file that will include the filename and the processing time taken for each file.
Here’s how to achieve that:
python
import os
import base64
import requests
import json
import shutil
import time
from tqdm import tqdm
from openpyxl import Workbook
# Constants
url = "http://172.20.16.97:9015/aadhaarmaskws/aadhaarmask/maskapi"
data_dir = r"F:\task_17\2024-11-14_sbi_Documents\2024-11-14_sbi_Documents/"
save_dir = r"F:\task_17\2024-11-14_sbi_Documents_masked/"
excel_file_path = r"F:\task_17\processing_time.xlsx"
# Create an Excel workbook and add a worksheet
workbook = Workbook()
sheet = workbook.active
sheet.title = "Processing Times"
sheet.append(["Filename", "Processing Time (s)"])
start = time.time()
for root, dirs, files in os.walk(data_dir):
for filename in tqdm(files):
file_start_time = time.time() # Start the timer for the file
try:
fullPath = os.path.join(root, filename)
print(f"Processing file: {fullPath}")
file_type = filename.split('.')[-1]
print(f"File type is {file_type}")
# Reading the file and encoding it to Base64
with open(fullPath, 'rb') as file_text:
file_read = file_text.read()
base64file = base64.b64encode(file_read)
payload = json.dumps({
"app_no": "manu",
"app_type": "manu",
"security_key": "",
"filename": str(filename),
"filedata": str(base64file, encoding='utf-8')
})
headers = {
'Authorization': 'Token 9869d49a7875f7b2c4b72c5bc6cf45c322f8ff8f',
'Content-Type': 'application/json'
}
print("Sending request...")
try:
response = requests.post(url, headers=headers, data=payload).json()
print("Received response:", response)
# Determine where to save the file
relative_path = os.path.relpath(fullPath, data_dir)
save_full_path = os.path.join(save_dir, relative_path)
save_folder = os.path.dirname(save_full_path)
# Create the subdirectory in save_dir if it does not exist
if not os.path.exists(save_folder):
os.makedirs(save_folder)
# If the response status is "P", save the processed (masked) file
if response.get('status') == 'P':
masked_file = response.get('result')
with open(save_full_path, "wb") as output_file:
output_file.write(base64.b64decode(masked_file))
print(f"Masked file saved at {save_full_path}")
else:
# If status is not "P", save the original file
shutil.copy2(fullPath, save_full_path)
print(f"Original file saved at {save_full_path}")
# After processing, remove the original file from data_dir
os.remove(fullPath)
print(f"Original file {fullPath} removed from data_dir")
except Exception as e:
print("Error during API request:", e)
# Save the original file due to error
shutil.copy2(fullPath, save_full_path)
os.remove(fullPath)
print(f"Original file saved at {save_full_path} and removed from data_dir.")
except Exception as e:
print("EXCEPTION IN OUTER BLOCK")
print(e)
# Calculate processing time and log it in the Excel file
processing_time = time.time() - file_start_time
sheet.append([filename, processing_time])
print(f"Processed {filename} in {processing_time:.2f}s")
# Save the Excel file
workbook.save(excel_file_path)
# Final processing time for all files
cost_time = (time.time() - start)
print("Total API hit cost time: {:.2f}s".format(cost_time))
Key Changes:
Excel File Creation: A new Excel file is created to store the processing times for each file.
Timing Each File: A timer is started before the processing of each file and stopped afterward to calculate the total processing time for that file.
Logging Processing Times: After processing each file, we append the filename and its processing time to the Excel sheet.
Error Handling: Added additional print statements to clarify where in the process an error occurs.
Please ensure you have write permissions for the path where the Excel file will be saved.