import gradio as gr import pandas as pd import plotly.express as px import plotly.graph_objects as go from datasets import load_dataset # --------------------------------------------------------------------------- # Data loading # --------------------------------------------------------------------------- def load_data(lang="en"): """Load the dataset for the given language.""" repo = "AYI-NEDJIMI/ai-agents-fr" if lang == "fr" else "AYI-NEDJIMI/ai-agents-en" ds = load_dataset(repo, split="train") df = ds.to_pandas() return df # Pre-load both datasets at startup DATA = {} for _lang in ("en", "fr"): try: DATA[_lang] = load_data(_lang) except Exception as e: print(f"Warning: could not load {_lang} dataset: {e}") DATA[_lang] = pd.DataFrame(columns=["id", "category", "subcategory", "question", "answer", "metadata", "source_url", "language"]) ALL_CATEGORIES = ["All"] + sorted(DATA["en"]["category"].dropna().unique().tolist()) # --------------------------------------------------------------------------- # Helper functions # --------------------------------------------------------------------------- def get_df(lang): return DATA.get(lang, DATA["en"]) def filter_explorer(search_text, category, lang): df = get_df(lang) if category and category != "All": df = df[df["category"] == category] if search_text: mask = ( df["question"].str.contains(search_text, case=False, na=False) | df["category"].str.contains(search_text, case=False, na=False) | df["subcategory"].str.contains(search_text, case=False, na=False) ) df = df[mask] display_df = df[["category", "subcategory", "question"]].reset_index(drop=True) return display_df def get_item_details(evt: gr.SelectData, lang): df = get_df(lang) if evt is None: return "", "", "", "" row_idx = evt.index[0] if isinstance(evt.index, (list, tuple)) else evt.index # We need to map back; the explorer table was filtered, so we search by question question_val = evt.value if isinstance(evt.value, str) else "" # Fallback: try to find by row in full df if row_idx < len(df): row = df.iloc[row_idx] else: row = df.iloc[0] # Better approach: search by the selected row's question from the displayed table return ( str(row.get("question", "")), str(row.get("answer", "")), str(row.get("metadata", "")), str(row.get("source_url", "")) ) def get_details_by_id(item_id, lang): df = get_df(lang) if item_id is None or item_id == "": return "Select an item ID", "", "", "" try: item_id = int(item_id) except (ValueError, TypeError): return "Invalid ID", "", "", "" matches = df[df["id"] == item_id] if matches.empty: return "Item not found", "", "", "" row = matches.iloc[0] return ( str(row.get("question", "")), str(row.get("answer", "")), str(row.get("metadata", "")), str(row.get("source_url", "")) ) def get_qa_pairs(category, lang): df = get_df(lang) if category and category != "All": df = df[df["category"] == category] pairs = [] for _, row in df.iterrows(): pairs.append(f"### Q: {row['question']}\n\n**A:** {row['answer']}\n\n---\n") return "\n".join(pairs) if pairs else "No items found." def get_id_choices(lang): df = get_df(lang) return [str(i) for i in sorted(df["id"].unique().tolist())] def build_category_chart(lang): df = get_df(lang) counts = df["category"].value_counts().reset_index() counts.columns = ["Category", "Count"] fig = px.bar( counts, x="Category", y="Count", color="Category", title="Distribution by Category", template="plotly_white", color_discrete_sequence=px.colors.qualitative.Set2 ) fig.update_layout(showlegend=False, xaxis_tickangle=-30, margin=dict(t=50, b=80)) return fig def build_subcategory_chart(lang): df = get_df(lang) counts = df.groupby(["category", "subcategory"]).size().reset_index(name="Count") fig = px.bar( counts, x="subcategory", y="Count", color="category", title="Distribution by Subcategory", template="plotly_white", color_discrete_sequence=px.colors.qualitative.Set2 ) fig.update_layout(xaxis_tickangle=-45, margin=dict(t=50, b=120), legend_title_text="Category") return fig def build_pie_chart(lang): df = get_df(lang) counts = df["category"].value_counts().reset_index() counts.columns = ["Category", "Count"] fig = px.pie( counts, names="Category", values="Count", title="Category Proportions", template="plotly_white", color_discrete_sequence=px.colors.qualitative.Set2 ) fig.update_layout(margin=dict(t=50, b=30)) return fig # --------------------------------------------------------------------------- # Footer HTML # --------------------------------------------------------------------------- FOOTER_HTML = """
AI Agents & Frameworks Explorer — Built by AYI-NEDJIMI Consultants