fork download
  1. import os # Added to check if the CSV file exists
  2. import pandas as pd
  3. import mysql.connector
  4. import matplotlib.pyplot as plt
  5. import seaborn as sns
  6.  
  7. # Connect to MySQL Database
  8. def connect_to_database():
  9. try:
  10. return mysql.connector.connect(
  11. host="localhost",
  12. user="your_username",
  13. password="your_password",
  14. database="personality_db"
  15. )
  16. except mysql.connector.Error as e:
  17. print(f"Error connecting to MySQL: {e}")
  18. exit()
  19.  
  20. # Create a table for storing data
  21. def create_table():
  22. try:
  23. db = connect_to_database()
  24. cursor = db.cursor()
  25. cursor.execute("""
  26. CREATE TABLE IF NOT EXISTS personality_data (
  27. id INT AUTO_INCREMENT PRIMARY KEY,
  28. personality_type VARCHAR(255) UNIQUE,
  29. count INT DEFAULT 1
  30. )
  31. """)
  32. db.commit()
  33. db.close()
  34. except Exception as e:
  35. print(f"Error creating table: {e}")
  36. exit()
  37.  
  38. # Update personality counts in the database
  39. def update_personality_count(personality):
  40. try:
  41. db = connect_to_database()
  42. cursor = db.cursor()
  43. cursor.execute("""
  44. INSERT INTO personality_data (personality_type, count)
  45. VALUES (%s, 1)
  46. ON DUPLICATE KEY UPDATE count = count + 1
  47. """, (personality,))
  48. db.commit()
  49. db.close()
  50. except Exception as e:
  51. print(f"Error updating personality count: {e}")
  52.  
  53. # Fetch all data from the database
  54. def fetch_personality_data():
  55. try:
  56. db = connect_to_database()
  57. cursor = db.cursor(dictionary=True)
  58. cursor.execute("SELECT * FROM personality_data")
  59. result = cursor.fetchall()
  60. db.close()
  61. return result
  62. except Exception as e:
  63. print(f"Error fetching data: {e}")
  64. return []
  65.  
  66. # Save responses to CSV
  67. def save_to_csv(answers, personality):
  68. try:
  69. file_exists = os.path.isfile("responses.csv")
  70. data = pd.DataFrame([answers + [personality]], columns=["Q1", "Q2", "Q3", "Personality"])
  71. data.to_csv("responses.csv", mode='a', header=not file_exists, index=False)
  72. except Exception as e:
  73. print(f"Error saving to CSV: {e}")
  74.  
  75. # Ask questions function
  76. def ask_question(question, options):
  77. while True:
  78. print(f"\n{question}")
  79. for index, option in enumerate(options, start=1):
  80. print(f"{index}. {option}")
  81. try:
  82. answer = int(input("Enter the number corresponding to your choice: "))
  83. if 1 <= answer <= len(options):
  84. return options[answer - 1]
  85. else:
  86. print("Invalid choice. Please select a valid option.")
  87. except ValueError:
  88. print("Invalid input. Please enter a number.")
  89.  
  90. # Determine personality
  91. def determine_personality(answers):
  92. personality_map = {
  93. ("I prefer spending time alone", "I enjoy thinking logically", "I avoid taking risks"): "Introverted, Logical, Cautious",
  94. ("I enjoy socializing", "I enjoy thinking creatively", "I love taking risks"): "Extroverted, Creative, Risk-taking",
  95. ("I prefer spending time alone", "I enjoy thinking creatively", "I avoid taking risks"): "Introverted, Creative, Cautious",
  96. ("I enjoy socializing", "I enjoy thinking logically", "I love taking risks"): "Extroverted, Logical, Risk-taking"}
  97. return personality_map.get(tuple(answers), "Unique Personality Type")
  98.  
  99. # Display personality description
  100. def display_personality_description(personality):
  101. descriptions = {
  102. "Introverted, Logical, Cautious": "...values solitude, enjoys logical thinking, and tends to avoid risks.",
  103. "Extroverted, Creative, Risk-taking": "...loves socializing, thinks outside the box, and takes bold decisions.",
  104. "Introverted, Creative, Cautious": "...prefers alone time, enjoys creativity, and is careful with decisions.",
  105. "Extroverted, Logical, Risk-taking": "...loves social settings, enjoys logical problem-solving, and is open to new experiences.",
  106. "Unique Personality Type": "...has a distinct combination of traits that don't fit typical categories."}
  107.  
  108. print(f"\nYour Personality Type is: {personality}")
  109. print("Personality Description: Based on your answers, you're a person who...")
  110. print(descriptions.get(personality, "...has an undefined personality type."))
  111.  
  112. # Plot personality distribution
  113. def plot_personality_distribution():
  114. data = fetch_personality_data()
  115. if not data:
  116. print("No data available to plot.")
  117. return
  118.  
  119. df = pd.DataFrame(data)
  120. sns.barplot(x='personality_type', y='count', data=df, palette='viridis')
  121. plt.title("Personality Type Distribution")
  122. plt.xlabel("Personality Type")
  123. plt.ylabel("Count")
  124. plt.xticks(rotation=45)
  125. plt.show()
  126.  
  127. # Main function
  128. def main():
  129. create_table()
  130.  
  131. print("Welcome to the Personality Type Identifier!")
  132.  
  133. questions = [
  134. ("Do you prefer spending time alone or with others?",
  135. ["I prefer spending time alone", "I enjoy socializing"]),
  136. ("Do you prefer thinking logically or creatively?",
  137. ["I enjoy thinking logically", "I enjoy thinking creatively"]),
  138. ("Do you like to take risks or play it safe?",
  139. ["I avoid taking risks", "I love taking risks"])
  140. ]
  141.  
  142. # Collect answers
  143. answers = [ask_question(question, options) for question, options in questions]
  144.  
  145. # Determine personality type
  146. personality = determine_personality(answers)
  147. display_personality_description(personality)
  148.  
  149. # Save results
  150. save_to_csv(answers, personality)
  151. update_personality_count(personality)
  152.  
  153. # Plot personality distribution
  154. plot_personality_distribution()
  155.  
  156. if __name__ == "__main__":
  157. main()
  158.  
Success #stdin #stdout 0.04s 25616KB
stdin
Standard input is empty
stdout
import os  # Added to check if the CSV file exists
import pandas as pd
import mysql.connector
import matplotlib.pyplot as plt
import seaborn as sns

# Connect to MySQL Database
def connect_to_database():
    try:
        return mysql.connector.connect(
            host="localhost",
            user="your_username", 
            password="your_password",
            database="personality_db" 
        )
    except mysql.connector.Error as e:
        print(f"Error connecting to MySQL: {e}")
        exit()

# Create a table for storing data
def create_table():
    try:
        db = connect_to_database()
        cursor = db.cursor()
        cursor.execute("""
        CREATE TABLE IF NOT EXISTS personality_data (
            id INT AUTO_INCREMENT PRIMARY KEY,
            personality_type VARCHAR(255) UNIQUE,
            count INT DEFAULT 1
        )
        """)
        db.commit()
        db.close()
    except Exception as e:
        print(f"Error creating table: {e}")
        exit()

# Update personality counts in the database
def update_personality_count(personality):
    try:
        db = connect_to_database()
        cursor = db.cursor()
        cursor.execute("""
        INSERT INTO personality_data (personality_type, count)
        VALUES (%s, 1)
        ON DUPLICATE KEY UPDATE count = count + 1
        """, (personality,))
        db.commit()
        db.close()
    except Exception as e:
        print(f"Error updating personality count: {e}")

# Fetch all data from the database
def fetch_personality_data():
    try:
        db = connect_to_database()
        cursor = db.cursor(dictionary=True)
        cursor.execute("SELECT * FROM personality_data")
        result = cursor.fetchall()
        db.close()
        return result
    except Exception as e:
        print(f"Error fetching data: {e}")
        return []

# Save responses to CSV
def save_to_csv(answers, personality):
    try:
        file_exists = os.path.isfile("responses.csv")
        data = pd.DataFrame([answers + [personality]], columns=["Q1", "Q2", "Q3", "Personality"])
        data.to_csv("responses.csv", mode='a', header=not file_exists, index=False)
    except Exception as e:
        print(f"Error saving to CSV: {e}")

# Ask questions function
def ask_question(question, options):
    while True:
        print(f"\n{question}")
        for index, option in enumerate(options, start=1):
            print(f"{index}. {option}")
        try:
            answer = int(input("Enter the number corresponding to your choice: "))
            if 1 <= answer <= len(options):
                return options[answer - 1]
            else:
                print("Invalid choice. Please select a valid option.")
        except ValueError:
            print("Invalid input. Please enter a number.")

# Determine personality
def determine_personality(answers):
    personality_map = {
        ("I prefer spending time alone", "I enjoy thinking logically", "I avoid taking risks"): "Introverted, Logical, Cautious",
        ("I enjoy socializing", "I enjoy thinking creatively", "I love taking risks"): "Extroverted, Creative, Risk-taking",
        ("I prefer spending time alone", "I enjoy thinking creatively", "I avoid taking risks"): "Introverted, Creative, Cautious",
        ("I enjoy socializing", "I enjoy thinking logically", "I love taking risks"): "Extroverted, Logical, Risk-taking"}
    return personality_map.get(tuple(answers), "Unique Personality Type")

# Display personality description
def display_personality_description(personality):
    descriptions = {
        "Introverted, Logical, Cautious": "...values solitude, enjoys logical thinking, and tends to avoid risks.",
        "Extroverted, Creative, Risk-taking": "...loves socializing, thinks outside the box, and takes bold decisions.",
        "Introverted, Creative, Cautious": "...prefers alone time, enjoys creativity, and is careful with decisions.",
        "Extroverted, Logical, Risk-taking": "...loves social settings, enjoys logical problem-solving, and is open to new experiences.",
        "Unique Personality Type": "...has a distinct combination of traits that don't fit typical categories."}
    
    print(f"\nYour Personality Type is: {personality}")
    print("Personality Description: Based on your answers, you're a person who...")
    print(descriptions.get(personality, "...has an undefined personality type."))

# Plot personality distribution
def plot_personality_distribution():
    data = fetch_personality_data()
    if not data:
        print("No data available to plot.")
        return
    
    df = pd.DataFrame(data)
    sns.barplot(x='personality_type', y='count', data=df, palette='viridis')
    plt.title("Personality Type Distribution")
    plt.xlabel("Personality Type")
    plt.ylabel("Count")
    plt.xticks(rotation=45)
    plt.show()

# Main function
def main():
    create_table() 
    
    print("Welcome to the Personality Type Identifier!")
    
    questions = [
        ("Do you prefer spending time alone or with others?", 
         ["I prefer spending time alone", "I enjoy socializing"]),
        ("Do you prefer thinking logically or creatively?", 
         ["I enjoy thinking logically", "I enjoy thinking creatively"]),
        ("Do you like to take risks or play it safe?", 
         ["I avoid taking risks", "I love taking risks"])
    ]

    # Collect answers
    answers = [ask_question(question, options) for question, options in questions]
    
    # Determine personality type
    personality = determine_personality(answers)
    display_personality_description(personality)
    
    # Save results
    save_to_csv(answers, personality)
    update_personality_count(personality)
    
    # Plot personality distribution
    plot_personality_distribution()

if __name__ == "__main__":
    main()