noch inator commited on
Commit
8e8f2a5
·
1 Parent(s): 5b65d02

added the AI files

Browse files
Files changed (4) hide show
  1. interact.py +153 -0
  2. main.h5 +3 -0
  3. tokenizer.pkl +3 -0
  4. train.py +80 -0
interact.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ print("Initializing...")
2
+ import os
3
+ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
4
+ import pickle
5
+ import re
6
+ import webbrowser as wb
7
+ import tensorflow as tf
8
+ import numpy as np
9
+ import speech_recognition as sr
10
+ import keyboard
11
+
12
+
13
+ # Define the function to preprocess the input text
14
+ def preprocess_text(text):
15
+ # Convert the text to lowercase
16
+ text = text.lower()
17
+ # Replace any non-alphanumeric characters with a space
18
+ text = re.sub(r'[^a-zA-Z0-9\'+\-*/\s]', ' ', text)
19
+ # Replace the word 'plus' with the '+' symbol
20
+ text = text.replace('plus', '+')
21
+ # Replace the word 'minus' with the '-' symbol
22
+ text = text.replace('minus', '-')
23
+ # Replace the word 'times' with the '*' symbol
24
+ text = text.replace('times', '*')
25
+ # Replace the word 'divided by' with the '/' symbol
26
+ text = text.replace('divided by', '/')
27
+ # Replace the characters * / - + with a space and the character itself
28
+ text = text.replace('*', ' * ').replace('/', ' / ').replace('-', ' - ').replace('+', ' + ').replace('.', ' . ')
29
+ # Replace all numbers with a special token
30
+ text = re.sub(r'\d+', '<num>', text)
31
+ # Replace tokens that are not present in the tokenizer with a special token
32
+ text = text.split()
33
+ text = [word if word in vocab.word_index else '<oov>' for word in text]
34
+ text = ' '.join(text)
35
+ # Remove any extra whitespace
36
+ text = re.sub(r'\s+', ' ', text)
37
+ return text.strip()
38
+
39
+
40
+ def listen_and_convert():
41
+ recognizer = sr.Recognizer()
42
+
43
+ with sr.Microphone() as source:
44
+ print("Recording... Speak something:")
45
+ audio = recognizer.listen(source)
46
+
47
+ print("Processing...")
48
+ try:
49
+ text = recognizer.recognize_google(audio)
50
+ print(text)
51
+ process_input(text) # Process the converted text using the existing function
52
+ except sr.UnknownValueError:
53
+ print("Google Speech Recognition could not understand the audio.")
54
+
55
+ except sr.RequestError as e:
56
+ print(f"Could not request results from Google Speech Recognition service; {e}")
57
+
58
+
59
+ def site():
60
+ # Define a regex pattern to find URL
61
+ url_pattern = r'(?:http://|https://)?(\S+\.(?:com|org|net|edu|gov|me|ai|io))'
62
+ matches = re.findall(url_pattern, input_text)
63
+ url = None
64
+
65
+ if matches:
66
+ url = "https://" + matches[0]
67
+ elif "chatgpt" in input_text:
68
+ url = "chat.openai.com"
69
+ elif "email" in input_text:
70
+ url = "mail.google.com"
71
+ elif "gmail" in input_text:
72
+ url = "mail.google.com"
73
+ elif "youtube" in input_text:
74
+ url = "youtube.com"
75
+ elif "pandora" in input_text:
76
+ url = "pandora.com"
77
+ elif "spotify" in input_text:
78
+ url = "spotify.com"
79
+
80
+ if url is not None:
81
+ print("opened " + url)
82
+ wb.get('windows-default').open(url)
83
+ else:
84
+ print("Somethings wrong, check your input, if your input is good then create a bug report with the following: "
85
+ f"category: open website, input: {input_text}")
86
+
87
+
88
+ def search():
89
+ # Remove common words that don't contribute to search terms
90
+ stop_words = {'search', 'for', 'find', 'on', 'the', 'web', 'do', 'do a', 'google'}
91
+ words = input_text.split()
92
+ filtered_words = [word for word in words if word.lower() not in stop_words]
93
+
94
+ # Extract the remaining words as search terms
95
+ search_terms = ' '.join(filtered_words)
96
+
97
+ print("searched for " + search_terms)
98
+ search_url = f"https://duckduckgo.com/?q={search_terms}"
99
+ wb.get('windows-default').open(search_url)
100
+
101
+
102
+ def math():
103
+ # Define a regex pattern to match basic math expressions (e.g., 2 + 3, 4 * 5, etc.)
104
+ math_pattern = r'(\d+(\.\d+)?(\s*(\+|-|\*|\/)\s*\d+(\.\d+)?)+)'
105
+ matches = re.findall(math_pattern, input_text)
106
+
107
+ return matches[0][0] if matches else None
108
+
109
+
110
+ def process_input(text):
111
+ if text == "/quit":
112
+ return False
113
+
114
+ processed_input_text = preprocess_text(text)
115
+ test_data = [processed_input_text] # Wrap the input data in a list
116
+ test_encoded = vocab.texts_to_sequences(test_data)
117
+ test_padded = tf.keras.preprocessing.sequence.pad_sequences(test_encoded, maxlen=15, padding='post')
118
+ predictions = model.predict(test_padded)
119
+ predicted_category_number = np.argmax(predictions[0])
120
+ predicted_category = "report this as logic error 1 and with steps to reproduce."
121
+
122
+ if predicted_category_number == 0:
123
+ predicted_category = "math"
124
+ math()
125
+ elif predicted_category_number == 1:
126
+ predicted_category = "web search"
127
+ search()
128
+ elif predicted_category_number == 2:
129
+ predicted_category = "open website"
130
+ site()
131
+ print(f"Predicted Function: {predicted_category}")
132
+
133
+ return True
134
+
135
+
136
+ # Load the saved model
137
+ model = tf.keras.models.load_model('main.h5')
138
+
139
+ # Load the tokenizer using pickle
140
+ with open('tokenizer.pkl', 'rb') as file:
141
+ vocab = pickle.load(file)
142
+ print()
143
+
144
+ # Enter into an interactive loop to test the model
145
+ while True:
146
+ input_text = input("user: ")
147
+
148
+ # Check for the hotkey press
149
+ if keyboard.is_pressed('ctrl'):
150
+ listen_and_convert() # If hotkey pressed, start listening and convert speech to text
151
+
152
+ if not process_input(input_text):
153
+ break
main.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a35281af8d155acab2db9174c7a28fb0049cb15b7b0e7a9f30ca08ff6f85c82
3
+ size 562512
tokenizer.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aa5958b2cdf31bf4c3bdc91a31a88a7dc8b429d7595c2946df65baa901092f3b
3
+ size 2973
train.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+ import tensorflow as tf
3
+ import pandas as pd
4
+ import re
5
+
6
+
7
+ # Define the function to preprocess the input text
8
+ def preprocess_text(text):
9
+ # Convert the text to lowercase
10
+ text = text.lower()
11
+ # Replace any non-alphanumeric characters with a space
12
+ text = re.sub(r'[^a-zA-Z0-9\'+\-*/\s]', ' ', text)
13
+ # Replace the word 'plus' with the '+' symbol
14
+ text = text.replace('plus', '+')
15
+ # Replace the word 'minus' with the '-' symbol
16
+ text = text.replace('minus', '-')
17
+ # Replace the word 'times' with the '*' symbol
18
+ text = text.replace('times', '*')
19
+ # Replace the word 'divided by' with the '/' symbol
20
+ text = text.replace('divided by', '/')
21
+ # Replace the characters * / - + with a space and the character itself
22
+ text = text.replace('*', ' * ').replace('/', ' / ').replace('-', ' - ').replace('+', ' + ').replace('.', ' . ')
23
+ # Replace all numbers with a special token
24
+ text = re.sub(r'\d+', '<num>', text)
25
+ # Replace all numbers with a special token
26
+ text = text.replace(r'oov', '<oov>')
27
+ # Remove any extra whitespace
28
+ text = re.sub(r'\s+', ' ', text)
29
+ return text.strip()
30
+
31
+
32
+ epochs = int(input("epochs: "))
33
+ batch_size = int(input("batch size: "))
34
+
35
+ # Load the training data from a CSV file
36
+ data = pd.read_csv("data.csv")
37
+ input_data = data['input'].values
38
+ labels = data['class'].values
39
+
40
+ # Preprocess the input data
41
+ input_data = [preprocess_text(text) for text in input_data]
42
+
43
+ # Define the vocabulary and encode the input data
44
+ vocab = tf.keras.preprocessing.text.Tokenizer(filters='')
45
+ vocab.fit_on_texts(input_data)
46
+ encoded_input = vocab.texts_to_sequences(input_data)
47
+
48
+ # Pad the encoded input data to ensure all inputs are of the same length
49
+ max_length = max([len(seq) for seq in encoded_input])
50
+ padded_input = tf.keras.preprocessing.sequence.pad_sequences(encoded_input, maxlen=max_length, padding='post')
51
+
52
+ # Define the neural network model
53
+ model = tf.keras.Sequential([
54
+ tf.keras.layers.Embedding(input_dim=len(vocab.word_index) + 1, output_dim=64, input_length=max_length),
55
+ tf.keras.layers.Conv1D(filters=64, kernel_size=3, activation='relu', padding='same'),
56
+ tf.keras.layers.GlobalMaxPooling1D(),
57
+ tf.keras.layers.Dense(128, activation='relu'),
58
+ tf.keras.layers.Dense(128, activation=tf.keras.layers.ELU(alpha=1.0)),
59
+ tf.keras.layers.Dense(3, activation='softmax')
60
+ ])
61
+
62
+ # Compile the model
63
+ model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
64
+
65
+ # Train the model
66
+ model.fit(padded_input, labels, epochs=epochs, batch_size=batch_size)
67
+
68
+ # Save the trained model
69
+ model.save('main.h5')
70
+
71
+ # Save the tokenizer using pickle
72
+ with open('tokenizer.pkl', 'wb') as file:
73
+ pickle.dump(vocab, file)
74
+
75
+ token_to_word = {token: word for word, token in vocab.word_index.items()}
76
+ print(token_to_word)
77
+
78
+ model.summary()
79
+
80
+ # Enter into an interactive loop to test the model