tahamajs/OS / Files /CAs /CA2 /code1 /code.c
tahamajs's picture
download
raw
4.2 kB
import os
import multiprocessing
from multiprocessing import Pipe, Process
import csv
from collections import defaultdict
# Directory containing warehouse data files
WAREHOUSE_DIR = 'warehouses/'
def map_process(file_path, conn):
"""
Map function to process a single warehouse file.
Calculates total inventory and profit per item.
Parameters:
- file_path: Path to the warehouse data file.
- conn: Connection object for sending data back to the main process.
"""
inventory = defaultdict(int)
profit = defaultdict(int)
try:
with open(file_path, 'r') as f:
reader = csv.reader(f)
for row in reader:
if len(row) != 4:
continue # Skip malformed lines
item, quantity, value, transaction = row
quantity = int(quantity)
value = int(value)
if transaction.lower() == 'input':
inventory[item] += quantity
elif transaction.lower() == 'output':
inventory[item] -= quantity
profit[item] += quantity * value
except Exception as e:
print(f"Error processing file {file_path}: {e}")
# Send the result back to the main process
conn.send({'inventory': dict(inventory), 'profit': dict(profit)})
conn.close()
def reduce_phase(mapped_data):
"""
Reduce function to aggregate data from all Map processes.
Parameters:
- mapped_data: List of dictionaries containing 'inventory' and 'profit'.
Returns:
- Aggregated inventory and profit dictionaries.
"""
total_inventory = defaultdict(int)
total_profit = defaultdict(int)
for data in mapped_data:
for item, qty in data['inventory'].items():
total_inventory[item] += qty
for item, prof in data['profit'].items():
total_profit[item] += prof
return dict(total_inventory), dict(total_profit)
def main():
"""
Main function to orchestrate the Map-Reduce process.
"""
if not os.path.exists(WAREHOUSE_DIR):
print(f"Warehouse directory '{WAREHOUSE_DIR}' does not exist.")
return
# List all CSV files in the warehouse directory
warehouse_files = [os.path.join(WAREHOUSE_DIR, f) for f in os.listdir(WAREHOUSE_DIR) if f.endswith('.csv')]
if not warehouse_files:
print(f"No warehouse data files found in '{WAREHOUSE_DIR}'.")
return
processes = []
parent_conns = []
# Start Map processes
for file_path in warehouse_files:
parent_conn, child_conn = Pipe()
p = Process(target=map_process, args=(file_path, child_conn))
p.start()
processes.append(p)
parent_conns.append(parent_conn)
# Collect results from Map processes
mapped_data = []
for conn in parent_conns:
data = conn.recv()
mapped_data.append(data)
conn.close()
# Ensure all Map processes have finished
for p in processes:
p.join()
# Perform Reduce phase
total_inventory, total_profit = reduce_phase(mapped_data)
# Generate Final Report
print("\\n=== Inventory and Profit Report ===\\n")
print(f"{'Item':<15}{'Total Inventory':<20}{'Total Profit':<15}")
print("-" * 50)
for item in sorted(total_inventory.keys()):
inventory = total_inventory[item]
profit = total_profit.get(item, 0)
print(f"{item:<15}{inventory:<20}{profit:<15}")
print("\\nReport generation completed.")
if __name__ == '__main__':
# Example: Create the warehouses directory and sample files if they don't exist
if not os.path.exists(WAREHOUSE_DIR):
os.makedirs(WAREHOUSE_DIR)
# Sample data for Tehran warehouse
with open(os.path.join(WAREHOUSE_DIR, 'tehran.csv'), 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['berenj', '100', '30000', 'input'])
writer.writerow(['roghan', '50', '50000', 'output'])
writer.writerow(['shekar', '80', '20000', 'input'])
writer.writerow(['makaroni', '60', '15000', 'input'])
# Add more sample files as needed
main()

Xet Storage Details

Size:
4.2 kB
·
Xet hash:
e5d6901817fd39429f80e9092340399755a99fb8b755b3162dcc1f8b33fae4be

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.