How to detect AI-Generated scams with Programming Languages

 How To Detect AI-Generated Scams With Programming Languages.


The easiest way to know if a content or a user is AI-generated, is to use the tool those scammers use to create and manage the AI: Programming Languages.

If you are a developer, it will be easier for you to trace and avoid AI-generated scams being from content or user to come into your way or your loved ones. I recommend you to learn those languages so that you will know deeply about online scamming and avoid being a victim.

Before I go into the codes, I'll show you some algorithms you will need while checking contents in all languages. This general algorithm is a basis every developer use in detecting AI content. These details vary depending on the language you are using. 

(All codes listed below are adopted from OpenAI for educational purposes and all the codes are basic. You can use this formats on real sophisticated codes on libraries of the Programming Languages below mentioned)

1. Extraction of Features: From the text and script like the word frequency, sentence structure, sentiment etc.

2. Sentiment Analysis: Analyze APIs to know the tone of the text with sentiment analysis. The AI generated content lacks genuine emotional expressions. 

3. Unusual Timing: Analyze the time taken to generate responses. AI-generated responses have a noticeable delay on the processing time.

4. Input: If the text is user-provided or it is generated by AI

5. AI Patterns: Verify patterns used often in the AI generated content that you know. This might be the use of phrases, sentence structure, lack of typical human errors and clean/unkept grammatic errors.



AI Detection With Java.




This example with Java uses a basic set of techniques and features. It contains basic string manipulation and comparison for demonstration. I recommend you to use sophisticated libraries and techniques in more tricky and hard AI-generated contents.


Java

import java.util.regex.Pattern;

import java.util.regex.Matcher;


public class AIDetection {


    public static void main(String[] args) {

        String userText = "Hello, how are you?";


        boolean isAIGenerated = isAIGenerated(userText);


        if (isAIGenerated) {

            System.out.println("This might be AI-generated.");

        } else {

            System.out.println("This seems to be human-generated.");

        }

    }


    public static boolean isAIGenerated(String text) {

        // Check for patterns that might indicate AI-generated content

        boolean hasUnnaturalLanguage = containsUnnaturalLanguage(text);

        boolean hasLowSentiment = hasLowSentiment(text);

        boolean hasLongResponseTime = hasLongResponseTime(text);


        // Combine results and return

        return hasUnnaturalLanguage || hasLowSentiment || hasLongResponseTime;

    }


    public static boolean containsUnnaturalLanguage(String text) {

        // Basic example of checking for unnatural language patterns

        String[] aiPhrases = { "I am a robot", "Generated by AI", "AI Response" };


        for (String phrase : aiPhrases) {

            if (text.contains(phrase)) {

                return true;

            }

        }

        return false;

    }


    public static boolean hasLowSentiment(String text) {

        // Basic example of sentiment analysis based on positive/negative words

        String[] positiveWords = { "happy", "good", "excellent" };

        String[] negativeWords = { "sad", "bad", "terrible" };


        int positiveCount = countWords(text, positiveWords);

        int negativeCount = countWords(text, negativeWords);


        return negativeCount > positiveCount;

    }


    public static boolean hasLongResponseTime(String text) {

        // Basic example of checking for long response times

        return text.length() > 100; // Adjust threshold as needed

    }


    public static int countWords(String text, String[] words) {

        int count = 0;

        for (String word : words) {

            if (text.contains(word)) {

                count++;

            }

        }

        return count;

    }

}


NB: This example is just a basic example and it cannot cover all AI-generated content. You can use this format in more advanced techniques in NLP libraries, learning models and APIs to empower the accuracy of your algorithm.


AI Detection With Swift. 




Like Java, Swift also has a basic content detection for some specific AI-generated contents. 


Swift 

import Foundation


func main() {

    let userText = "Hello, how are you?"

    

    let isAIGenerated = isAIGenerated(userText: userText)

    

    if isAIGenerated {

        print("This might be AI-generated.")

    } else {

        print("This seems to be human-generated.")

    }

}


func isAIGenerated(userText: String) -> Bool {

    let hasUnnaturalLanguage = containsUnnaturalLanguage(text: userText)

    let hasLowSentiment = hasLowSentiment(text: userText)

    let hasLongResponseTime = hasLongResponseTime(text: userText)

    

    return hasUnnaturalLanguage || hasLowSentiment || hasLongResponseTime

}


func containsUnnaturalLanguage(text: String) -> Bool {

    // Basic example of checking for unnatural language patterns

    let aiPhrases = ["I am a robot", "Generated by AI", "AI Response"]

    

    for phrase in aiPhrases {

        if text.contains(phrase) {

            return true

        }

    }

    return false

}


func hasLowSentiment(text: String) -> Bool {

    // Basic example of sentiment analysis based on positive/negative words

    let positiveWords = ["happy", "good", "excellent"]

    let negativeWords = ["sad", "bad", "terrible"]

    

    let positiveCount = countWords(text: text, words: positiveWords)

    let negativeCount = countWords(text: text, words: negativeWords)

    

    return negativeCount > positiveCount

}


func hasLongResponseTime(text: String) -> Bool {

    // Basic example of checking for long response times

    return text.count > 100 // Adjust threshold as needed

}


func countWords(text: String, words: [String]) -> Int {

    var count = 0

    for word in words {

        if text.contains(word) {

            count += 1

        }

    }

    return count

}


// Call the main function

main()


AI Detection Using C++




#include <iostream>

#include <vector>

#include <algorithm>


bool isAIGenerated(const std::string& userText);

bool containsUnnaturalLanguage(const std::string& text);

bool hasLowSentiment(const std::string& text);

bool hasLongResponseTime(const std::string& text);

int countWords(const std::string& text, const std::vector<std::string>& words);


int main() {

    std::string userText = "Hello, how are you?";

    

    bool isAIGeneratedResult = isAIGenerated(userText);

    

    if (isAIGeneratedResult) {

        std::cout << "This might be AI-generated." << std::endl;

    } else {

        std::cout << "This seems to be human-generated." << std::endl;

    }

    

    return 0;

}


bool isAIGenerated(const std::string& userText) {

    bool hasUnnaturalLanguage = containsUnnaturalLanguage(userText);

    bool hasLowSentimentResult = hasLowSentiment(userText);

    bool hasLongResponseTimeResult = hasLongResponseTime(userText);

    

    return hasUnnaturalLanguage || hasLowSentimentResult || hasLongResponseTimeResult;

}


bool containsUnnaturalLanguage(const std::string& text) {

    // Basic example of checking for unnatural language patterns

    std::vector<std::string> aiPhrases = {"I am a robot", "Generated by AI", "AI Response"};

    

    for (const std::string& phrase : aiPhrases) {

        if (text.find(phrase) != std::string::npos) {

            return true;

        }

    }

    return false;

}


bool hasLowSentiment(const std::string& text) {

    // Basic example of sentiment analysis based on positive/negative words

    std::vector<std::string> positiveWords = {"happy", "good", "excellent"};

    std::vector<std::string> negativeWords = {"sad", "bad", "terrible"};

    

    int positiveCount = countWords(text, positiveWords);

    int negativeCount = countWords(text, negativeWords);

    

    return negativeCount > positiveCount;

}


bool hasLongResponseTime(const std::string& text) {

    // Basic example of checking for long response times

    return text.length() > 100; // Adjust threshold as needed

}


int countWords(const std::string& text, const std::vector<std::string>& words) {

    int count = 0;

    for (const std::string& word : words) {

        if (text.find(word) != std::string::npos) {

            count++;

        }

    }

    return count;

}


AI Detection Using HTML & CSS 











Note that HTML is a language used to structure up content on the web and CSS is a language used for formatting HTML documents. However you can use the code below and sync it with Javascript to create a web page with the backend code that is written on Python, Swift and Java for content detection performance. 

The codes below is a example you can create a page on HTML and  that enables users to put their text and execute the detection on a backend using Python.

index.html

<!DOCTYPE html>

<html>

<head>

    <title>AI Detection</title>

</head>

<body>

    <h1>AI Detection</h1>

    <label for="userText">Enter Text:</label>

    <input type="text" id="userText">

    <button id="detectButton">Detect AI Content</button>

    <p id="result"></p>


    <script>

        document.getElementById("detectButton").addEventListener("click", async function() {

            const userText = document.getElementById("userText").value;

            const response = await fetch('/detect-ai', {

                method: 'POST',

                headers: {

                    'Content-Type': 'application/json'

                },

                body: JSON.stringify({ userText })

            });

            const result = await response.json();

            document.getElementById("result").textContent = result.isAIGenerated

                ? "This might be AI-generated."

                : "This seems to be human-generated.";

        });

    </script>

</body>

</html>


Python Backend using Flask.

from flask import Flask, request, jsonify


app = Flask(__name__)


def detect_ai_generated(user_text):

    # Your AI-generated content detection logic here

    # Return True if AI-generated, False if not

    # Example logic: return len(user_text) > 100


@app.route('/detect-ai', methods=['POST'])

def detect_ai():

    data = request.get_json()

    user_text = data.get('userText')

    is_ai_generated = detect_ai_generated(user_text)

    return jsonify({'isAIGenerated': is_ai_generated})


if __name__ == '__main__':

    app.run(debug=True)

The HTML code have a input field field where users can text. When the user clicks on the "Detect AI Content" button, the Javascript function sends an HTTP POST to the Python backend ('app.py'). The backend does the detection and send a JSON response indicating if the content is AI-generated or not.  


With CSS:

On the HTML script:

<!DOCTYPE html>

<html>

<head>

    <title>AI Detection</title>

    <link rel="stylesheet" type="text/css" href="styles.css">

</head>

<body>

    <h1>AI Detection</h1>

    <label for="userText">Enter Text:</label>

    <input type="text" id="userText">

    <button id="detectButton">Detect AI Content</button>

    <p id="result"></p>


    <script>

        // JavaScript code here...

    </script>

</body>

</html>


Styles.css 

body {

    font-family: Arial, sans-serif;

    margin: 0;

    padding: 20px;

    background-color: #f5f5f5;

}


h1 {

    color: #333;

}


label {

    font-weight: bold;

}


input[type="text"] {

    padding: 8px;

    border: 1px solid #ccc;

    border-radius: 4px;

    margin-right: 10px;

}


button {

    padding: 8px 12px;

    background-color: #007bff;

    color: #fff;

    border: none;

    border-radius: 4px;

    cursor: pointer;

}


button:hover {

    background-color: #0056b3;

}


p#result {

    margin-top: 10px;

    font-weight: bold;

}

The 'styles.css' contains CSS rules for the elements of the HTML page. It contains colors, font types, margins and more to create a layout for your detection interface.

AI Detection Using Ruby.





require 'json'

require 'sinatra'


def is_ai_generated(user_text)

  has_unnatural_language = contains_unnatural_language(user_text)

  has_low_sentiment = has_low_sentiment(user_text)

  has_long_response_time = has_long_response_time(user_text)


  has_unnatural_language || has_low_sentiment || has_long_response_time

end


def contains_unnatural_language(text)

  # Basic example of checking for unnatural language patterns

  ai_phrases = ["I am a robot", "Generated by AI", "AI Response"]

  

  ai_phrases.any? { |phrase| text.include?(phrase) }

end


def has_low_sentiment(text)

  # Basic example of sentiment analysis based on positive/negative words

  positive_words = ["happy", "good", "excellent"]

  negative_words = ["sad", "bad", "terrible"]

  

  positive_count = count_words(text, positive_words)

  negative_count = count_words(text, negative_words)

  

  negative_count > positive_count

end


def has_long_response_time(text)

  # Basic example of checking for long response times

  text.length > 100 # Adjust threshold as needed

end


def count_words(text, words)

  words.count { |word| text.include?(word) }

end


post '/detect-ai' do

  request_body = JSON.parse(request.body.read)

  user_text = request_body['userText']

  

  is_ai_result = is_ai_generated(user_text)

  

  { isAIGenerated: is_ai_result }.to_json

end


In Ruby, they use the Sinatra framework to create a web application.  The '/detect-ai ' handles the logic of the AI-generated content detection. The front end languages like Java and HTML will send a POST to the route and the backend will respond with the JSON object if it is AI-generated or not. 



Comments