Skip to main content
Loading...

More Python Posts

import os
import sys
import argparse
import json
import csv
import getpass
import string
import random
import re

from datetime import datetime
import ldap
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
from requests.auth import HTTPBasicAuth
import validators



def create_guac_connection(BASE_URL, auth_token, ldap_group, computer, guac_group_id):
    '''
    creates a guac connection
    '''
    json_header = {'Accept': 'application/json'}
    query_parm_payload = { 'token': auth_token }

    payload_data = {
   "parentIdentifier":guac_group_id,
   "name":computer,
   "protocol":"vnc",
   "parameters":{
      "port":"5900",
      "read-only":"",
      "swap-red-blue":"",
      "cursor":"",
      "color-depth":"",
      "clipboard-encoding":"",
      "disable-copy":"",
      "disable-paste":"",
      "dest-port":"",
      "recording-exclude-output":"",
      "recording-exclude-mouse":"",
      "recording-include-keys":"",
      "create-recording-path":"",
      "enable-sftp":"true",
      "sftp-port":"",
      "sftp-server-alive-interval":"",
      "enable-audio":"",
      "audio-servername":"",
      "sftp-directory":"",
      "sftp-root-directory":"",
      "sftp-passphrase":"",
      "sftp-private-key":"",
      "sftp-username":"",
      "sftp-password":"",
      "sftp-host-key":"",
      "sftp-hostname":"",
      "recording-name":"",
      "recording-path":"",
      "dest-host":"",
      "password":"asdasd",
      "username":"asdasd",
      "hostname":"nt72310.cvad.unt.edu"
   },
   "attributes":{
      "max-connections":"",
      "max-connections-per-user":"1",
      "weight":"",
      "failover-only":"",
      "guacd-port":"",
      "guacd-encryption":"",
      "guacd-hostname":""
   }
}
    CREATE_CONNECTION_URL = BASE_URL + "/api/session/data/mysql/connections"

    create_connection_request = requests.post(CREATE_CONNECTION_URL, headers=json_header, params=query_parm_payload, data=payload_data, verify=False)
    create_connection_result = create_connection_request.status_code


    if create_connection_result == "200":
        print("Successfully created computer: " + computer)
    else: 
        print(create_connection_request.json())

    return create_connection_result
def format_timestamp(timestamp_epoch):
    """
    Convert epoch timestamp to formatted datetime string without using datetime package.
    
    Args:
        timestamp_epoch (int/float): Unix epoch timestamp (seconds since 1970-01-01 00:00:00 UTC)
        
    Returns:
        str: Formatted datetime string in 'YYYY-MM-DD HH:MM:SS' format
    """
    # Constants for time calculations
    SECONDS_PER_DAY = 86400
    SECONDS_PER_HOUR = 3600
    SECONDS_PER_MINUTE = 60
    
    # Handle negative timestamps and convert to integer
    timestamp = int(timestamp_epoch)
    
    # Calculate days since epoch and remaining seconds
    days_since_epoch = timestamp // SECONDS_PER_DAY
    remaining_seconds = timestamp % SECONDS_PER_DAY
    
    # Calculate hours, minutes, seconds
    hours = remaining_seconds // SECONDS_PER_HOUR
    remaining_seconds %= SECONDS_PER_HOUR
    minutes = remaining_seconds // SECONDS_PER_MINUTE
    seconds = remaining_seconds % SECONDS_PER_MINUTE
    
    # Calculate date (simplified, ignoring leap seconds)
    year = 1970
    days = days_since_epoch
    while days >= 365:
        is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
        days_in_year = 366 if is_leap else 365
        if days >= days_in_year:
            days -= days_in_year
            year += 1
    
    # Month lengths (non-leap year for simplicity, adjusted later for leap years)
    month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        month_lengths[1] = 29
    
    month = 0
    while days >= month_lengths[month]:
        days -= month_lengths[month]
        month += 1
    
    # Convert to 1-based indexing for month and day
    month += 1
    day = days + 1
    
    # Format the output string
    return f"{year:04d}-{month:02d}-{day:02d} {hours:02d}:{minutes:02d}:{seconds:02d}"

# Example timestamp (Unix epoch seconds)
timestamp = 1697054700
formatted_date = format_timestamp(timestamp)
print(formatted_date + " UTC")  # Output: 2023-10-11 18:45:00
import subprocess   #for the praat calls
import os   #for ffmpeg and the pause call at the end
#Even if we wanted all videos being rendered asynchronously, we couldn't see progress or errors
import glob #for the ambiguous files
import tempfile
audioFileDirectory = 'Audio Files'
timeList = {}
fileList = glob.glob(audioFileDirectory + '\\*.wav')
pipeList = {}
for fileName in fileList:
    arglist = ['Praat.exe', '--run', 'crosscorrelateMatch.praat', 'zeussound.wav', fileName, "0" , "300"]
    print(' '.join(arglist))
    pipe = subprocess.Popen(arglist, stdout=subprocess.PIPE)
    pipeList[fileName[len(audioFileDirectory)+1:-4]] = pipe #+1 because of back slash, -4 because .wav
#for fileName, pipe in pipeList.items():
#    text = pipe.communicate()[0].decode('utf-8')
#    timeList[fileName] = float(text[::2])
for fileName, pipe in pipeList.items():
    if float(pipe.communicate()[0].decode('utf-8')[::2]) > .0003:    #.000166 is not a match, and .00073 is a perfect match. .00053 is a tested match
        arglist = ['Praat.exe', '--run', 'crosscorrelate.praat', 'zeussound.wav', audioFileDirectory + '\\' + fileName + '.wav', "0" , "300"]
        print(' '.join(arglist))
        text = subprocess.Popen(arglist, stdout=subprocess.PIPE).communicate()[0].decode('utf-8')
        timeList[fileName] = float(text[::2])
clipLength = 10
for fileName, time in timeList.items():
    arglist = ['ffmpeg', '-i', '"'+fileName+'.mp4"', '-ss', str(time-clipLength), '-t', str(clipLength*2), '-acodec', 'copy' , '-vcodec', 'copy', '"ZEUS'+ fileName + '.mp4"']
    print(' '.join(arglist))
    os.system(' '.join(arglist))
tempFile = tempfile.NamedTemporaryFile(delete=False)
for fileName in glob.glob('ZEUS*.mp4'):
    tempFile.write(("file '" + os.path.realpath(fileName) + "'\n").encode());
tempFile.seek(0)
print(tempFile.read())
tempFile.close()
arglist = ['ffmpeg', '-safe', '0', '-f', 'concat', '-i', '"'+tempFile.name+'"', '-c', 'copy', 'ZeusMontage.mp4']
print(' '.join(arglist))
os.system(' '.join(arglist))
os.unlink(tempFile.name)    #Delete the temp file
#print(timeList)
os.system('PAUSE')