Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Just beginning
#1
I have downloaded and installed python wins from Microsoft v 3.12.3 using default installation.

I got these three files: the first gen_metadata.py the second gen_prompts.py and the third get_next_prompts.sh files off of youtube https://www.youtube.com/watch?v=7ee1G-IGmI4&t=768s to help me automate some of the things I am doing.

I have no idea how to install or where to place them in the Python program on my windows 11 desktop. I understand that this is probably way out of line in asking anyone on this forum to show me how but I really have to given I am a dumb-sh..

Please.

--------------

#!/usr/local/bin/python3
import os

# Define a function to extract the first two words from a line
def extract_first_two_words(line):
    return ' '.join(line.split()[:2])

# Define a function to remove anything starting with '--' and the first two words from the prompt
def format_prompt(line):
    # Remove comments starting with '--'
    formatted_line = line.split('--')[0].strip()
    # Remove the first two words
    formatted_line = ' '.join(formatted_line.split()[2:])
    return formatted_line

def quoted(theStr):
    return f'"{theStr}"'

def get_keywords(sentence):
    if not sentence:
        return ""
    
    # Define a set of stopwords
    stopwords = {'with', 'the', 'and', 'a', 'an', 'in', 'on', 'at', 'of', 'to', 'for', 'by', 'from', 'into'}
    
    # Tokenize the sentence into words
    words = sentence.split()
    
    # Remove stopwords and words without alphabetic characters, remove punctuation, and make lowercase
    keywords = [word.strip('.,:;?!()-[]{}\\/|<>"\'').lower() for word in words 
                if word.lower() not in stopwords and any(c.isalpha() for c in word)]
    
    # Join keywords with comma separated
    keywords = ', '.join(keywords)
    return keywords

# Read prompts from the file
with open(os.path.expanduser('~/prompts.txt')) as file:
    prompts = file.readlines()

# Prepare the CSV header
csv_header = "Filename,Title,Keywords,Category,Releases"

# Write the header to the CSV file
with open("csv-adobe.csv", "w") as csv_file:
    csv_file.write(csv_header + "\n")

# Iterate through each file in the current directory
for filename in os.listdir('.'):
    if os.path.isfile(filename):
        # Initialize a list to store matching prompts for each filename
        matching_prompts = []
        
        # Iterate through each prompt to find matches
        for prompt in prompts:
            # Format the prompt
            formatted_prompt = format_prompt(prompt)
            
            # Extract first two words from the prompt
            first_two_words = ' '.join(prompt.split()[:2]).replace(' ', '_')
            
            # Check if the filename contains the first two words followed by an underscore or a dot
            if f"{first_two_words}_" in filename or f"{first_two_words}." in filename:
                keywords = get_keywords(formatted_prompt)
                matching_prompts.append((formatted_prompt.strip(), keywords))
        
        # Append data to the CSV file for the current filename
        with open("csv-adobe.csv", "a") as csv_file:
            for title, keywords in matching_prompts:
                filename = quoted(filename)
                title = quoted(title)
                keywords = quoted(keywords)
                category = "8"  # Assuming category 8 is default
                csv_file.write(f"{filename},{title},{keywords},{category},\n")

# After writing data to the CSV file, read and print its contents
with open("csv-adobe.csv", "r") as csv_file:
    print(csv_file.read())
-----------------------------------------

#!/usr/local/bin/python3
import os
from datetime import datetime

# Load prompts from file
promptList = []
file_path = os.path.expanduser("~/prompts_input.txt")
with open(file_path, 'r') as file:
    for line in file:
        line = line.strip()
        if line:  # Check if line is not empty
            promptList.append(line)

style = "Lofi style illustration"
aspectRatio = "16:9"

promptList = sorted(set(promptList))
promptId = 0


# Open the file for writing in your home directory
home_dir = os.path.expanduser("~")
file_path = os.path.join(home_dir, "prompts.txt")

# Function to generate the list
def generate_list(promptList, promptAdd, file):
    global promptId
    # Define the ID and promptList
    # Get the current date and time
    genId = datetime.now().strftime("%Y%m%d%H%M%S") + "list"

    for promptItem in promptList:
        promptId += 1
        line = f"{genId} {promptId} {promptItem} {promptAdd}\n"
        file.write(line)


with open(file_path, 'w') as file:
    generate_list(promptList, f"{style} --ar {aspectRatio}", file)

# Replace this with the shell command you want to execute
command = "cat ~/prompts.txt"

print("\nCommands: ")
print(command)
-----------------------------------

Bash Script:
#!/bin/bash

# CHANGE AS NEEDED.
work="$HOME"
prompts="$HOME/prompts.txt"

# CHANGE AS NEEDED.
# Define the URL you want to open in Chrome
url="https://discord.com/channels/1136822967897178152/1226570210291748944"

# CHANGE AS NEEDED.
# Delay in seconds, recommend
urlDelay=5
promptDelay=10

# Main
if [ ! -f "$prompts" ]; then
   echo "$prompts file not found"
   exit 1
fi

# Prompter apple script:
function send_prompt() {
    # Check if clipboard is empty
    clipboardIsEmpty=$(osascript -e 'the clipboard is equal to ""')
    if [ "$clipboardIsEmpty" = "true" ]; then
        echo "Clipboard is empty."
        return 1
    fi

    osascript <<EOF
    tell application "Google Chrome"
        activate
    end tell

    tell application "System Events"
        keystroke (ASCII character 27)
        delay 2
        keystroke "/" using {option down}
        delay 1
        keystroke "imagine"
        delay 1
        keystroke tab
        delay 1
        keystroke "v" using {command down}
        delay 1
        keystroke return
    end tell
EOF
}

# Check if Google Chrome is already running
if ! pgrep -x "Google Chrome" > /dev/null; then
    # If Chrome is not running, open it
    open -a "Google Chrome"
fi

# Activate Chrome
echo "Activate chrome"
osascript -e 'tell application "Google Chrome" to activate'

# Wait for a moment to ensure Chrome is active
sleep 1

# Open the URL in a new tab or window
echo "open URL"
osascript -e 'tell application "Google Chrome" to set URL of the active tab of the first window to "'"$url"'"'
status=$?
if [ "$status" != 0 ]; then
   echo "Bad status, exit"
   exit 1
fi

sleep "$urlDelay"

###################################################
prev=""
# Function to check if clipboard is empty
function clipboard_check {
    clipboard=$(pbpaste)
    if [ "$clipboard" == "$prev" ]; then
      echo "End"
      exit 0
    fi

    prev="$clipboard"
    if [ -z "$clipboard" ]; then
        return 0 # Clipboard is empty
    else
        return 1 # Clipboard is not empty
    fi
}

max=$(wc -l < "$prompts")
echo "Will loop for max: $max"

# Run the loop N times or until clipboard is empty
for (( i=1; i<=$max; i++ )); do
    echo "Getting $i of $max prompts"
    head -${i} $prompts | tail -1 | pbcopy
    
    clipboard_check
    if [ $? -eq 0 ]; then
      echo "skip line"
    else
      echo "will paste"
      pbpaste
    
      # Run the AppleScript
      send_prompt

      # Delay between runs (adjust the delay as needed)
      sleep "$promptDelay"
    fi
done
Reply
#2
(Apr-15-2024, 01:22 AM)dalekeel Wrote: I have downloaded and installed python wins from Microsoft v 3.12.3 using default installation.

I got these three files: the first gen_metadata.py the second gen_prompts.py and the third get_next_prompts.sh files off of youtube https://www.youtube.com/watch?v=7ee1G-IGmI4&t=768s to help me automate some of the things I am doing.

I have no idea how to install or where to place them in the Python program on my windows 11 desktop. I understand that this is probably way out of line in asking anyone on this forum to show me how but I really have to given I am a dumb-sh..

Please.

--------------

#!/usr/local/bin/python3
import os

# Define a function to extract the first two words from a line
def extract_first_two_words(line):
    return ' '.join(line.split()[:2])

# Define a function to remove anything starting with '--' and the first two words from the prompt
def format_prompt(line):
    # Remove comments starting with '--'
    formatted_line = line.split('--')[0].strip()
    # Remove the first two words
    formatted_line = ' '.join(formatted_line.split()[2:])
    return formatted_line

def quoted(theStr):
    return f'"{theStr}"'

def get_keywords(sentence):
    if not sentence:
        return ""
    
    # Define a set of stopwords
    stopwords = {'with', 'the', 'and', 'a', 'an', 'in', 'on', 'at', 'of', 'to', 'for', 'by', 'from', 'into'}
    
    # Tokenize the sentence into words
    words = sentence.split()
    
    # Remove stopwords and words without alphabetic characters, remove punctuation, and make lowercase
    keywords = [word.strip('.,:;?!()-[]{}\\/|<>"\'').lower() for word in words 
                if word.lower() not in stopwords and any(c.isalpha() for c in word)]
    
    # Join keywords with comma separated
    keywords = ', '.join(keywords)
    return keywords

# Read prompts from the file
with open(os.path.expanduser('~/prompts.txt')) as file:
    prompts = file.readlines()

# Prepare the CSV header
csv_header = "Filename,Title,Keywords,Category,Releases"

# Write the header to the CSV file
with open("csv-adobe.csv", "w") as csv_file:
    csv_file.write(csv_header + "\n")

# Iterate through each file in the current directory
for filename in os.listdir('.'):
    if os.path.isfile(filename):
        # Initialize a list to store matching prompts for each filename
        matching_prompts = []
        
        # Iterate through each prompt to find matches
        for prompt in prompts:
            # Format the prompt
            formatted_prompt = format_prompt(prompt)
            
            # Extract first two words from the prompt
            first_two_words = ' '.join(prompt.split()[:2]).replace(' ', '_')
            
            # Check if the filename contains the first two words followed by an underscore or a dot
            if f"{first_two_words}_" in filename or f"{first_two_words}." in filename:
                keywords = get_keywords(formatted_prompt)
                matching_prompts.append((formatted_prompt.strip(), keywords))
        
        # Append data to the CSV file for the current filename
        with open("csv-adobe.csv", "a") as csv_file:
            for title, keywords in matching_prompts:
                filename = quoted(filename)
                title = quoted(title)
                keywords = quoted(keywords)
                category = "8"  # Assuming category 8 is default
                csv_file.write(f"{filename},{title},{keywords},{category},\n")

# After writing data to the CSV file, read and print its contents
with open("csv-adobe.csv", "r") as csv_file:
    print(csv_file.read())
-----------------------------------------

#!/usr/local/bin/python3
import os
from datetime import datetime

# Load prompts from file
promptList = []
file_path = os.path.expanduser("~/prompts_input.txt")
with open(file_path, 'r') as file:
    for line in file:
        line = line.strip()
        if line:  # Check if line is not empty
            promptList.append(line)

style = "Lofi style illustration"
aspectRatio = "16:9"

promptList = sorted(set(promptList))
promptId = 0


# Open the file for writing in your home directory
home_dir = os.path.expanduser("~")
file_path = os.path.join(home_dir, "prompts.txt")

# Function to generate the list
def generate_list(promptList, promptAdd, file):
    global promptId
    # Define the ID and promptList
    # Get the current date and time
    genId = datetime.now().strftime("%Y%m%d%H%M%S") + "list"

    for promptItem in promptList:
        promptId += 1
        line = f"{genId} {promptId} {promptItem} {promptAdd}\n"
        file.write(line)


with open(file_path, 'w') as file:
    generate_list(promptList, f"{style} --ar {aspectRatio}", file)

# Replace this with the shell command you want to execute
command = "cat ~/prompts.txt"

print("\nCommands: ")
print(command)
-----------------------------------
bash Script:
#!/bin/bash

# CHANGE AS NEEDED.
work="$HOME"
prompts="$HOME/prompts.txt"

# CHANGE AS NEEDED.
# Define the URL you want to open in Chrome
url="https://discord.com/channels/1136822967897178152/1226570210291748944"

# CHANGE AS NEEDED.
# Delay in seconds, recommend
urlDelay=5
promptDelay=10

# Main
if [ ! -f "$prompts" ]; then
   echo "$prompts file not found"
   exit 1
fi

# Prompter apple script:
function send_prompt() {
    # Check if clipboard is empty
    clipboardIsEmpty=$(osascript -e 'the clipboard is equal to ""')
    if [ "$clipboardIsEmpty" = "true" ]; then
        echo "Clipboard is empty."
        return 1
    fi

    osascript <<EOF
    tell application "Google Chrome"
        activate
    end tell

    tell application "System Events"
        keystroke (ASCII character 27)
        delay 2
        keystroke "/" using {option down}
        delay 1
        keystroke "imagine"
        delay 1
        keystroke tab
        delay 1
        keystroke "v" using {command down}
        delay 1
        keystroke return
    end tell
EOF
}

# Check if Google Chrome is already running
if ! pgrep -x "Google Chrome" > /dev/null; then
    # If Chrome is not running, open it
    open -a "Google Chrome"
fi

# Activate Chrome
echo "Activate chrome"
osascript -e 'tell application "Google Chrome" to activate'

# Wait for a moment to ensure Chrome is active
sleep 1

# Open the URL in a new tab or window
echo "open URL"
osascript -e 'tell application "Google Chrome" to set URL of the active tab of the first window to "'"$url"'"'
status=$?
if [ "$status" != 0 ]; then
   echo "Bad status, exit"
   exit 1
fi

sleep "$urlDelay"

###################################################
prev=""
# Function to check if clipboard is empty
function clipboard_check {
    clipboard=$(pbpaste)
    if [ "$clipboard" == "$prev" ]; then
      echo "End"
      exit 0
    fi

    prev="$clipboard"
    if [ -z "$clipboard" ]; then
        return 0 # Clipboard is empty
    else
        return 1 # Clipboard is not empty
    fi
}

max=$(wc -l < "$prompts")
echo "Will loop for max: $max"

# Run the loop N times or until clipboard is empty
for (( i=1; i<=$max; i++ )); do
    echo "Getting $i of $max prompts"
    head -${i} $prompts | tail -1 | pbcopy
    
    clipboard_check
    if [ $? -eq 0 ]; then
      echo "skip line"
    else
      echo "will paste"
      pbpaste
    
      # Run the AppleScript
      send_prompt

      # Delay between runs (adjust the delay as needed)
      sleep "$promptDelay"
    fi
done


To run the Python scripts (gen_metadata.py, gen_prompts.py) you downloaded, save them in a folder on your Windows 11 PC and execute them via Command Prompt, ensuring Python is correctly installed and accessible. For the shell script (get_next_prompts.sh), you'll need additional software like Git Bash or Windows Subsystem for Linux (WSL), as Windows doesn't natively support shell scripts. Open the terminal application for Git Bash or WSL, navigate to the directory containing the script, and run it with bash get_next_prompts.sh. If the scripts require modifications, such as adjusting file paths, you can edit them using a text editor like Notepad++ or Visual Studio Code.
Reply
#3
Oh dear, a Windows user, poor you!

Go here, download the Windoze installer.

Should install itself, maybe some questions on the way.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Program doesnt return beginning bilisim19 2 976 Feb-15-2023, 06:23 PM
Last Post: Larz60+
  List of dataframe values beginning with x,y or z glidecode 3 1,986 Nov-08-2021, 10:16 PM
Last Post: glidecode
  How to start the program from the beginning. iamaghost 5 3,035 Feb-23-2021, 03:40 AM
Last Post: deanhystad
  want to change the beginning of the result Rudinirudini 5 3,645 Nov-15-2018, 11:28 AM
Last Post: Rudinirudini
  Beginning of Beginner Help: Should I start with Python? appdevelnewb 2 3,106 Jul-23-2018, 11:17 PM
Last Post: appdevelnewb
  Wrap from end to beginning. 27 to 1, 28 to 2 etc DreamingInsanity 5 3,748 Jun-24-2018, 01:02 PM
Last Post: ljmetzger
  How to Loop CSV File Beginning at Specific Row? bmccollum 5 40,448 Nov-05-2017, 11:04 PM
Last Post: bmccollum
  Need help for beginning coding sylas 13 8,403 Mar-28-2017, 06:36 AM
Last Post: sylas

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020