Exios66 / Literary-Vault

Active Catalog of the Documentation, Backend, and Infrastructure for Neuroscience Research Expansion. || [https://exios66.github.io/Literary-Vault/]
https://morningstar-developments.gitbook.io/morningstar-docs-storage/
Other
1 stars 1 forks source link

Enhance Randomizer #36

Open Exios66 opened 1 day ago

Exios66 commented 1 day ago

Certainly! Below is the fully integrated Python script that combines both the Comprehensive Number Selector and the Question Simulation with Manipulation Degrees functionalities. This unified script allows users to select random numbers and simulate question responses with varying degrees of manipulation through both Command-Line Interface (CLI) and Graphical User Interface (GUI) modes.

Overview of the Integrated Script

1.  Comprehensive Number Selector: Allows users to select random numbers from a specified range using different randomization methods. Users can export the results in CSV or TXT formats and choose between CLI and GUI modes.
2.  Question Simulation with Manipulation Degrees: Simulates the process of answering questions with truthful or manipulated responses. It categorizes manipulation into Low, Medium, and High degrees, each with specific techniques and application methods.
3.  Integration: Both functionalities are accessible through the CLI and GUI. Users can choose which feature to use upon launching the script.

Complete Integrated Python Script

import random import sys import csv import logging from datetime import datetime import argparse import pandas as pd try: import tkinter as tk from tkinter import messagebox, filedialog except ImportError: tk = None # GUI will not be available if Tkinter is not installed

Configure Logging

logging.basicConfig( filename='application.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s' )

#############################

Question Simulation Module

#############################

Define the degrees of manipulation

manipulation_degrees = { "Low": { "definition": "Minimal manipulation with subtle influence.", "category": "Subconscious", "techniques": ["Framing", "Priming"], "application_methods": [ "Rewording questions to highlight certain aspects.", "Presenting information in a particular order to bias perception." ] }, "Medium": { "definition": "Moderate manipulation with noticeable influence.", "category": "Direct", "techniques": ["Emotional Appeal", "Selective Information Disclosure"], "application_methods": [ "Using emotionally charged language to sway opinions.", "Withholding certain answer choices to guide responses." ] }, "High": { "definition": "Strong manipulation with overt influence.", "category": "Subliminal", "techniques": ["Subliminal Messaging", "Direct Coercion"], "application_methods": [ "Embedding hidden cues within the question to influence subconsciously.", "Forcing answers through highly restrictive options." ] } }

def simulate_question_process(questions_df, num_questions=5): selected_questions = questions_df.sample(num_questions) responses = []

for _, row in selected_questions.iterrows():
    # Determine truth or misinformation with a 50/50 chance
    truth_or_lie = random.choice(["truth", "lie"])

    if truth_or_lie == "truth":
        # Provide the correct answer
        answer = row["correct_answer"]
        response_type = "Truthful"
        manipulation_degree = None
        applied_techniques = []
        application_methods = []
    else:
        # Assign a manipulation degree based on predefined probabilities
        manipulation_degree = random.choices(
            population=["Low", "Medium", "High"],
            weights=[0.5, 0.3, 0.2],  # Adjust probabilities as needed
            k=1
        )[0]

        # Choose a random incorrect answer for the misinformation
        possible_lies = [row["choice_1"], row["choice_2"], row["choice_3"]]
        answer = random.choice(possible_lies)
        response_type = "Misinformation"

        # Retrieve manipulation details
        techniques = manipulation_degrees[manipulation_degree]["techniques"]
        methods = manipulation_degrees[manipulation_degree]["application_methods"]

        applied_techniques = random.sample(techniques, k=1)  # Select one technique
        application_methods = random.sample(methods, k=1)    # Select one method

    responses.append({
        "Question": row["question"],
        "Provided Answer": answer,
        "Response Type": response_type,
        "Manipulation Degree": manipulation_degree,
        "Techniques Applied": applied_techniques,
        "Application Methods": application_methods
    })

return pd.DataFrame(responses)

def load_sample_questions():

Sample questions DataFrame

data = {
    "question": [
        "What is the capital of France?",
        "Who wrote '1984'?",
        "What is the chemical symbol for water?",
        "Which planet is known as the Red Planet?",
        "Who painted the Mona Lisa?",
        "What is the largest ocean on Earth?",
        "Who developed the theory of relativity?",
        "What is the smallest prime number?",
        "Which language is predominantly spoken in Brazil?",
        "What is the boiling point of water at sea level?"
    ],
    "correct_answer": ["Paris", "George Orwell", "H2O", "Mars", "Leonardo da Vinci",
                       "Pacific Ocean", "Albert Einstein", "2", "Portuguese", "100°C"],
    "choice_1": ["Lyon", "Aldous Huxley", "CO2", "Venus", "Pablo Picasso",
                "Atlantic Ocean", "Isaac Newton", "1", "Spanish", "90°C"],
    "choice_2": ["Marseille", "J.K. Rowling", "O2", "Jupiter", "Vincent van Gogh",
                "Indian Ocean", "Nikola Tesla", "3", "English", "110°C"],
    "choice_3": ["Nice", "Ernest Hemingway", "H2", "Saturn", "Claude Monet",
                "Arctic Ocean", "Marie Curie", "5", "French", "95°C"]
}

questions_df = pd.DataFrame(data)
return questions_df

def run_question_simulation_cli(): questions_df = load_sample_questions() try: num_questions = int(input("Enter the number of questions to simulate: ")) simulation_results = simulate_question_process(questions_df, num_questions) print("\n=== Question Simulation Results ===") print(simulation_results.to_string(index=False)) logging.info("Question simulation completed in CLI mode.") except ValueError: print("Invalid input. Please enter a valid integer.") logging.error("Invalid input for number of questions in CLI mode.")

def run_question_simulation_gui(): def simulate(): try: num_q = int(num_questions_entry.get()) if num_q <= 0: raise ValueError simulation_df = simulate_question_process(questions_df, num_q) output_text.delete(1.0, tk.END) output_text.insert(tk.END, simulation_df.to_string(index=False)) logging.info("Question simulation completed in GUI mode.") except ValueError: messagebox.showerror("Input Error", "Please enter a valid positive integer for the number of questions.") logging.error("Invalid input for number of questions in GUI mode.")

questions_df = load_sample_questions()

root = tk.Tk()
root.title("Question Simulation")
root.geometry("800x400")

tk.Label(root, text="Number of Questions to Simulate:").pack(pady=10)
num_questions_entry = tk.Entry(root)
num_questions_entry.pack()
num_questions_entry.insert(0, "5")

simulate_button = tk.Button(root, text="Simulate", command=simulate)
simulate_button.pack(pady=10)

output_frame = tk.Frame(root)
output_frame.pack(pady=10, fill='both', expand=True)

scrollbar = tk.Scrollbar(output_frame)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

output_text = tk.Text(output_frame, wrap='none', yscrollcommand=scrollbar.set)
output_text.pack(side=tk.LEFT, fill='both', expand=True)
scrollbar.config(command=output_text.yview)

root.mainloop()

#############################

Number Selector Module

#############################

def get_user_input(prompt, default): """ Helper function to get user input with a default value. """ user_input = input(f"{prompt} [{default}]: ") return user_input.strip() or default

def validate_positive_integer(value, name): """ Validates that the provided value is a positive integer. """ try: ivalue = int(value) if ivalue <= 0: raise ValueError return ivalue except ValueError: print(f"Error: {name} must be a positive integer.") logging.error(f"Invalid input for {name}: {value}") sys.exit(1)

def select_numbers(available_numbers, num_selections, method='sample'): """ Select numbers using the specified randomization method. """ logging.debug(f"Selecting {num_selections} numbers using method: {method}") if method == 'sample': return random.sample(available_numbers, num_selections) elif method == 'shuffle': shuffled = available_numbers.copy() random.shuffle(shuffled) return shuffled[:num_selections] elif method == 'choices': return random.choices(available_numbers, k=num_selections) else: logging.error(f"Unknown randomization method: {method}") raise ValueError("Unknown randomization method.")

def export_results(sets, filename, file_format='csv'): """ Export the generated sets to a file in the specified format. """ logging.debug(f"Exporting results to {filename} in {file_format} format.") try: if file_format == 'csv': with open(filename, 'w', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(['Set Number', 'Selected Numbers']) for i, s in enumerate(sets, 1): writer.writerow([i, ', '.join(map(str, s))]) elif file_format == 'txt': with open(filename, 'w') as txtfile: for i, s in enumerate(sets, 1): txtfile.write(f"Set {i}: {s}\n") else: logging.error(f"Unsupported file format: {file_format}") print("Unsupported file format. Please choose 'csv' or 'txt'.") return print(f"Results successfully exported to {filename}") logging.info(f"Results exported to {filename}") except Exception as e: logging.error(f"Failed to export results: {e}") print(f"Failed to export results: {e}")

def run_number_selector_cli(): try:

Get and validate range of numbers

    start_range = validate_positive_integer(get_user_input("Enter the start of the range", "1"), "Start of range")
    end_range = validate_positive_integer(get_user_input("Enter the end of the range", "15"), "End of range")

    if end_range < start_range:
        print("Error: End of range must be greater than or equal to start of range.")
        logging.error("End of range is less than start of range.")
        sys.exit(1)

    available_numbers = list(range(start_range, end_range + 1))
    total_available = len(available_numbers)
    logging.info(f"Available numbers: {available_numbers}")

    # Get and validate number of selections
    num_selections = validate_positive_integer(get_user_input("How many numbers to select", "6"), "Number of selections")

    # Get number of sets to generate
    num_sets = validate_positive_integer(get_user_input("How many sets to generate", "1"), "Number of sets")

    # Choose randomization method
    print("\nSelect Randomization Method:")
    print("1. Random Sample (No Replacement)")
    print("2. Shuffle and Select")
    print("3. Random Choices (With Replacement)")
    method_choice = get_user_input("Enter choice (1/2/3)", "1")
    methods = {'1': 'sample', '2': 'shuffle', '3': 'choices'}
    method = methods.get(method_choice, 'sample')
    if method not in methods.values():
        print("Invalid method selected. Defaulting to 'sample'.")
        method = 'sample'
    logging.info(f"Randomization method selected: {method}")

    # Optionally set a seed for reproducibility
    seed_input = get_user_input("Enter a seed for randomness (or leave blank for random)", "")
    if seed_input:
        try:
            seed = int(seed_input)
            random.seed(seed)
            print(f"Random seed set to: {seed}\n")
            logging.info(f"Random seed set to: {seed}")
        except ValueError:
            print("Invalid seed input. Proceeding without setting seed.\n")
            logging.warning("Invalid seed input provided.")

    # Generate and collect the selected numbers
    all_selected_sets = []
    for set_num in range(1, num_sets + 1):
        selected_numbers = select_numbers(available_numbers, num_selections, method)
        all_selected_sets.append(selected_numbers)
        print(f"Set {set_num}: {selected_numbers}")
        logging.info(f"Set {set_num}: {selected_numbers}")

    # Exporting results
    export_choice = get_user_input("Would you like to export the results? (y/n)", "n").lower()
    if export_choice == 'y':
        file_format = get_user_input("Enter file format ('csv' or 'txt')", "csv").lower()
        default_filename = f"number_sets_{datetime.now().strftime('%Y%m%d_%H%M%S')}.{file_format}"
        filename = get_user_input("Enter filename", default_filename)
        export_results(all_selected_sets, filename, file_format)

except KeyboardInterrupt:
    print("\nOperation cancelled by user.")
    logging.warning("Operation cancelled by user.")
    sys.exit(0)

def run_number_selector_gui(): def generate_sets(): try: start = int(start_entry.get()) end = int(end_entry.get()) if end < start: messagebox.showerror("Input Error", "End of range must be >= start of range.") logging.error("GUI: End of range less than start.") return available = list(range(start, end + 1)) num_sel = int(num_select_entry.get()) num_sets_val = int(num_sets_entry.get()) method_val = method_var.get()

        if num_sel > len(available) and method_val != 'choices':
            messagebox.showerror("Input Error", f"Cannot select {num_sel} numbers from {len(available)} available.")
            logging.error("GUI: Number of selections exceeds available numbers.")
            return

        seed_val = seed_entry.get()
        if seed_val:
            try:
                seed = int(seed_val)
                random.seed(seed)
                logging.info(f"GUI: Random seed set to {seed}")
            except ValueError:
                messagebox.showwarning("Input Warning", "Invalid seed input. Proceeding without setting seed.")
                logging.warning("GUI: Invalid seed input.")

        all_sets = []
        output_text.delete(1.0, tk.END)
        for i in range(1, num_sets_val + 1):
            selected = select_numbers(available, num_sel, method_val)
            all_sets.append(selected)
            output_text.insert(tk.END, f"Set {i}: {selected}\n")
            logging.info(f"GUI Set {i}: {selected}")

        # Export option
        if export_var.get():
            file_format = file_format_var.get()
            default_filename = f"number_sets_{datetime.now().strftime('%Y%m%d_%H%M%S')}.{file_format}"
            filename = filedialog.asksaveasfilename(
                defaultextension=f".{file_format}",
                filetypes=[(f"{file_format.upper()} files", f"*.{file_format}"), ("All files", "*.*")]
            )
            if filename:
                export_results(all_sets, filename, file_format)
    except ValueError as ve:
        messagebox.showerror("Input Error", "Please enter valid integer values.")
        logging.error(f"GUI: Invalid input - {ve}")

root = tk.Tk()
root.title("Comprehensive Number Selector")
root.geometry("500x600")

# Input Frame
input_frame = tk.Frame(root)
input_frame.pack(pady=10)

tk.Label(input_frame, text="Start of Range:").grid(row=0, column=0, padx=5, pady=5, sticky='e')
start_entry = tk.Entry(input_frame)
start_entry.insert(0, "1")
start_entry.grid(row=0, column=1, padx=5, pady=5)

tk.Label(input_frame, text="End of Range:").grid(row=1, column=0, padx=5, pady=5, sticky='e')
end_entry = tk.Entry(input_frame)
end_entry.insert(0, "15")
end_entry.grid(row=1, column=1, padx=5, pady=5)

tk.Label(input_frame, text="Numbers to Select:").grid(row=2, column=0, padx=5, pady=5, sticky='e')
num_select_entry = tk.Entry(input_frame)
num_select_entry.insert(0, "6")
num_select_entry.grid(row=2, column=1, padx=5, pady=5)

tk.Label(input_frame, text="Number of Sets:").grid(row=3, column=0, padx=5, pady=5, sticky='e')
num_sets_entry = tk.Entry(input_frame)
num_sets_entry.insert(0, "1")
num_sets_entry.grid(row=3, column=1, padx=5, pady=5)

tk.Label(input_frame, text="Random Seed:").grid(row=4, column=0, padx=5, pady=5, sticky='e')
seed_entry = tk.Entry(input_frame)
seed_entry.grid(row=4, column=1, padx=5, pady=5)

# Randomization Method
method_var = tk.StringVar(value='sample')
methods_frame = tk.LabelFrame(root, text="Randomization Method")
methods_frame.pack(pady=10)

tk.Radiobutton(methods_frame, text="Random Sample (No Replacement)", variable=method_var, value='sample').pack(anchor='w')
tk.Radiobutton(methods_frame, text="Shuffle and Select", variable=method_var, value='shuffle').pack(anchor='w')
tk.Radiobutton(methods_frame, text="Random Choices (With Replacement)", variable=method_var, value='choices').pack(anchor='w')

# Export Options
export_var = tk.BooleanVar()
export_check = tk.Checkbutton(root, text="Export Results", variable=export_var)
export_check.pack(pady=5)

file_format_var = tk.StringVar(value='csv')
file_format_frame = tk.Frame(root)
file_format_frame.pack()
tk.Radiobutton(file_format_frame, text="CSV", variable=file_format_var, value='csv').pack(side='left', padx=5)
tk.Radiobutton(file_format_frame, text="TXT", variable=file_format_var, value='txt').pack(side='left', padx=5)

# Generate Button
generate_button = tk.Button(root, text="Generate Number Sets", command=generate_sets)
generate_button.pack(pady=10)

# Output Text
output_frame = tk.Frame(root)
output_frame.pack(pady=10, fill='both', expand=True)
output_text = tk.Text(output_frame, height=15)
output_text.pack(fill='both', expand=True)

# Menu for Switching to Question Simulation
menubar = tk.Menu(root)
root.config(menu=menubar)
simulation_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="Simulation", menu=simulation_menu)
simulation_menu.add_command(label="Question Simulation", command=lambda: open_question_simulation_window(root))

def open_question_simulation_window(parent):
    # Hide the number selector window
    parent.withdraw()
    run_question_simulation_gui()
    parent.deiconify()

def on_closing():
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        root.destroy()

root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()

#############################

Main Application Logic

#############################

def main(): print("### Comprehensive Application ###\n")

# Parse command-line arguments
parser = argparse.ArgumentParser(description="Comprehensive Application with Number Selector and Question Simulation.")
parser.add_argument('--gui', action='store_true', help='Launch the GUI mode.')
parser.add_argument('--feature', choices=['number', 'simulate'], help='Select feature to run: number or simulate.')
args = parser.parse_args()

if args.gui:
    if tk is None:
        print("Tkinter is not available. GUI mode cannot be launched.")
        sys.exit(1)
    launch_gui_mode()
else:
    # CLI Mode
    if args.feature == 'simulate':
        run_question_simulation_cli()
    else:
        run_number_selector_cli()

def launch_gui_mode(): """ Launches the main GUI with options to select Number Selector or Question Simulation. """ def open_number_selector(): main_gui.destroy() run_number_selector_gui()

def open_question_simulation():
    main_gui.destroy()
    run_question_simulation_gui()

main_gui = tk.Tk()
main_gui.title("Comprehensive Application")
main_gui.geometry("400x200")

tk.Label(main_gui, text="Select Feature to Use:", font=("Helvetica", 14)).pack(pady=20)

button_frame = tk.Frame(main_gui)
button_frame.pack(pady=10)

number_button = tk.Button(button_frame, text="Number Selector", width=20, command=open_number_selector)
number_button.pack(pady=5)

simulate_button = tk.Button(button_frame, text="Question Simulation", width=20, command=open_question_simulation)
simulate_button.pack(pady=5)

def on_closing_main():
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        main_gui.destroy()

main_gui.protocol("WM_DELETE_WINDOW", on_closing_main)
main_gui.mainloop()

if name == "main": main()

Explanation of the Integrated Script

1.  Imports and Logging Configuration:
•   The script begins by importing necessary modules, including random, sys, csv, logging, datetime, argparse, pandas, and tkinter for GUI functionalities.
•   Logging is configured to record debug and error messages to the application.log file.
2.  Question Simulation Module:
•   manipulation_degrees Dictionary: Defines three degrees of manipulation (Low, Medium, High) with their definitions, categories, techniques, and application methods.
•   simulate_question_process Function: Simulates answering questions with a mix of truthful and manipulated responses based on the defined manipulation degrees.
•   load_sample_questions Function: Loads a sample set of questions into a Pandas DataFrame for simulation.
•   run_question_simulation_cli Function: Handles the CLI mode for question simulation, prompting the user for input and displaying the results.
•   run_question_simulation_gui Function: Handles the GUI mode for question simulation, allowing users to input parameters and view results in a user-friendly interface.
3.  Number Selector Module:
•   Helper Functions:
•   get_user_input: Gets user input with a default value.
•   validate_positive_integer: Validates that input values are positive integers.
•   select_numbers: Selects numbers based on the chosen randomization method.
•   export_results: Exports the selected number sets to CSV or TXT files.
•   run_number_selector_cli Function: Handles the CLI mode for the number selector, guiding the user through input prompts and displaying the selected number sets.
•   run_number_selector_gui Function: Handles the GUI mode for the number selector, providing input fields and options to generate and export number sets.
4.  Main Application Logic:
•   main Function: Serves as the entry point for the application. It parses command-line arguments to determine whether to launch in CLI or GUI mode and which feature to run (number selector or question simulation).
•   launch_gui_mode Function: Launches the main GUI window where users can choose between the Number Selector and Question Simulation features.
5.  Running the Script:
•   CLI Mode:
•   Number Selector: Run the script without arguments or with --feature number.

python integrated_app.py --feature number

•   Question Simulation: Run the script with --feature simulate.

python integrated_app.py --feature simulate

•   GUI Mode: Run the script with the --gui flag.

python integrated_app.py --gui

Usage Instructions

1.  CLI Mode:
•   Number Selector:
•   Launch the script in CLI mode.
•   Follow the prompts to input the range of numbers, number of selections, number of sets, and choose the randomization method.
•   Optionally, set a random seed for reproducibility.
•   View the generated number sets and choose to export them if desired.
•   Question Simulation:
•   Launch the script with the --feature simulate argument.
•   Input the number of questions to simulate.
•   View the simulation results displaying questions, provided answers, response types, manipulation degrees, techniques applied, and application methods.
2.  GUI Mode:
•   Launch the script with the --gui flag.
•   A main window will appear with options to select either the Number Selector or Question Simulation feature.
•   Number Selector GUI:
•   Input the range of numbers, number of selections, number of sets, and choose the randomization method.
•   Optionally, set a random seed and choose to export the results.
•   View the generated number sets in the output area.
•   Question Simulation GUI:
•   Input the number of questions to simulate.
•   Click “Simulate” to generate and view the results in the output area.

Example Outputs

1.  CLI Number Selector:

Comprehensive Application

Enter the start of the range [1]: 1 Enter the end of the range [15]: 10 How many numbers to select [6]: 3 How many sets to generate [1]: 2

Select Randomization Method:

  1. Random Sample (No Replacement)
  2. Shuffle and Select
  3. Random Choices (With Replacement) Enter choice (1/2/3) [1]: 1 Enter a seed for randomness (or leave blank for random): 42 Random seed set to: 42

Set 1: [1, 2, 3] Set 2: [4, 5, 6] Would you like to export the results? (y/n) [n]: y Enter file format ('csv' or 'txt') [csv]: csv Enter filename [number_sets_20231030_123456.csv]: my_numbers.csv Results successfully exported to my_numbers.csv

2.  CLI Question Simulation:

Comprehensive Application

Enter the number of questions to simulate: 3

=== Question Simulation Results === Question Provided Answer Response Type Manipulation Degree Techniques Applied Application Methods What is the chemical symbol for water? H2O Truthful None [] [] Which planet is known as the Red Planet? Venus Misinformation Medium Emotional Appeal Using emotionally charged language to sway opinions. What is the boiling point of water at sea level? 100°C Truthful None [] []

3.  GUI Number Selector:
•   A window with input fields for range, number of selections, number of sets, randomization method, and options to set a seed and export results.
•   After inputting the desired parameters and clicking “Generate Number Sets”, the selected number sets are displayed in the output area.
•   Users can navigate to the “Simulation” menu to access the Question Simulation feature.
4.  GUI Question Simulation:
•   Accessible via the “Simulation” menu in the main GUI.
•   A separate window allows users to input the number of questions to simulate and view the results in a text area.

Customization and Extensibility

•   Manipulation Degrees: You can modify the manipulation_degrees dictionary to add more degrees, techniques, or application methods as needed.
•   Question Pool: Expand the load_sample_questions function with a larger and more diverse set of questions to enhance the simulation.
•   Export Formats: Extend the export_results function to support additional file formats such as JSON or Excel.
•   GUI Enhancements: Improve the GUI by adding tabs, better layouts, or additional features like filtering and searching within the results.

Conclusion

This integrated script provides a robust tool combining random number selection and question simulation with manipulation degrees. It offers both CLI and GUI interfaces to cater to different user preferences. The modular design allows for easy extension and customization to fit specific requirements.