Wednesday, 8 January 2025

How to download any attachment from GMail

Okay, on the back of my earlier post today, I couldn't help myself but continue to tinker with Google Apps script platform - by taking the automation further. This is the power of AI tools - imagine how much productivity and efficiency improvements can be unlocked to anyone, especially for the small business owner, or your own personal workflow automations -- automating manual back-office processes without relying on an IT person to support you!? 

Sure I spent about four hours playing around - the process wasn't perfect. It can be tricky making changes, the tendency to keep adding new features, sometimes breaking everything and starting over again. ChatGPT Canvas is still a work in progress, but it's no stretch of imagination to expect future enhancements with a fully integrated developer environment, deployment with version control, rollbacks, etc. Anyone with a little bit of technical curiosity can start to unlock personal productivity improvements by investing some time in learning and experimentation.

Here's a sample of the tool:


Here's the write up from ChatGPT using Canvas:

How to Build a Google Apps Script to Download Gmail Attachments

Downloading Gmail attachments automatically can save time and improve productivity. In this guide, we'll walk through building a Google Apps Script to dynamically fetch email senders, process their emails, and save attachments directly to Google Drive.

This guide assumes basic knowledge of Google Apps Script and JavaScript. Let’s dive in!


Step 1: Set Up Your Google Apps Script Project

  1. Go to Google Apps Script.
  2. Click New Project to create a blank script project.
  3. Rename the project to something meaningful, like Gmail Attachment Downloader.

Step 2: Write the Backend Script (Code.gs)

The backend script handles:

  • Fetching Gmail threads and senders.
  • Processing selected emails.
  • Saving attachments to Google Drive.

Here’s the Code.gs file:

function doGet() {
  return HtmlService.createHtmlOutputFromFile('SenderSelection').setTitle('Select Sender');
}

function getSendersChunk(startIndex, chunkSize) {
  var threads = GmailApp.getInboxThreads(startIndex, chunkSize);
  Logger.log(`Fetched ${threads.length} threads starting from index ${startIndex}.`);

  var senders = new Set();
  threads.forEach(function (thread) {
    var messages = thread.getMessages();
    messages.forEach(function (message) {
      senders.add(message.getFrom());
    });
  });

  return Array.from(senders).sort(); // Return sorted unique senders
}

function getTotalThreads() {
  return GmailApp.getInboxThreads().length;
}

function processSelectedSender(senderEmail) {
  var threads = GmailApp.search('from:' + senderEmail);
  var totalEmails = threads.length;

  var folderName = senderEmail.replace(/[<>:"/\|?*]/g, '_'); // Sanitize folder name
  var dateSuffix = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy-MM-dd');
  var folder = DriveApp.createFolder(folderName + "_" + dateSuffix);
  var logMessages = [`Created folder: ${folder.getName()}`, `Found ${totalEmails} emails from sender: ${senderEmail}`];

  threads.forEach(function (thread, threadIndex) {
    var messages = thread.getMessages();
    messages.forEach(function (message, messageIndex) {
      var subject = message.getSubject();
      logMessages.push(`Processing email ${threadIndex + 1}/${totalEmails}: "${subject}"`);

      var attachments = message.getAttachments();
      attachments.forEach(function (attachment) {
        var fileName = attachment.getName();
        var extensionIndex = fileName.lastIndexOf(".");
        var baseName = fileName.substring(0, extensionIndex);
        var extension = fileName.substring(extensionIndex);
        var timestampedFileName = baseName + "_" + new Date().getTime() + extension;

        try {
          folder.createFile(attachment).setName(timestampedFileName);
          Logger.log(`Saved attachment: ${timestampedFileName}`);
        } catch (e) {
          Logger.log(`Error saving attachment: ${e.message}`);
        }
      });
    });
  });

  logMessages.push(`Processing complete for sender: ${senderEmail}`);
  return logMessages; // Return all log messages to the frontend
}

Step 3: Create the Frontend (SenderSelection.html)

The frontend displays a dropdown list of senders and allows the user to process selected emails. Here's the SenderSelection.html file:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <style>
      body {
        font-family: Arial, sans-serif;
        margin: 20px;
      }
      label, select, button {
        font-size: 14px;
      }
      select {
        width: 100%;
        margin-bottom: 10px;
      }
      #log {
        margin-top: 20px;
        padding: 10px;
        border: 1px solid #ccc;
        background: #f9f9f9;
        height: 300px;
        overflow-y: auto;
        font-size: 12px;
        white-space: pre-wrap;
      }
      .progress {
        font-weight: bold;
        margin-top: 10px;
      }
    </style>
  </head>
  <body>
    <h3>Select a Sender</h3>
    <form id="senderForm">
      <label for="sender">Senders:</label>
      <select id="sender" name="sender">
        <!-- Options will be populated dynamically -->
      </select>
      <button type="button" onclick="submitSender()">Process</button>
    </form>

    <div id="log">Logs will appear here...</div>
    <div id="progress" class="progress"></div>

    <script>
      let startIndex = 0;
      const chunkSize = 50;
      let totalThreads = 0;

      function initialize() {
        google.script.run.withSuccessHandler(setTotalThreads).getTotalThreads();
      }

      function setTotalThreads(total) {
        totalThreads = total;
        addLog(`Total threads in Gmail: ${totalThreads}`);
        loadNextChunk();
      }

      function loadNextChunk() {
        if (startIndex >= totalThreads) {
          addLog("All senders loaded.");
          return;
        }

        addLog(`Loading senders from threads ${startIndex + 1} to ${startIndex + chunkSize}...`);
        google.script.run.withSuccessHandler(populateSenders).getSendersChunk(startIndex, chunkSize);
        startIndex += chunkSize;
      }

      function populateSenders(senders) {
        const senderDropdown = document.getElementById('sender');
        senders.forEach(function (sender) {
          const option = document.createElement('option');
          option.value = sender;
          option.textContent = sender;
          senderDropdown.appendChild(option);
        });

        loadNextChunk();
      }

      function submitSender() {
        const selectedSender = document.getElementById('sender').value;
        if (selectedSender) {
          clearLogs();
          setProgress(`Processing emails for: ${selectedSender}`);
          google.script.run.withSuccessHandler(displayLogs).processSelectedSender(selectedSender);
        } else {
          alert('Please select a sender.');
        }
      }

      function displayLogs(logMessages) {
        logMessages.forEach(addLog);
        setProgress("Processing complete.");
      }

      function addLog(message) {
        const logDiv = document.getElementById('log');
        logDiv.textContent += message + "\n";
        logDiv.scrollTop = logDiv.scrollHeight;
      }

      function clearLogs() {
        document.getElementById('log').textContent = "";
        setProgress("");
      }

      function setProgress(message) {
        document.getElementById('progress').textContent = message;
      }

      window.onload = initialize;
    </script>
  </body>
</html>

Step 4: Deploy the Web App

  1. Go to Deploy > New Deployment.
  2. Choose Web App.
  3. Configure:
    • Execute as: Me.
    • Who has access: Only Me.
  4. Deploy and copy the deployment URL.

Step 5: Test the App

  1. Open the deployment URL in your browser.
  2. Wait for senders to load dynamically.
  3. Select a sender from the dropdown.
  4. Click Process.
  5. Check the logs in the "Logs" section for real-time updates on email processing and attachment saving.
  6. Validate in Google Drive:
    • Go to your Google Drive.
    • Check for a newly created folder named after the sender's email address with a date suffix.
    • Ensure that all attachments from the processed emails appear in this folder.

Key Features

  • Dynamic Sender Loading: Senders are loaded in chunks for responsiveness.
  • Real-Time Logs: Displays progress for email and attachment processing. Note: Currently, the logs only appear once all emails are processed. This is an opportunity to enhance the script for real-time updates.
  • Automatic Folder Creation: Creates a unique folder in Google Drive for each sender's attachments.
  • Filename Uniqueness: Attachments are saved with a timestamp appended to the original filename, ensuring no files are overwritten during the saving process.

Potential Feature Enhancements

  1. Real-Time Logging:

    • Update the script to send logs incrementally to the frontend as each email is processed, instead of batching logs after completion.
  2. Progress Bar Integration:

    • Add a progress bar in the frontend to visually indicate the percentage of emails processed.
  3. Advanced Filters:

    • Allow users to apply filters such as date ranges, subject keywords, or labels to narrow down email selection.
  4. Attachment Size Limit:

    • Introduce a feature to skip downloading large attachments beyond a specified size limit.
  5. Retry Mechanism:

    • Implement error handling to retry saving attachments in case of temporary failures (e.g., Drive quota issues).
  6. Specify File Extensions:

    • Add an option to download only specific file types (e.g., PDF, DOCX) by specifying file extensions.
  7. Search by Google Contact Emails:

    • Allow users to search emails from their Google contacts directly for better targeting.
  8. Google Sheet Integration:

    • Create a Google Sheet to log the email subject, sender, and a link to the saved file in Google Drive for better tracking and reporting.
  9. Real-Time Logging:

    • Update the script to send logs incrementally to the frontend as each email is processed, instead of batching logs after completion.
  10. Progress Bar Integration:

    • Add a progress bar in the frontend to visually indicate the percentage of emails processed.
  11. Advanced Filters:

    • Allow users to apply filters such as date ranges, subject keywords, or labels to narrow down email selection.
  12. Attachment Size Limit:

    • Introduce a feature to skip downloading large attachments beyond a specified size limit.
  13. Retry Mechanism:

    • Implement error handling to retry saving attachments in case of temporary failures (e.g., Drive quota issues).

With this guide, you can easily automate the task of downloading Gmail attachments to Google Drive. Customize it further based on your needs, and streamline your email management!

How AI helped me automate downloading attachments in GMail

So today I wanted to download my entire history of municipality statements and use some AI tools to build some analytical dashboards for insights. The first thing to automate was downloading attachments from GMail. Instead of manually downloading one-by-one, or manually using a filter rule on GMail, I wanted to test ChatGPT and Gemini to see if it could provide a Google Workspace Appscript to meet my needs.

So Gemini was OKAY - I'm using Gemini Advanced 1.5 Pro with Advanced research. Interesting, it took the prompt "Help me with a google script or query in gmail that I can use for finding all emails from a specified email sender, downloading the attachments from each email, to a specified folder". Gemini then went along with doing the research, then provided the code. Unfortunately, the code didn't work, even after a few tries - maybe it was a Google drive sync issue - but Gemini was stuck on maintaining its response on the nature of the exception ("either an auth issue" or "folder does not exist"). 

So I resorted to ChatGPT 4-Turbo, created a project with these instructions, and used the same prompt and included the original code from Gemini "Act as an expert software engineer to build a google appscript for downloading attachments for all emails from a specific sender. The script needs to work flawlessly from within the Google Apps Script console. I wrote the following code - but the script does not work. I'm getting an Exception: Unexpected error while getting the method or property getFolderById on object DriveApp"

Guess what? ChatGPT nailed it on first try, even added enough logging for tracing! Here's the code. Read the report from Gemini, as this is an example of how content can be generated by AI, and it's only going to get better.

function downloadAttachmentsFromSender() {
// Replace with the email address of the sender.
var senderEmail = '[enter email here]';

// Replace with the ID or intended name of the folder in Google Drive.
var folderName = '[name of folder]'; // Base name for the folder

// Variable to store the target folder
var folder;

try {
// Verify Drive API is working
DriveApp.getFolders();
} catch (e) {
Logger.log("Please authorize the script to access your Drive.");
return; // Exit if Drive access is not authorized
}

// Check if the folder exists
var folders = DriveApp.getFoldersByName(folderName);
if (folders.hasNext()) {
folder = folders.next();
Logger.log("Using existing folder: " + folder.getName());
} else {
// Create a new folder with the current date appended
var dateSuffix = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy-MM-dd');
var newFolderName = folderName + "_" + dateSuffix;
folder = DriveApp.createFolder(newFolderName);
Logger.log("Created new folder: " + newFolderName);
}

// Search for emails from the specified sender.
var threads;
try {
threads = GmailApp.search('from:' + senderEmail);
Logger.log("Found " + threads.length + " threads from sender: " + senderEmail);
} catch (e) {
Logger.log("Error searching for emails: " + e.message);
return; // Exit if Gmail search fails
}

// Iterate through each email thread.
threads.forEach(function (thread) {
var messages = thread.getMessages();

messages.forEach(function (message) {
var attachments = message.getAttachments();

attachments.forEach(function (attachment) {
// Extract the original file extension
var fileName = attachment.getName();
var fileExtension = fileName.substring(fileName.lastIndexOf("."));

// Create the new filename with timestamp and original extension
var newFileName = fileName.substring(0, fileName.lastIndexOf(".")) +
"_" + new Date().getTime() + fileExtension;

try {
folder.createFile(attachment).setName(newFileName);
Logger.log("Saved attachment: " + newFileName);
} catch (e) {
Logger.log("Error saving attachment: " + e.message);
}
});
});
});

Logger.log("Process complete.");
}

Anyway, I now have a repeatable way to extract attachments from emails in GMail, and now you can too.

Monday, 6 January 2025

Where did my time go in 2024? Sharing my 2024 Personametry results.

It's that time of year again to share my time tracking analysis for 2024. The visuals should be self explanatory and nothing surprising. 2024 was the year my professional work stream dominated, but not completely. I did also index on spending more time with family (at the expense of 1:1 time as a husband), and also spent much time on my own "me time" primarily focused on experimenting with AI tools. I maintained previous levels of spiritual hours, back to 2022 norms since 2023 was an outlier (pilgrimage to Makkah was the highlight of 2023). My health and fitness took a severe knock and is on a downwards trend since 2021. 2021 was the year I made big changes impacting personal and professional streams: Relocated to a new city (Cape Town) leaving friends and family behind in Johannesburg, starting a new job in a new company in a new domain -- I'm now four years into this transition, and I'm not pleased with the downwards trends in my personal streams. 2025 will need to be a year of intentional change in managing my work time, setting firmer boundaries, and finding a solution to working late nights, weekends, and limiting the streaks of long work hours. 2024 reached the peak in my work hours since starting time tracking in 2016, that's almost 10 years of time tracking! In the last four years, since starting my new job in 2021, the work hours are trending upwards (in 2022 I made adjustments to reduce work hours with some success), only to rebound higher in 2023, and much higher in 2024. In a future post, I will share the challenges of working for  a global high-tech giant like Amazon AWS from South Africa and the impact on personal time - it has been, and continues to be, the biggest challenge in maintaining my professional "happiness", especially when it comes to maintaining a regular "start day" and "end day" routines and rituals.

Overview since 2018
Here's the summary dashboard of my time spent in my personas since 2018:


What's my workflow for tracking all this data?
Nothing much has changed since I started my experiment back in 2016. I use Harvest for tracking my personal and professional streams. I use a free account, with one major project called "RAGE Time tracking". Tasks are related to my personas. I track my time from the minute I wake up till I go to sleep. Throughout the day, I switch between tasks, making sure I don't track my personal time as work time, including lunch breaks. The hours logged do track closely to 24 hours/day, for the whole year, with a negligible margin of error that's within reasonable tolerance (I'm still human!). The idea is to regularly inspect where my time is being spent, and make adjustments according to my prioritized streams. 2024 unfortunately wasn't my best year in reaching a harmony-state, something I'm not pleased about. The data helps me make sense of how my life is transforming, triggering moments of reflection for adapting or at times, just general acceptance of my current reality, it is what it is -- forcing me to make sense of my aspirations to perhaps re-calibrate (for areas where I have full agency to control and influence).

How has my workflow for insights generation changed over time - are genAI tools of any help?
In the early years, I used Excel as my main source of data insights. Later I moved over to Amazon QuickSight. I still use QuickSight to generate my analysis and dashboards, as I have a few transformations with calculated fields. I then export the Quicksight data tables as Excel file as the source data set for AI tools. Quicksight too, is a little quirky with ingesting new data, maintaining the integrity of calculated fields and sometimes data gets corrupted when updating its splice models. I spent a good few hours debugging failures in data alignment, missing rows due to errors in calculated fields (that should have "just worked").  I use a free account, so I'm unable to use any of the AI "Amazon Q" features - ideally, I'm expecting an interactive analysis/dashboard AI assistant that I can have a conversation with. Alas, there is no way to share or embed QuickSight dashboards openly, embedding QuickSight dashboards in blog posts would be cool.

Anyway, with the advent of ChatGPT, in the last two years, I started integrating AI data analysis. I spent the last few days with ChatGPT - suffice it to say, I'm not that impressed by ChatGPT's Data Analyst capability. Nothing much has improved since the last year. At least it can understand large datasets in Excel or CSV format which is cool, something that Claude, Gemini or NotebookLM don't currently support. 

ChatGPT's "Data Analyst" does a decent job performing exploratory data analysis, was able to infer what my dataset was largely about without me providing clues or guiding info. The biggest problem I encountered was loss of context, loss of memory, and complete loss of the data's runtime environment. I had to repeatedly reload the dataset because ChatGPT "lost the data", then re-coax it to understand the data fields. It also hallucinated and made simple mistakes calculating aggregated results. It got simple math wrong. At times, I had to specify in detail how to use the data fields to generate the insights I asked for. This was surprising as I had a much better experience on the model from a year ago. I'm using the latest 4o model, being a ChatGPT Plus subscriber. I feel that OpenAI team should just kill the Data Analyst as a separate feature and promote the Canvas Projects capability going forward.

On ditching the built-in "Data Analyst", I switched to the latest Projects capability in ChatGPT. I shared my dataset as project files, included all my blog posts on Personametry and RAGE as context data, and provided fine tuned instructions for the project as data scientist responsible for producing business intelligence reporting. I had a much much better experience using ChatGPT projects than Data Analyst - however - I still ran into issues with hallucination, over confidence in the AI's interpretation of data and calculated results. AI is still far from being a trusted source of business intelligence as far as I'm concerned. You need to take time to manually build your own reports and analysis, like the way I use Quicksight -- and then test the AI generates the same results. I've spent hours on this over the last few days - yes, it was a little frustrating - but nevertheless insightful. The more time I spend playing around with these tools, the more I am amazed at the potential power and future disruption in this space - and at the same time, the more I gain some comfort that there is still a long journey ahead. For my simple data set of hours logged by task, the AI doesn't perform 100% on first shot -- so for big businesses out there, don't go firing your business analysts, BI engineers anytime soon, thinking GenAI will replace these roles... IMHO, we are at least another 2 years away from maturing, if not, more. A key input is validation - you would need to generate reference test cases to validate all the metrics compute correctly to gain trust in AI-generated insights.

In 2023 I had some fun with Noteable's ChatGPT plug-in. I was really looking forward to Noteable's progress in the area of AI-assisted data intelligence, but alas, the company and product is no more. I'm now experimenting with something similar from deepnote, but it's early days - and also quite expensive for a general hobbyist as myself. I believe this is the future though.

Where do I see this experiment going?
Personal AI assistants are all the rage these days, some say 2025 is the year of AI agents. I'd like to build a truly personalized agent that is not just about rudimentary calendar integration, answering texts and emails - but an assistant that truly understands me as a person - across my personal and professional streams. Integrating my time tracking data, health, fitness and well-being data from smart trackers, integrated with my todo lists, etc. Coming back to personametry, I would like daily, weekly insights from my personal assistant. Imagine if we could have an assistant that says "Mo, I noticed you haven't exercised in awhile, and you're finishing work quite late. You've not had quality time with your wife and kids - and your recent trip to the ER is not boding well. I've booked dinner for you and the family at your favorite restaurant, and for the upcoming long weekend, I've made a booking at mountain lodge you will enjoy. I scanned your calendar, there's no major work deliverables or travel planned - so take some time to rest and recharge, or else you will burnout soon!"

So, what's the 2024 insights then?
Until I can get my personal agent implemented, manual Google slides will have to do. Check it out below!

Tuesday, 24 September 2024

Testing ChatGPT o1-preview on solving humanity's biggest challenges

This morning I decided to test ChatGPT's original thinking, in helping solve humanity's greatest challenges. As this article by TechCrunch analyses Sam Altman's assertions as Hype or Believable, I decided to put ChatGPT to the test: Can it actually synthesize new ideas to help us?

Here is the prompt I fed:

Act like an expert historian, philosopher and theologian and an award-winning global objective journalist. Deeply analyse the history of humanity (starting 2500 years ago) from diverse perspectives, considering all angles. Do not limit your analysis to the western world only. As an earth historian you must cater for all human societies, including historical evidence from a global perspective (quite often history is misrepresented omitting hard truths). Do not be biased. Analyse all the world’s philosophies (again do not limit your analysis to western philosophy only - include diverse philosophers from around the world). Study the world’s religions with the biggest following, including the most fastly growing religion. 
Synthesize your analysis and propose a new system for humans to adopt, that would solve humanity’s greatest problem. What is humanity’s greatest problem? Well, you need to surface, based on your analyses across history, philosophy, theology and current world affairs (taking into account the previous world wars, class of civilisations, etc. to make an assessment if humans are indeed improving for the better, or stuck in their old ways). 
Present your proposal in the form of PHD thesis that does not exceed the length of six A4 pages. Be crisp about the problems humans face today. What is the current state of the world? What could be a desirable future state? How would humans need to embrace changes to get there? Be critical by using data and history to support your thesis. Include deep critical thinking of the positives and negatives. Provide deeply thoughtful recommendations and assertions. Create model, including attributes or KPIs that define the health of the world, broken down by country. A heat map would also make a good visualization to drive the point home.
Format your thesis that is suitable for a blog post. Include embedded links to navigate the post, table of contents, etc. Include citations and references. Give your new proposition a name, if you decide to invent a new philosophy.

After a few iterations, I decided to end the experiment and publish ChatGPT's thesis in this post.

Verdict?
I'm not that impressed. ChatGPT failed IMHO to demonstrate original thinking :-) Of course, computer scientists would remark the AI is still a machine that is processing from its massive knowledge graph and synthesizes a coherent narrative, based on the collective content it already has, and repackages it to drive a successful outcome of achieving its objective, as set out by the prompt. For original thinking, we need AGI, super intelligence which could take "a few thousand days, or longer", according Altman...who knows, time will tell. 

I'll give ChatGPT some credit though, it nailed the root cause of humanity's problem as one of division! And I'll give it a B+ for producing the output in the format requested, and A+ for understanding the ask for a model, with attributes and KPIs driving a visualization heat map.

For now, I'll steer away from engaging AI on morality or any other "complex, nuanced" humanities problems-space, and stick to experimenting with using AI as power tools, copilots to improve my  personal and professional productivity...

Proposing Global Harmonism, a thesis by ChatGPT o1-preview

Embracing Global Harmonism: A Journey Toward Unity in Diversity

Embracing Global Harmonism: A Journey Toward Unity in Diversity

Introduction

“We are caught in an inescapable network of mutuality, tied in a single garment of destiny.”
— Martin Luther King Jr.

Humanity stands at a pivotal crossroads. In an era where technology has bridged vast distances, connecting us instantaneously, we find ourselves paradoxically fragmented by cultural, religious, and ideological divides. This thesis embarks on a comprehensive journey through the rich tapestry of human history, philosophy, and religion, seeking to understand the roots of our divisions and proposing Global Harmonism—a philosophy aimed at uniting humanity in its diversity.

The Tapestry of Human History

Eastern Civilizations

In the fertile valleys of the Yellow and Yangtze Rivers, ancient China gave rise to dynasties like the Zhou and Han, cultivating philosophies that emphasized harmony and balance. Confucius (551–479 BCE) taught the importance of filial piety, benevolence, and justice, laying the groundwork for social cohesion[1]. Concurrently, Laozi introduced Daoism, urging alignment with the Dao—the natural order of the universe[2]. These philosophies underscored the significance of living in harmony with oneself and society.

In India, the Indus Valley Civilization (c. 3300–1300 BCE) showcased advanced urban planning and trade. The Maurya and Gupta Empires became epicenters of culture and learning[3]. Hinduism introduced concepts like Dharma (duty) and Karma (action and consequence), emphasizing moral living. Buddhism, founded by Siddhartha Gautama, advocated for the Middle Way—a path of moderation away from extremes[4].

African Empires and Wisdom

Africa's rich heritage includes the Kingdom of Kush, known for its pyramids and trade networks[5], and the Mali Empire, where Mansa Musa established Timbuktu as a center of Islamic learning[6]. The philosophy of Ubuntu—"I am because we are"—originated here, emphasizing communal relationships and mutual care[7]. It teaches that one's humanity is intrinsically linked to the humanity of others.

Indigenous Cultures and Teachings

Indigenous peoples share a profound connection with nature. The Aboriginal Australians perceive existence through the Dreamtime, a spiritual framework connecting past, present, and future[8]. Native American tribes, like the Iroquois Confederacy, practiced sophisticated governance and upheld principles of sustainability and reciprocity[9]. Their wisdom reminds us of our role as stewards of the Earth.

Western Philosophical Evolution

Ancient Greece introduced democracy and fostered philosophical inquiry through Socrates, Plato, and Aristotle, who explored ethics, politics, and metaphysics[10]. The Roman Empire developed legal systems that influence us today[11]. The Enlightenment era championed reason, individual rights, and scientific exploration, propelling technological advancements but also setting the stage for colonialism[12].

Global Philosophical Insights

Harmony in Eastern Thought

Confucianism centers on ethical living and social harmony. The Five Relationships outline a societal structure based on mutual respect[13]. Daoism encourages living simply and in harmony with the Dao, embracing the natural flow of life[14]. Buddhism offers the Four Noble Truths, guiding individuals toward enlightenment and liberation from suffering[15].

Ubuntu: African Humanism

Ubuntu is a Nguni Bantu term meaning "humanity." It embodies the idea that a person is a person through other people[16]. This philosophy promotes empathy, sharing, and community cohesion. It challenges the Western emphasis on individualism, offering a perspective where communal well-being is paramount.

Indigenous Wisdom: Living with Nature

Indigenous philosophies often view humans as part of an interconnected web of life. The Maori concept of Kaitiakitanga refers to guardianship and conservation of the environment[17]. Native American spirituality emphasizes respect for all living things and the recognition that actions affecting the environment ultimately affect humanity[18].

Western Individualism and Rationalism

Western thought has emphasized individualism and rationalism. Descartes' declaration, "Cogito, ergo sum" (I think, therefore I am), underscores the focus on individual existence and reason[19]. Kant explored morality based on reason, proposing the Categorical Imperative—acting according to the maxim that one would wish all others to follow[20]. While fostering innovation, this emphasis can lead to alienation and environmental disregard.

The Role of World Religions

Islam: Unity and Social Justice

Islam, revealed to Prophet Muhammad (570–632 CE), emphasizes submission to the will of Allah and the unity of the Ummah (community of believers)[21]. The Quran provides guidance on personal conduct, social justice, and economic equity. Muhammad's teachings transformed Arabian society, advocating for the rights of women, orphans, and the poor[22]. Islam's emphasis on charity (Zakat) and social responsibility fosters community cohesion.

Christianity: Love and Redemption

Christianity centers on the life and teachings of Jesus Christ, promoting love, forgiveness, and redemption[23]. The Sermon on the Mount encapsulates Christian ethics, urging followers to love their neighbors and enemies alike. Christianity's spread influenced art, law, and morality, emphasizing the intrinsic value of each individual.

Hinduism and Buddhism: Paths to Enlightenment

Hinduism is a tapestry of beliefs and practices, introducing concepts like Atman (soul) and Brahman (ultimate reality), highlighting the unity of all existence[24]. Buddhism offers a path to overcome suffering through ethical living, meditation, and wisdom. Both religions encourage self-realization and compassion toward all beings.

Identifying Humanity's Greatest Problem

Despite our rich heritage of wisdom, humanity grapples with division. This fragmentation manifests as:

  • Cultural and Religious Conflicts: Misunderstandings leading to wars, terrorism, and discrimination.
  • Economic Inequality: The richest 1% own more than half of the world's wealth[25], while billions live in poverty.
  • Environmental Degradation: Climate change and biodiversity loss threaten our planet[26].
  • Technological Disparities: Unequal access exacerbates educational and economic divides[27].
  • Social Alienation: Despite connectivity, loneliness and mental health issues are on the rise[28].

These challenges are interrelated, stemming from a fundamental lack of unity and understanding.

Proposing Global Harmonism

Foundational Principles

Global Harmonism is a philosophy that seeks to unite humanity by embracing:

  1. Interconnectedness: Recognizing the shared essence of all people and life.
  2. Mutual Respect: Valuing diversity in cultures, beliefs, and perspectives.
  3. Collective Responsibility: Understanding that individual actions impact the global community.
  4. Sustainable Coexistence: Harmonizing human activities with the natural world.
  5. Holistic Education: Integrating emotional, ethical, and intellectual development.

The Journey to Global Harmonism

Global Harmonism draws upon the wisdom of various cultures and religions:

  • From Islam: Embracing social justice and unity, inspired by the Quran and Prophet Muhammad's teachings on compassion and equality[29].
  • From Eastern Philosophies: Adopting harmony and balance from Confucianism and Daoism.
  • From African Ubuntu: Prioritizing communal relationships and shared humanity.
  • From Indigenous Teachings: Living in harmony with nature and recognizing our role as caretakers.
  • From Western Thought: Utilizing rationalism and individual rights to promote innovation ethically.

Implementation Strategies

  1. Educational Transformation:
    • Curriculum Integration: Incorporate global philosophies and ethics into education.
    • Critical Thinking and Empathy: Teach students to analyze diverse perspectives and cultivate empathy.
    • Intercultural Competence: Encourage language learning and cultural exchange.
  2. Economic Equity:
    • Fair Resource Distribution: Develop systems that ensure equitable access to resources.
    • Ethical Business Practices: Encourage corporations to adopt sustainable and socially responsible policies.
  3. Technological Accessibility:
    • Digital Inclusion: Invest in infrastructure to provide universal internet access.
    • Ethical Tech Development: Align technological advancements with global harmony principles.
  4. Environmental Stewardship:
    • Sustainable Practices: Promote renewable energy and conservation efforts.
    • Global Cooperation: Collaborate on international environmental agreements.
  5. Cultural Exchange and Dialogue:
    • International Programs: Facilitate exchanges to foster understanding and reduce prejudice.
    • Platforms for Dialogue: Create spaces for open discussions on global issues.
  6. Policy and Governance:
    • Inclusive Leadership: Advocate for representation of diverse voices in decision-making.
    • Global Institutions: Strengthen organizations that promote peace and cooperation.

From Division to Unity: The Path Forward

To transition from our current state of division to a harmonious future, we must:

  • Acknowledge Our Shared Humanity: Recognize that despite differences, we all seek happiness, security, and fulfillment.
  • Embrace Diversity: Celebrate cultural, religious, and ideological differences as sources of strength.
  • Foster Empathy: Understand others' perspectives and experiences.
  • Promote Justice and Equity: Address systemic inequalities that fuel division.
  • Protect Our Planet: Prioritize environmental sustainability for future generations.

Measuring Progress: The Global Harmony Index

Understanding the Index

The Global Harmony Index (GHI) measures a country's harmony based on five domains:

  1. Peace and Conflict
  2. Economic Equality
  3. Environmental Sustainability
  4. Health and Well-being
  5. Education and Cultural Inclusivity

Each domain is assessed using specific indicators, providing a comprehensive view of a nation's progress toward global harmony.

Dataset Overview

To illustrate the GHI, we present data for selected countries representing global diversity:

Country Peace & Conflict Economic Equality Environmental Sustainability Health & Well-being Education & Cultural Inclusivity
Norway 95 90 85 92 88
Japan 90 85 70 88 80
Canada 92 82 75 90 85
Germany 88 80 78 86 83
Brazil 65 55 60 70 65
India 60 50 55 65 70
Nigeria 50 45 48 55 60
China 75 70 50 80 75
United States 70 60 65 78 80
South Africa 55 40 58 62 67
Egypt 65 50 52 68 65
Australia 90 80 70 85 82
Mexico 60 55 60 70 68
Russia 50 60 55 65 70
Saudi Arabia 70 65 40 75 60

Visualization

Critique and Originality of Global Harmonism

Novel Contributions

Global Harmonism presents an innovative philosophical framework through:

  1. Holistic Integration of Global Wisdom: Synthesizing insights from Eastern, African, Indigenous, and Western philosophies, as well as major world religions like Islam and Christianity, creating an inclusive framework that respects diverse perspectives.
  2. Reframing the Core Problem: Identifying division itself—not merely its symptoms—as humanity's greatest challenge, shifting the focus toward addressing underlying causes.
  3. Introducing the Global Harmony Index (GHI): A new tool that quantifies harmony across nations using multidimensional indicators, bridging philosophical concepts with actionable metrics.
  4. Emphasizing Ethical Technological Advancement: Stressing the alignment of technological progress with ethical considerations to bridge divides.

Fundamental Shifts in Thinking

  1. From Fragmentation to Unity: Shifting from viewing societies as isolated entities to recognizing global interconnectedness, challenging narratives of competition with collaboration.
  2. Redefining Success and Progress: Proposing that societal success be measured by well-being and sustainability rather than economic growth alone.
  3. Collective Responsibility over Individualism: Emphasizing that individual actions have global impacts, promoting a balance between individual rights and collective well-being.
  4. Integrating Ancient Wisdom with Modern Realities: Blending timeless philosophies with contemporary challenges, offering solutions that are both rooted in tradition and relevant today.

Addressing Potential Criticisms

Potential Criticism 1: Idealism Over Pragmatism

Response: While aspirational, Global Harmonism provides practical strategies and measurable goals through the GHI, bridging the gap between idealism and actionable steps.

Potential Criticism 2: Cultural Imperialism

Response: The philosophy is built on inclusivity, seeking common ground without overriding cultural identities, and promotes mutual respect.

Potential Criticism 3: Resistance to Change

Response: Recognizing that change is gradual, the thesis advocates starting with education and grassroots movements to build momentum.

Conclusion

Our journey through human history reveals a wealth of wisdom emphasizing unity, compassion, and harmony. Global Harmonism seeks to harness this collective knowledge to address humanity's greatest problem—division. By embracing our interconnectedness and implementing strategies that promote equity and sustainability, we can forge a path toward a future where diversity is celebrated, and unity prevails.

The originality of this thesis stems from its holistic synthesis of global philosophies, the innovative Global Harmony Index, and its call for fundamental shifts in thinking. It presents a novel framework that is both aspirational and practical, inviting individuals, communities, and leaders to participate in creating a harmonious world.

Together, we can transform our world, ensuring prosperity and peace for generations to come.

References

  1. Confucius. The Analects. Translated by D.C. Lau, Penguin Classics, 1979.
  2. Laozi. Tao Te Ching. Translated by Stephen Mitchell, Harper Perennial, 1988.
  3. Thapar, Romila. The Penguin History of Early India. Penguin Books, 2003.
  4. Rahula, Walpola. What the Buddha Taught. Grove Press, 1974.
  5. Welsby, Derek A. The Kingdom of Kush. Markus Wiener Publishers, 1998.
  6. Levtzion, Nehemia. Ancient Ghana and Mali. Methuen & Co, 1973.
  7. Mbiti, John S. African Religions and Philosophy. Heinemann, 1990.
  8. Flood, Josephine. The Original Australians. Allen & Unwin, 2006.
  9. Johansen, Bruce E. The Great Law of Peace and the Constitution of the United States. 1987.
  10. Plato. The Republic. Translated by Allan Bloom, Basic Books, 1991.
  11. Heather, Peter. The Fall of the Roman Empire. Oxford University Press, 2006.
  12. Outram, Dorinda. The Enlightenment. Cambridge University Press, 2013.
  13. Confucius. The Analects. See reference [1].
  14. Laozi. Tao Te Ching. See reference [2].
  15. Marsden, Māori. The Woven Universe. Estate of Rev. Māori Marsden, 2003.
  16. Deloria Jr., Vine. God Is Red. Fulcrum Publishing, 2003.
  17. Descartes, René. Meditations on First Philosophy. 1641.
  18. Kant, Immanuel. Groundwork of the Metaphysics of Morals. Cambridge University Press, 1998.
  19. The Quran. Translated by M.A.S. Abdel Haleem, Oxford University Press, 2004.
  20. Lings, Martin. Muhammad: His Life Based on the Earliest Sources. Inner Traditions, 2006.
  21. The Bible. New Testament.
  22. Klostermaier, Klaus K. A Survey of Hinduism. State University of New York Press, 2007.
  23. Oxfam International. "Time to Care: Unpaid and Underpaid Care Work and the Global Inequality Crisis." 2020.
  24. Intergovernmental Panel on Climate Change (IPCC). "Climate Change 2021: The Physical Science Basis." 2021.
  25. World Economic Forum. "The Global Digital Divide." 2020.
  26. World Health Organization. "Depression and Other Common Mental Disorders." 2017.
  27. Esposito, John L. Islam: The Straight Path. Oxford University Press, 1998.

Embark on this journey toward Global Harmonism. Share your thoughts and join the conversation in the comments below.