import gradio as gr
import numpy as np
import pandas as pd
import torch
import matplotlib.pyplot as plt
import json
import time
import os
from functools import partial
import datetime
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# AI Snipper Custom CSS
ai_snipper_css = """
/* AI Snipper Color Variables */
:root {
--ai-cyan: #06b6d4;
--ai-blue: #3b82f6;
--ai-purple: #8b5cf6;
--ai-teal: #14b8a6;
--ai-indigo: #6366f1;
--bg-primary: #0a0e16;
--bg-secondary: #1a2332;
--bg-tertiary: #2a3441;
--bg-card: #1e293b;
--bg-card-hover: #334155;
--text-primary: #ffffff;
--text-secondary: #e2e8f0;
--text-muted: #94a3b8;
--text-accent: #06b6d4;
--border-primary: #475569;
--border-accent: #06b6d4;
--gradient-primary: linear-gradient(135deg, #06b6d4, #3b82f6, #8b5cf6);
--gradient-secondary: linear-gradient(135deg, #0a0e16 0%, #1a2332 50%, #2a3441 100%);
--gradient-button: linear-gradient(135deg, #06b6d4, #3b82f6);
--gradient-card: linear-gradient(135deg, #1e293b 0%, #334155 100%);
}
/* Main container styling */
.gradio-container {
background: var(--gradient-secondary) !important;
color: var(--text-primary) !important;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif !important;
min-height: 100vh !important;
}
/* Force text visibility */
.gradio-container * {
color: inherit !important;
}
/* Header styling */
.gradio-container h1 {
background: var(--gradient-primary) !important;
-webkit-background-clip: text !important;
-webkit-text-fill-color: transparent !important;
background-clip: text !important;
text-align: center !important;
font-size: 3rem !important;
font-weight: 800 !important;
margin-bottom: 1rem !important;
text-shadow: 0 0 20px rgba(6, 182, 212, 0.3) !important;
}
.gradio-container h2, .gradio-container h3, .gradio-container h4, .gradio-container h5, .gradio-container h6 {
color: var(--text-primary) !important;
font-weight: 600 !important;
}
/* Card/Panel styling */
.gr-box, .gr-form, .gr-panel {
background: var(--gradient-card) !important;
border: 1px solid var(--border-primary) !important;
border-radius: 16px !important;
box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1) !important;
backdrop-filter: blur(10px) !important;
color: var(--text-primary) !important;
}
/* Group styling */
.gr-group {
background: var(--gradient-card) !important;
border: 1px solid var(--border-primary) !important;
border-radius: 12px !important;
padding: 1.5rem !important;
color: var(--text-primary) !important;
}
/* Text inputs - FIXED */
.gr-textbox textarea, .gr-textbox input {
background: var(--bg-secondary) !important;
border: 1px solid var(--border-primary) !important;
border-radius: 12px !important;
color: var(--text-primary) !important;
padding: 1rem !important;
font-family: inherit !important;
}
.gr-textbox textarea:focus, .gr-textbox input:focus {
border-color: var(--border-accent) !important;
box-shadow: 0 0 0 3px rgba(6, 182, 212, 0.1) !important;
outline: none !important;
color: var(--text-primary) !important;
}
.gr-textbox textarea::placeholder, .gr-textbox input::placeholder {
color: var(--text-muted) !important;
opacity: 0.8 !important;
}
/* Labels - FIXED */
.gr-textbox label, .gr-slider label, .gr-radio label, .gr-checkbox label, label {
color: var(--text-secondary) !important;
font-weight: 500 !important;
margin-bottom: 0.5rem !important;
}
/* All text elements */
p, span, div:not(.gr-button), .gr-markdown {
color: var(--text-secondary) !important;
}
/* Strong contrast for important text */
.gr-textbox label, .gr-form label {
color: var(--text-primary) !important;
font-weight: 600 !important;
}
/* Buttons */
.gr-button {
background: var(--gradient-button) !important;
border: none !important;
border-radius: 12px !important;
color: var(--text-primary) !important;
font-weight: 600 !important;
padding: 1rem 2rem !important;
transition: all 0.3s ease !important;
box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1) !important;
font-family: inherit !important;
}
.gr-button:hover {
transform: translateY(-2px) !important;
box-shadow: 0 10px 20px rgba(6, 182, 212, 0.3) !important;
filter: brightness(1.1) !important;
color: var(--text-primary) !important;
}
.gr-button.secondary {
background: var(--bg-card) !important;
color: var(--text-primary) !important;
border: 1px solid var(--border-primary) !important;
}
.gr-button.secondary:hover {
background: var(--bg-card-hover) !important;
border-color: var(--border-accent) !important;
color: var(--text-primary) !important;
}
/* Tabs - FIXED */
.gr-tab-nav {
background: var(--gradient-card) !important;
border-radius: 12px !important;
padding: 0.5rem !important;
}
.gr-tab-nav button {
background: transparent !important;
color: var(--text-secondary) !important;
border: none !important;
border-radius: 8px !important;
margin: 0 4px !important;
padding: 0.75rem 1.5rem !important;
transition: all 0.3s ease !important;
font-weight: 500 !important;
}
.gr-tab-nav button.selected {
background: var(--gradient-button) !important;
color: var(--text-primary) !important;
box-shadow: 0 2px 4px rgba(6, 182, 212, 0.3) !important;
}
.gr-tab-nav button:hover:not(.selected) {
background: var(--bg-card-hover) !important;
color: var(--text-primary) !important;
}
/* Tab content */
.gr-tabitem {
background: var(--gradient-card) !important;
border: 1px solid var(--border-primary) !important;
border-radius: 12px !important;
padding: 1.5rem !important;
margin-top: 1rem !important;
color: var(--text-primary) !important;
}
/* Audio and file upload */
.gr-audio, .gr-file-upload {
background: var(--gradient-card) !important;
border: 1px solid var(--border-primary) !important;
border-radius: 12px !important;
color: var(--text-secondary) !important;
}
.gr-file-upload {
border: 2px dashed var(--border-accent) !important;
}
/* Sliders */
.gr-slider input[type="range"] {
background: var(--bg-secondary) !important;
}
.gr-slider input[type="range"]::-webkit-slider-track {
background: var(--bg-secondary) !important;
border-radius: 6px !important;
}
.gr-slider input[type="range"]::-webkit-slider-thumb {
background: var(--gradient-button) !important;
border: none !important;
border-radius: 50% !important;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2) !important;
}
/* Radio buttons and checkboxes */
.gr-radio input[type="radio"], .gr-checkbox input[type="checkbox"] {
accent-color: var(--ai-cyan) !important;
}
.gr-radio .wrap, .gr-checkbox .wrap {
color: var(--text-secondary) !important;
}
/* Accordion */
.gr-accordion {
background: var(--gradient-card) !important;
border: 1px solid var(--border-primary) !important;
border-radius: 12px !important;
}
.gr-accordion summary {
background: var(--bg-card) !important;
color: var(--text-primary) !important;
padding: 1rem !important;
border-radius: 12px !important;
cursor: pointer !important;
font-weight: 600 !important;
}
.gr-accordion[open] summary {
border-bottom: 1px solid var(--border-primary) !important;
border-radius: 12px 12px 0 0 !important;
}
/* JSON and HTML output */
.gr-json, .gr-html {
background: var(--gradient-card) !important;
border: 1px solid var(--border-primary) !important;
border-radius: 12px !important;
color: var(--text-primary) !important;
padding: 1rem !important;
}
/* Plot containers */
.gr-plot {
background: var(--gradient-card) !important;
border: 1px solid var(--border-primary) !important;
border-radius: 12px !important;
padding: 1rem !important;
}
/* Progress bars */
.gr-progress {
background: var(--bg-secondary) !important;
border-radius: 6px !important;
}
.gr-progress-bar {
background: var(--gradient-button) !important;
border-radius: 6px !important;
}
/* Markdown content */
.gr-markdown, .gr-markdown * {
color: var(--text-secondary) !important;
}
.gr-markdown h1, .gr-markdown h2, .gr-markdown h3, .gr-markdown h4, .gr-markdown h5, .gr-markdown h6 {
color: var(--text-primary) !important;
font-weight: 600 !important;
}
/* Footer hiding */
footer {
visibility: hidden !important;
}
/* Scrollbars */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--bg-secondary);
border-radius: 4px;
}
::-webkit-scrollbar-thumb {
background: var(--gradient-button);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--ai-cyan);
}
/* Specific fixes for form elements */
.gr-form .gr-box, .gr-form .gr-group {
color: var(--text-primary) !important;
}
/* Ensure all children inherit proper colors */
.gr-form *, .gr-group *, .gr-box * {
color: inherit !important;
}
/* Additional text visibility fixes */
.block.svelte-1t38q2d {
color: var(--text-primary) !important;
}
/* Mobile responsiveness */
@media (max-width: 768px) {
.gradio-container h1 {
font-size: 2rem !important;
}
.gr-button {
width: 100% !important;
justify-content: center !important;
}
.gr-row {
flex-direction: column !important;
}
}
"""
"""
# Global variables to store models
tokenizer = None
ner_pipeline = None
pos_pipeline = None
intent_classifier = None
semantic_model = None
stt_model = None # Speech-to-text model
models_loaded = False
# Database to store keyword ranking history (in-memory database for this example)
# In a real app, you would use a proper database
ranking_history = {}
def load_models(progress=gr.Progress()):
"""Lazy-load models only when needed"""
global tokenizer, ner_pipeline, pos_pipeline, intent_classifier, semantic_model, stt_model, models_loaded
if models_loaded:
return True
try:
progress(0.1, desc="Loading models...")
# Use smaller models and load them sequentially to reduce memory pressure
from transformers import AutoTokenizer, pipeline
progress(0.2, desc="Loading tokenizer...")
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
progress(0.3, desc="Loading NER model...")
ner_pipeline = pipeline("ner", model="dslim/bert-base-NER")
progress(0.4, desc="Loading POS model...")
# Use smaller POS model
from transformers import AutoModelForTokenClassification, BertTokenizerFast
pos_model = AutoModelForTokenClassification.from_pretrained("vblagoje/bert-english-uncased-finetuned-pos")
pos_tokenizer = BertTokenizerFast.from_pretrained("vblagoje/bert-english-uncased-finetuned-pos")
pos_pipeline = pipeline("token-classification", model=pos_model, tokenizer=pos_tokenizer)
progress(0.6, desc="Loading intent classifier...")
# Use a smaller model for zero-shot classification
intent_classifier = pipeline(
"zero-shot-classification",
model="typeform/distilbert-base-uncased-mnli", # Smaller than BART
device=0 if torch.cuda.is_available() else -1 # Use GPU if available
)
progress(0.7, desc="Loading speech-to-text model...")
try:
# Load automatic speech recognition model
from transformers import WhisperProcessor, WhisperForConditionalGeneration
processor = WhisperProcessor.from_pretrained("openai/whisper-small.en")
stt_model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-small.en")
stt_model = (processor, stt_model)
except Exception as e:
print(f"Warning: Could not load speech-to-text model: {str(e)}")
stt_model = None # Set to None so we can check if it's available
progress(0.8, desc="Loading semantic model...")
try:
from sentence_transformers import SentenceTransformer
semantic_model = SentenceTransformer('all-MiniLM-L6-v2')
except Exception as e:
print(f"Warning: Could not load semantic model: {str(e)}")
semantic_model = None # Set to None so we can check if it's available
progress(1.0, desc="Models loaded successfully!")
models_loaded = True
return True
except Exception as e:
print(f"Error loading models: {str(e)}")
return f"Error: {str(e)}"
def speech_to_text(audio_path):
"""Convert speech to text using the loaded speech-to-text model"""
if stt_model is None:
return "Speech-to-text model not loaded. Please try text input instead."
try:
import librosa
import numpy as np
# Load audio file
audio, sr = librosa.load(audio_path, sr=16000)
# Process audio with Whisper
processor, model = stt_model
input_features = processor(audio, sampling_rate=16000, return_tensors="pt").input_features
# Generate token ids
predicted_ids = model.generate(input_features)
# Decode token ids to text
transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)[0]
return transcription
except Exception as e:
print(f"Error in speech_to_text: {str(e)}")
return f"Error processing speech: {str(e)}"
def handle_voice_input(audio):
"""Handle voice input and convert to text"""
if audio is None:
return "No audio detected. Please try again."
try:
# Convert speech to text
text = speech_to_text(audio)
return text
except Exception as e:
print(f"Error in handle_voice_input: {str(e)}")
return f"Error: {str(e)}"
def simulate_google_serp(keyword, num_results=10):
"""Simulate Google SERP results for a keyword"""
try:
# In a real implementation, this would call the Google API
# For now, we'll generate fake SERP data
# Deterministic seed for consistent results by keyword
np.random.seed(sum(ord(c) for c in keyword))
serp_results = []
domains = [
"example.com", "wikipedia.org", "medium.com", "github.com",
"stackoverflow.com", "amazon.com", "youtube.com", "reddit.com",
"linkedin.com", "twitter.com", "facebook.com", "instagram.com"
]
for i in range(1, num_results + 1):
domain = domains[i % len(domains)]
title = f"{keyword.title()} - {domain.split('.')[0].title()} Resource #{i}"
snippet = f"This is a simulated SERP result for '{keyword}'. Result #{i} would provide relevant information about this topic."
url = f"https://www.{domain}/{keyword.replace(' ', '-')}-resource-{i}"
position = i
ctr = round(0.3 * (0.85 ** (i - 1)), 4) # Simulate click-through rate decay
serp_results.append({
"position": position,
"title": title,
"url": url,
"domain": domain,
"snippet": snippet,
"ctr_estimate": ctr,
"impressions_estimate": np.random.randint(1000, 10000)
})
return serp_results
except Exception as e:
print(f"Error in simulate_google_serp: {str(e)}")
return []
def update_ranking_history(keyword, serp_results):
"""Update the ranking history for a keyword"""
try:
# Get current timestamp
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Initialize if keyword not in history
if keyword not in ranking_history:
ranking_history[keyword] = []
# Add new entry
ranking_history[keyword].append({
"timestamp": timestamp,
"results": serp_results[:5] # Store top 5 results for history
})
# Keep only last 10 entries for each keyword
if len(ranking_history[keyword]) > 10:
ranking_history[keyword] = ranking_history[keyword][-10:]
return True
except Exception as e:
print(f"Error in update_ranking_history: {str(e)}")
return False
def get_semantic_similarity(token, comparison_terms):
"""Calculate semantic similarity between a token and comparison terms"""
try:
from sklearn.metrics.pairwise import cosine_similarity
token_embedding = semantic_model.encode([token])[0]
comparison_embeddings = semantic_model.encode(comparison_terms)
similarities = []
for i, emb in enumerate(comparison_embeddings):
similarity = cosine_similarity([token_embedding], [emb])[0][0]
similarities.append((comparison_terms[i], float(similarity)))
return sorted(similarities, key=lambda x: x[1], reverse=True)
except Exception as e:
print(f"Error in semantic similarity: {str(e)}")
# Return dummy data on error
return [(term, 0.5) for term in comparison_terms]
def get_token_colors(token_type):
colors = {
"prefix": "#D8BFD8", # Light purple
"suffix": "#AEDAA4", # Light green
"stem": "#A4C2F4", # Light blue
"compound_first": "#FFCC80", # Light orange
"compound_second": "#FFCC80", # Light orange
"word": "#E5E5E5" # Light gray
}
return colors.get(token_type, "#E5E5E5")
def simulate_historical_data(token):
"""Generate simulated historical usage data for a token"""
eras = ["1900s", "1950s", "1980s", "2000s", "2010s", "Present"]
# Different patterns based on token characteristics
if len(token) > 8:
# Possibly a technical term - recent growth
values = [10, 20, 30, 60, 85, 95]
elif token.startswith(("un", "re", "de", "pre")):
# Prefix words tend to be older
values = [45, 50, 60, 70, 75, 80]
else:
# Standard pattern for common words
# Use token hash value modulo instead of hash() directly to avoid different results across runs
base = 50 + (sum(ord(c) for c in token) % 30)
# Use a fixed seed for reproducibility
np.random.seed(sum(ord(c) for c in token))
noise = np.random.normal(0, 5, 6)
values = [max(5, min(95, base + i*5 + n)) for i, n in enumerate(noise)]
return list(zip(eras, values))
def generate_origin_data(token):
"""Generate simulated origin/etymology data for a token"""
origins = [
{"era": "Ancient", "language": "Latin"},
{"era": "Ancient", "language": "Greek"},
{"era": "Medieval", "language": "Old English"},
{"era": "16th century", "language": "French"},
{"era": "18th century", "language": "Germanic"},
{"era": "19th century", "language": "Anglo-Saxon"},
{"era": "20th century", "language": "Modern English"}
]
# Deterministic selection based on the token
index = sum(ord(c) for c in token) % len(origins)
origin = origins[index]
note = f"First appeared in {origin['era']} texts derived from {origin['language']}."
origin["note"] = note
return origin
def analyze_token_types(tokens):
"""Identify token types (prefix, suffix, compound, etc.)"""
processed_tokens = []
prefixes = ["un", "re", "de", "pre", "post", "anti", "pro", "inter", "sub", "super"]
suffixes = ["ing", "ed", "ly", "ment", "tion", "able", "ible", "ness", "ful", "less"]
for token in tokens:
token_text = token.lower()
token_type = "word"
# Check for prefixes
for prefix in prefixes:
if token_text.startswith(prefix) and len(token_text) > len(prefix) + 2:
if token_text != prefix: # Make sure the word isn't just the prefix
token_type = "prefix"
break
# Check for suffixes
if token_type == "word":
for suffix in suffixes:
if token_text.endswith(suffix) and len(token_text) > len(suffix) + 2:
token_type = "suffix"
break
# Check for compound words (simplified)
if token_type == "word" and len(token_text) > 8:
token_type = "compound_first" # Simplified - in reality would need more analysis
processed_tokens.append({
"text": token_text,
"type": token_type
})
return processed_tokens
def plot_historical_data(historical_data):
"""Create a plot of historical usage data, with error handling"""
try:
eras = [item[0] for item in historical_data]
values = [item[1] for item in historical_data]
plt.figure(figsize=(8, 3))
plt.bar(eras, values, color='skyblue')
plt.title('Historical Usage')
plt.xlabel('Era')
plt.ylabel('Usage Level')
plt.ylim(0, 100)
plt.xticks(rotation=45)
plt.tight_layout()
return plt
except Exception as e:
print(f"Error in plot_historical_data: {str(e)}")
# Return a simple error plot
plt.figure(figsize=(8, 3))
plt.text(0.5, 0.5, f"Error creating plot: {str(e)}",
horizontalalignment='center', verticalalignment='center')
plt.axis('off')
return plt
def create_evolution_chart(data, forecast_months=6, growth_scenario="Moderate"):
"""Create a simpler chart that's more compatible with Gradio"""
try:
import plotly.graph_objects as go
# Create a basic figure without subplots
fig = go.Figure()
# Add main trace for search volume
fig.add_trace(
go.Scatter(
x=[item["month"] for item in data],
y=[item["searchVolume"] for item in data],
name="Search Volume",
line=dict(color="#8884d8", width=3),
mode="lines+markers"
)
)
# Scale the other metrics to be visible on the same chart
max_volume = max([item["searchVolume"] for item in data])
scale_factor = max_volume / 100
# Add competition score (scaled)
fig.add_trace(
go.Scatter(
x=[item["month"] for item in data],
y=[item["competitionScore"] * scale_factor for item in data],
name="Competition Score",
line=dict(color="#82ca9d", width=2, dash="dot"),
mode="lines+markers"
)
)
# Add intent clarity (scaled)
fig.add_trace(
go.Scatter(
x=[item["month"] for item in data],
y=[item["intentClarity"] * scale_factor for item in data],
name="Intent Clarity",
line=dict(color="#ffc658", width=2, dash="dash"),
mode="lines+markers"
)
)
# Simple layout
fig.update_layout(
title=f"Keyword Evolution Forecast ({growth_scenario} Growth)",
xaxis_title="Month",
yaxis_title="Value",
legend=dict(orientation="h", y=1.1),
height=500
)
return fig
except Exception as e:
print(f"Error in chart creation: {str(e)}")
# Fallback to an even simpler chart
fig = go.Figure(data=go.Scatter(x=[1, 2, 3], y=[4, 1, 2]))
fig.update_layout(title="Fallback Chart (Error occurred)")
return fig
def create_ranking_history_chart(keyword_history):
"""Create a chart showing keyword ranking history over time"""
try:
if not keyword_history or len(keyword_history) < 2:
# Not enough data for a meaningful chart
fig = go.Figure()
fig.update_layout(
title="Insufficient Ranking Data",
annotations=[{
"text": "Need at least 2 data points for ranking history",
"showarrow": False,
"font": {"size": 16},
"xref": "paper",
"yref": "paper",
"x": 0.5,
"y": 0.5
}]
)
return fig
# Create a figure
fig = go.Figure()
# Extract timestamps and convert to datetime objects
timestamps = [entry["timestamp"] for entry in keyword_history]
dates = [datetime.datetime.strptime(ts, "%Y-%m-%d %H:%M:%S") for ts in timestamps]
# Get unique domains from all results
all_domains = set()
for entry in keyword_history:
for result in entry["results"]:
all_domains.add(result["domain"])
# Colors for different domains
domain_colors = {}
color_palette = [
"#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd",
"#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"
]
for i, domain in enumerate(all_domains):
domain_colors[domain] = color_palette[i % len(color_palette)]
# Track domains and their positions over time
domain_tracking = {domain: {"x": [], "y": [], "text": []} for domain in all_domains}
for i, entry in enumerate(keyword_history):
for result in entry["results"]:
domain = result["domain"]
position = result["position"]
title = result["title"]
domain_tracking[domain]["x"].append(dates[i])
domain_tracking[domain]["y"].append(position)
domain_tracking[domain]["text"].append(title)
# Add traces for each domain
for domain, data in domain_tracking.items():
if len(data["x"]) > 0: # Only add domains that have data
fig.add_trace(
go.Scatter(
x=data["x"],
y=data["y"],
mode="lines+markers",
name=domain,
line=dict(color=domain_colors[domain]),
hovertemplate="%{text}
Position: %{y}
Date: %{x}
Decode the genetic structure of your keywords with AI-powered analysis