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()