WWW1M / common /FastFacts.py
GauravGoel11's picture
initial commit
f71ff04 verified
import pandas as pd
class FastFacts:
def __init__(self):
self.facts = {} # Dictionary to store facts by category
def add_fact(self, category, fact):
"""
Add a single fact under a specific category.
"""
if not isinstance(category, str) or not isinstance(fact, str):
print("Both category and fact must be strings.")
return
# Initialize category if it doesn't exist
if category not in self.facts:
self.facts[category] = []
self.facts[category].append(fact)
def add_facts(self, category_facts):
"""
Add multiple facts under their respective categories.
category_facts should be a dictionary where keys are categories and values are lists of facts.
"""
if not isinstance(category_facts, dict):
print("Facts must be provided as a dictionary with categories as keys.")
return
for category, facts in category_facts.items():
if not isinstance(category, str) or not isinstance(facts, list):
print(f"Skipping invalid category or facts: {category}")
continue
if category not in self.facts:
self.facts[category] = []
self.facts[category].extend(f for f in facts if isinstance(f, str))
def get_all_facts(self):
"""
Returns all facts grouped by category.
"""
return self.facts
def get_facts_by_category(self, category):
"""
Returns all facts under a specific category.
"""
return self.facts.get(category, [])
def get_categories(self):
"""
Returns a list of all available categories.
"""
return list(self.facts.keys())
def __repr__(self):
if not self.facts:
return f"{self.__class__.__name__}: No facts available"
return "\n".join(
f"{category}: " + ", ".join(f"<{fact}>" for fact in facts)
for category, facts in self.facts.items()
)
def to_dict(self):
"""
Convert the FastFacts to a dictionary.
"""
return {"facts": self.facts}
@staticmethod
def read_from_excel(fact_file):
"""
Read facts from an Excel file and populate a FastFacts object.
Args:
fact_file (str): Path to the Excel file.
Returns:
FastFacts: A populated FastFacts object.
"""
try:
df = pd.read_excel(fact_file)
# Ensure the expected columns exist
if "Category" not in df.columns or "FastFacts" not in df.columns:
print("Error: Expected columns 'Category' and 'FastFacts' not found in the file.")
return None
# Drop rows with missing FastFacts
df = df.dropna(subset=["FastFacts"])
# Group facts by category
grouped_facts = df.groupby("Category")["FastFacts"].apply(list).to_dict()
# Create a FastFacts object and populate it
fast_facts_obj = FastFacts()
fast_facts_obj.add_facts(grouped_facts)
return fast_facts_obj
except Exception as e:
print(f"An error occurred while reading from the Excel file: {e}")
return None