Spaces:
Runtime error

File size: 3,048 Bytes
dd9d069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import os
import pandas as pd

DATA_LOCATION = "data/emails_data"

def save_data_to_csv(data, filename):
    """ Saves data as a CSV file """
    if ((isinstance(data, list) and len(data) == 0)):  # Check if list is not empty
        update = f"{filename}: No data to save"
        print(update)
        return update
    os.makedirs(DATA_LOCATION, exist_ok=True)  # exist_ok=True avoids permission errors if folder exists
    filepath = os.path.join(DATA_LOCATION, filename)
    df = data
    if not isinstance(data,pd.DataFrame):
        df = pd.DataFrame(data)
    df.to_csv(filepath, index=False)
    print(f"Data saved to {filename}")
    return filepath

def save_data_to_excel(data_dict, filename):
    """ Saves data into multiple sheets within an Excel file """
    if not data_dict or not isinstance(data_dict, dict):
        update = f"{filename}: No data to save or invalid format"
        print(update)
        return update
    
    os.makedirs(DATA_LOCATION, exist_ok=True)  # Ensure the directory exists
    filepath = os.path.join(DATA_LOCATION, filename)
    
    with pd.ExcelWriter(filepath, engine='xlsxwriter') as writer:
        for sheet_name, data in data_dict.items():
            if isinstance(data, list):  # Check if the data is a list and convert to DataFrame
                df = pd.DataFrame(data)
            elif isinstance(data, pd.DataFrame):  # If it's already a DataFrame, use it directly
                df = data
            else:
                print(f"Invalid data format in sheet: {sheet_name}")
                continue  # Skip this iteration if the data format is neither list nor DataFrame

            if not df.empty:  # Check if the df is not empty
                if len(sheet_name) > 31:
                    original_sheet_name = sheet_name
                    sheet_name = sheet_name[:31]  # Truncate to 31 characters
                    print(f"Sheet name '{original_sheet_name}' truncated to '{sheet_name}' to meet Excel's limitations.")
                
                df.to_excel(writer, sheet_name=sheet_name, index=False)
            else:
                print(f"No data to save in sheet: {sheet_name}")
    
    print(f"Data saved to {filepath}")
    return filepath

# def get_csv_filenames():
#     """ Fetches a list of CSV filenames from the 'data/emails_data' folder """
#     csv_files = sorted(os.listdir(DATA_LOCATION), reverse=True)
#     return [f for f in csv_files if f.lower().endswith('.csv')]  # Filter for CSV files

# def get_email_summary(filename):
#     """ Fetches email summaries from all CSV files in 'data/emails_data' folder """
#     try:
#         filepath = os.path.join(DATA_LOCATION, filename)
#         df = pd.read_csv(filepath)
#         sender_counts = df['Sender'].value_counts().reset_index(name='emailCount')
#         sender_counts = sender_counts.sort_values(by='emailCount', ascending=False)
#         return sender_counts.to_dict(orient='records')
#     except Exception as error:
#         return f"Error processing file '{filename}': {error}"