Python.md
January 20 2024 18:41:05
9.963 KB



Python


Instalacion

Linux

   sudo apt-get update
   sudo apt-get install python3
   python3 --version

masOS

   /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
   brew install python
   python3 --version

Windows

python --version

Paquetes

Para instalar paquetes o librerias en python usamos el comando pip.

pip install numpy
pip install matplotlib
pip install scipy
pip install requests
pip install beautifulsoup4
pip install plotly
pip install tensorflow
pip install pandas
pip install keras


*.py

Fractales

Julia set

import numpy as np
import matplotlib.pyplot as plt

def julia(h, w, c, max_iterations):
    x, y = np.linspace(-1.5, 1.5, w), np.linspace(-1.5, 1.5, h)
    X, Y = np.meshgrid(x, y)
    Z = X + Y*1j
    M = np.full((h, w), max_iterations)
    for n in range(max_iterations):
        Z = Z*Z + c
        divergence = np.abs(Z) > 2
        M[divergence] = n
    return M

plt.imshow(julia(400, 400, -0.4 + 0.6j, 250), cmap='hot')
plt.show()

Mandelbrot set

import numpy as np
import matplotlib.pyplot as plt

def mandelbrot(h,w, max_iterations):
    x,y = np.linspace(-2,2,w), np.linspace(-2,2,h)
    X,Y = np.meshgrid(x,y)
    c = X + Y*1j
    z = c
    divtime = max_iterations + np.zeros((h,w), dtype=int)
    for i in range(max_iterations):
        z = z**2 + c
        diverge = z*np.conj(z) > 2**2
        div_now = diverge & (divtime==max_iterations)
        divtime[div_now] = i
        z[diverge] = 2
    return divtime

plt.imshow(mandelbrot(800,800,250), cmap='hot')
plt.show()

web

Requests

import requests

url = "https://example.com/api/v1/resource"
data = {"name": "Alice", "age": 25}
headers = {
    "User-Agent": "MyApp/1.0",
    "Accept": "application/json",
    "Content-Type": "application/json",
    "Authorization": "Bearer <your_token>",
    "Cookie": "session_id=123456"
}

try:
    response = requests.post(url, json=data, headers=headers)
    response.raise_for_status()
    print(f"Status code: {response.status_code}")
    print(f"Content: {response.json()}")
except requests.exceptions.ConnectionError as e:
    print(f"Connection error: {e}")
except requests.exceptions.Timeout as e:
    print(f"Timeout error: {e}")
except requests.exceptions.HTTPError as e:
    print(f"HTTP error: {e}")
except requests.exceptions.RequestException as e:
    print(f"Request error: {e}")
finally:
    print("Request finished")

Secure POST

import schedule
import time
import json
import requests
import hashlib
from scapy.all import *

password = "s3cr3t"

def generate_auth_code(data):
    message = password + data
    hash = hashlib.sha256()
    hash.update(message.encode())
    return hash.hexdigest()

def get_all_macs():
    arp_request = Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst="192.168.0.0/24")
    ans, _ = srp(arp_request, timeout=2)
    all_macs = [r[ARP].hwsrc for _, r in ans]
    return all_macs

def send_all_macs():
    all_macs = get_all_macs()
    result = {"macs": all_macs}
    json_data = json.dumps(result)
    auth_code = generate_auth_code(json_data)
    requests.post("https://sixela.me/home/who.php", data={"json": json_data, "auth": auth_code})
    print(json_data)

schedule.every(60).seconds.do(send_all_macs)
send_all_macs()

while True:
    schedule.run_pending()
    time.sleep(1)

Discover Hosts

import os

network = "10.11.71."

for i in range(1, 256):
    host = network + str(i)
    response = os.system("ping -c 1 " + host)
    if response == 0:
        print(host, 'is up!')
    else:
        print(host, 'is down.')

Other discovery of hosts

import subprocess

network = "10.11.72."

for i in range(1, 256):
    host = network + str(i)
    try:
        subprocess.check_output(["ping", "-w", "1", host], stderr=subprocess.STDOUT)
        print(host, 'is up!')
    except subprocess.CalledProcessError:
        print(host, 'is down.')

Check Ports

import socket

def is_port_open(host, port):
    try:
        sock = socket.create_connection((host, port), timeout=0.01)
        sock.close()
        return True
    except socket.error:
        return False

def scan_ports(host):
    for port in range(1, 1000):
        if is_port_open(host, port):
            print(f"Port {port} is open")
    print("Done")


scan_ports("10.11.22.25")

Check for web servers

import socket

def check_port(host, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(0.1)
    try:
        s.connect((host, port))
        s.close()
        return True
    except:
        return False

network = "10.11.71."
ports_to_check = [22, 80, 443, 8080]

for i in range(1, 255):
    host = network + str(i)
    print("Checking host: " + host)
    for port in ports_to_check:
        if check_port(host, port):
            print(host + " has port " + str(port) + " open")

Audio

FFT to WAV file

import matplotlib.pyplot as plt
import numpy as np
import scipy.signal
import scipy.io.wavfile

# Load the audio file
rate, data = scipy.io.wavfile.read('bee.wav')

# Compute the spectrogram
f, t, Sxx = scipy.signal.spectrogram(data, rate)

# Plot the spectrogram
plt.pcolormesh(t, f, np.log(Sxx))
plt.xlabel('Time (s)')
plt.ylabel('Frequency (Hz)')
plt.title('Spectrogram of an Audio File')
plt.show()

More FFT

import numpy as np
import matplotlib.pyplot as plt
from scipy.fft import fft
from scipy.io import wavfile

# Load the audio file
fs, data = wavfile.read("bee.wav")

# Apply the Fourier transform
ft = np.abs(fft(data))
f = np.linspace(0, fs, len(data))

# Find the indices of the largest magnitude values
largest_indices = np.argsort(ft)[-5:]

# Convert the indices back to frequencies
largest_frequencies = f[largest_indices]

# Display the main values of the Fourier transform
print("Main frequencies:", largest_frequencies, "Hz")

# Plot the result
plt.plot(f[:len(f)//2], ft[:len(f)//2])
plt.xlabel("Frequency (Hz)")
plt.ylabel("Amplitude")
plt.title("Fourier Transform of Audio File")
plt.show()

FFT Señal de audio - Sistemas Inteligentes

Fourier transforms - MrPSolver YouTube Video https://github.com/lukepolson/youtube_channel/blob/main/Python%20Tutorial%20Series/fourier_transform1.ipynb

Github - More on MrPSolver python series.

Youtube psyfun numpy


Neural audio

Here's an example of how you can use a neural network to classify audio in Python using the Keras library:

import numpy as np
import librosa
from tensorflow import keras

# Load audio data and extract features
def load_audio(file_path):
    audio, sr = librosa.load(file_path)
    mfcc = librosa.feature.mfcc(audio, sr=sr)
    return mfcc.T

# Load data and labels
data = []
labels = []

for i, category in enumerate(['blues', 'classical', 'country', 'disco', 'hiphop', 'jazz', 'metal', 'pop', 'reggae', 'rock']):
    files = librosa.util.find_files(f'data/{category}')
    for file in files:
        audio = load_audio(file)
        data.append(audio)
        labels.append(i)

# Preprocess data
data = np.concatenate(data, axis=0)
labels = keras.utils.to_categorical(labels)

# Define the model architecture
model = keras.Sequential([
    keras.layers.Reshape((13, 87, 1), input_shape=(13, 87)),
    keras.layers.Conv2D(32, (3, 3), activation='relu'),
    keras.layers.MaxPooling2D((3, 3)),
    keras.layers.Flatten(),
    keras.layers.Dense(64, activation='relu'),
    keras.layers.Dense(10, activation='softmax'),
])

# Compile the model
model.compile(optimizer=keras.optimizers.Adam(0.001),
              loss=keras.losses.CategoricalCrossentropy(),
              metrics=['accuracy'])

# Train the model
model.fit(data, labels, epochs=20, batch_size=32)

In this example, the load_audio function uses the librosa library to load audio files and extract Mel-frequency cepstral coefficients (MFCCs), which are commonly used as features for audio classification tasks. The data and labels are then loaded, preprocessed, and split into training and validation sets. The neural network architecture consists of a reshape layer to change the data shape, a convolutional layer with 32 filters, a max pooling layer, a flattening layer, and two dense layers. The model is compiled with the Adam optimizer, categorical crossentropy loss, and accuracy as the evaluation metric. Finally, the model is trained for 20 epochs with a batch size of 32.

# Load a new audio file for prediction
new_audio = load_audio('new_audio.wav')

# Predict the category for the new audio
prediction = model.predict(new_audio)

# Convert the prediction to a categorical label
predicted_label = np.argmax(prediction)

The predict method returns a probability distribution over the 10 categories, which can be converted to the predicted label by finding the index of the highest probability.

It's also important to note that the model should be saved and loaded for later use to avoid having to retrain the model every time you want to use it. You can save a Keras model using the save method and load it using the keras.models.load_model function:

model.save('audio_classifier.h5')

# Load a saved model
loaded_model = keras.models.load_model('audio_classifier.h5')