{ "cells": [ { "cell_type": "markdown", "id": "53e9feaa-53de-4377-8d45-aa1f7264ae3a", "metadata": {}, "source": [ "### First Neccesary libararies needs to be loaded." ] }, { "cell_type": "code", "execution_count": 2, "id": "8864f53f-15d2-403c-a905-3da509cfb050", "metadata": {}, "outputs": [], "source": [ "import gradio as gr\n", "import transformers\n", "from transformers import pipeline\n", "import tf_keras as keras\n", "import pandas as pd\n", "import tempfile\n", "import os" ] }, { "cell_type": "markdown", "id": "5bb130f0-d8c8-459d-918f-84025c93bc05", "metadata": {}, "source": [ "### Now we import our already pre-trained model from " ] }, { "cell_type": "code", "execution_count": 4, "id": "1c4e29a8-9b24-47d6-b14b-0e2a7e4d66a1", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Some weights of the PyTorch model were not used when initializing the TF 2.0 model TFBertForSequenceClassification: ['bert.embeddings.position_ids']\n", "- This IS expected if you are initializing TFBertForSequenceClassification from a PyTorch model trained on another task or with another architecture (e.g. initializing a TFBertForSequenceClassification model from a BertForPreTraining model).\n", "- This IS NOT expected if you are initializing TFBertForSequenceClassification from a PyTorch model that you expect to be exactly identical (e.g. initializing a TFBertForSequenceClassification model from a BertForSequenceClassification model).\n", "All the weights of TFBertForSequenceClassification were initialized from the PyTorch model.\n", "If your task is similar to the task the model of the checkpoint was trained on, you can already use TFBertForSequenceClassification for predictions without further training.\n", "Device set to use 0\n" ] } ], "source": [ "# Load pre-trained spam classifier\n", "spam_classifier = pipeline(\n", " \"text-classification\",\n", " model=\"mrm8488/bert-tiny-finetuned-sms-spam-detection\"\n", ")" ] }, { "cell_type": "markdown", "id": "9cb4ab66-2833-40bd-87cb-4d712398e431", "metadata": {}, "source": [ "### Since single email check is hassle we will make a function for batch classication\n", "### we should assume certain file template or format so our program knows what to expect" ] }, { "cell_type": "code", "execution_count": 5, "id": "b8ae7b3b-5273-4242-85db-b5cb622a4046", "metadata": {}, "outputs": [], "source": [ "def classify_batch(file):\n", " \"\"\"Process uploaded CSV/TXT file with multiple emails\"\"\"\n", " try:\n", " results = []\n", " \n", " # Check if file exists\n", " if not file.name:\n", " raise gr.Error(\"No file uploaded\")\n", "\n", " # --- CSV File Handling ---\n", " if file.name.endswith('.csv'):\n", " df = pd.read_csv(file)\n", " \n", " # Check for required email column\n", " if 'email' not in df.columns:\n", " raise gr.Error(\"CSV file must contain a column named 'email'\")\n", " \n", " emails = df['email'].tolist()\n", "\n", " # --- Text File Handling ---\n", " elif file.name.endswith('.txt'):\n", " with open(file.name, 'r') as f:\n", " emails = f.readlines()\n", " \n", " # --- Unsupported Format ---\n", " else:\n", " raise gr.Error(\"Unsupported file format. Only CSV/TXT accepted\")\n", "\n", " # Process emails (common for both formats)\n", " emails = emails[:100] # Limit to 100 emails\n", " for email in emails:\n", " # Handle empty lines in text files\n", " if not email.strip():\n", " continue\n", " \n", " prediction = spam_classifier(email.strip())[0]\n", " results.append({\n", " \"email\": email.strip()[:50] + \"...\",\n", " \"label\": \"SPAM\" if prediction[\"label\"] == \"LABEL_1\" else \"HAM\",\n", " \"confidence\": f\"{prediction['score']:.4f}\"\n", " })\n", "\n", " return pd.DataFrame(results)\n", "\n", " except gr.Error as e:\n", " raise e # Show pop-up for expected errors\n", " except Exception as e:\n", " raise gr.Error(f\"Processing error: {str(e)}\")" ] }, { "cell_type": "markdown", "id": "6ccb5108-a5d4-4f61-b363-dc4c9d25b4fb", "metadata": {}, "source": [ "### We define simple function for classification" ] }, { "cell_type": "code", "execution_count": 6, "id": "1336344b-54c3-431d-8d89-c351b0c24f80", "metadata": {}, "outputs": [], "source": [ "def classify_text(text):\n", " result = spam_classifier(text)[0]\n", " return {\n", " \"Spam\": result[\"score\"] if result[\"label\"] == \"LABEL_1\" else 1 - result[\"score\"],\n", " \"Ham\": result[\"score\"] if result[\"label\"] == \"LABEL_0\" else 1 - result[\"score\"]\n", " }" ] }, { "cell_type": "markdown", "id": "4559470b-1356-4f9d-b977-44bfbe117f3d", "metadata": {}, "source": [ "### using gradio we will make a simple interface for our program" ] }, { "cell_type": "code", "execution_count": 12, "id": "67927628-4ca2-43ac-80c3-a1f9d4771d5d", "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "* Running on local URL: http://127.0.0.1:7868\n", "Caching examples at: '/Users/techgarage/Projects/spamedar/.gradio/cached_examples/143'\n", "\n", "To create a public link, set `share=True` in `launch()`.\n" ] }, { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "with gr.Blocks(title=\"Spam Classifier Pro\") as demo:\n", " gr.Markdown(\"# 📧 Welcome to Spamedar!\")\n", " \n", " \n", " with gr.Tab(\"✉️ Single Email\"):\n", " gr.Interface(\n", " description=\"

Copy your email to find out if it's a is Spam or Ham👇

\",\n", " fn=classify_text,\n", " inputs=gr.Textbox(label=\"Input Email\", lines=3),\n", " outputs=gr.Label(label=\"Classification\"),\n", " examples=[\n", " [\"Urgent: Verify your account details now!\"],\n", " [\"Hey, can we meet tomorrow to discuss the project?\"],\n", " [\"WINNER! You've been selected for a $1000 Walmart Gift Card!\"],\n", " [\"Your account needs verification. Click here to confirm your details.\"],\n", " [\"Meeting rescheduled to Friday 2 PM\"]\n", " ]\n", " )\n", " current_dir = os.getcwd()\n", " with gr.Tab(\"📨 Multiple Emails\"):\n", " gr.Markdown(\"## Upload email batch (CSV or TXT)\")\n", " file_input = gr.File(label=\"Upload File\", file_types=[\".csv\", \".txt\"])\n", " clear_btn = gr.Button(\"Clear Selection\", variant=\"secondary\")\n", " output_table = gr.Dataframe(\n", " headers=[\"email\", \"label\", \"confidence\"],\n", " datatype=[\"str\", \"str\", \"number\"],\n", " interactive=False,\n", " label=\"Classification Results\"\n", " )\n", " download_btn = gr.DownloadButton(label=\"Download Results\")\n", "\n", " def process_file(file):\n", " \"\"\"Process file and return (display_df, download_path)\"\"\"\n", " try:\n", " if file is None:\n", " return pd.DataFrame(), None\n", "\n", " results_df = classify_batch(file)\n", " with tempfile.NamedTemporaryFile(suffix=\".csv\", delete=False) as f:\n", " results_df.to_csv(f.name, index=False)\n", " return results_df, f.name\n", " except Exception as e:\n", " raise gr.Error(f\"Error processing file: {str(e)}\")\n", "\n", " def clear_selection():\n", " ###clear file input and results function\n", " return None, pd.DataFrame(), None\n", " \n", " file_input.upload(\n", " fn=process_file,\n", " inputs=file_input,\n", " outputs=[output_table, download_btn] # Update both components\n", " )\n", "\n", " clear_btn.click(\n", " fn=clear_selection,\n", " outputs=[file_input, output_table, download_btn]\n", " )\n", "\n", " example_files= [\n", " os.path.join(os.getcwd(), \"sample_emails.csv\"),\n", " os.path.join(os.getcwd(), \"batch_emails.txt\"),\n", " ]\n", " if all(os.path.exists(f) for f in example_files):\n", " gr.Examples(\n", " examples=[[f] for f in example_files],\n", " inputs=file_input,\n", " outputs=[output_table, download_btn],\n", " fn=process_file,\n", " cache_examples=True,\n", " label=\"Click any example below to test:\"\n", " )\n", " \n", " else:\n", " print(\"Warning: Example files missing. Place these in your project root:\")\n", " print(\"- sample_emails.csv\")\n", " print(\"- batch_emails.txt\")\n", " \n", "if __name__ == \"__main__\":\n", " demo.launch()" ] }, { "cell_type": "markdown", "id": "18c2a4bd-0404-46ec-87b1-4f47b5802150", "metadata": {}, "source": [ "### Thank you for following the guide until the end.🚀👾\n", "code: Raouf Jivad(with a lil help of GPT 😃)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.16" } }, "nbformat": 4, "nbformat_minor": 5 }