import gradio as gr
from google_play_scraper import search, app as play_app
import os
import time
from datetime import datetime
import json
import requests
from huggingface_hub import HfApi, hf_hub_download, create_repo
# -----------------------------
# CONFIG & API CONNECTION
# -----------------------------
HF_TOKEN = os.getenv("HF_TOKEN")
APP_PASSWORD = os.getenv("APP_PASSWORD")
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY") # Ensure this is set in HF Space Secrets
DATASET_REPO = "kacapower/lexical-space-data"
THEME_FILE_NAME = "website_theme.xml"
# -----------------------------
# CORE FUNCTIONS
# -----------------------------
def save_theme_to_dataset(xml_file):
"""Saves the uploaded XML file directly to the private hf dataset."""
if xml_file is None:
return "❌ Please upload an XML file first."
try:
file_path = xml_file if isinstance(xml_file, str) else xml_file.name
try:
create_repo(
repo_id=DATASET_REPO,
repo_type="dataset",
private=True,
exist_ok=True,
token=HF_TOKEN
)
except Exception as repo_err:
return f"❌ Failed to access or create repository: {repo_err}. Check your HF_TOKEN permissions."
api = HfApi()
api.upload_file(
path_or_fileobj=file_path,
path_in_repo=THEME_FILE_NAME,
repo_id=DATASET_REPO,
repo_type="dataset",
token=HF_TOKEN,
commit_message="Updated website theme XML"
)
return "✅ Theme successfully pushed to your private dataset! The AI will now use this for styling."
except Exception as e:
return f"❌ Error saving theme to dataset: {e}"
def generate_blogger_html(app_query, custom_link, mirror_1, mirror_2, mod_features, theme_color, telegram_link, custom_size, custom_date, req_name, req_link, tutorial_link, root_req, arch_input, lexical_score, pros_input, cons_input, vt_link, related_name, related_link, coffee_link):
try:
search_results = search(app_query, lang='en', country='us')
if not search_results:
return "Error: Could not find this app on the Play Store.", "App not found", "0", "0"
app_id = search_results[0]['appId']
app_details = play_app(app_id, lang='en', country='us')
# Base Extractions
title = app_details.get('title', app_query)
icon_url = app_details.get('icon', '')
rating = round(app_details.get('score', 4.5), 1)
reviews_count = app_details.get('ratings', 1000)
category = app_details.get('genre', 'Utility')
developer = app_details.get('developer', 'Unknown Developer')
# --- INSTALL FORMATTER (10,000,000,000+ to 10B+) ---
raw_installs = app_details.get('installs', '10,000+')
clean_num = raw_installs.replace(',', '').replace('+', '')
if clean_num.isdigit():
num = int(clean_num)
if num >= 1_000_000_000:
installs = f"{num // 1_000_000_000}B+"
elif num >= 1_000_000:
installs = f"{num // 1_000_000}M+"
elif num >= 1_000:
installs = f"{num // 1_000}K+"
else:
installs = f"{num}+"
else:
installs = raw_installs
# ---------------------------------------------------
version = app_details.get('version', 'Varies with device')
recent_changes = app_details.get('recentChanges', '')
final_size = custom_size.strip() if custom_size else app_details.get('size', 'Varies')
updated_ts = app_details.get('updated', 0)
final_date = custom_date.strip() if custom_date else (datetime.fromtimestamp(updated_ts).strftime('%B %d, %Y') if updated_ts else "Recently")
full_description = app_details.get('descriptionHTML', app_details.get('summary', 'Premium app.'))
screenshots = app_details.get('screenshots', [])[:4]
video_url = app_details.get('video', None)
# 1. Mod Features
features_list = "".join([f'
{f.strip()}\n' for f in mod_features.split(',') if f.strip()])
# 2. Pros & Cons
pros_html = "".join([f' {p.strip()}' for p in pros_input.split(',') if p.strip()])
cons_html = "".join([f' {c.strip()}' for c in cons_input.split(',') if c.strip()])
# 3. Dynamic Links (Mirrors, VT, Coffee)
mirror1_html = f' Mirror 1' if mirror_1 else ""
mirror2_html = f' Mirror 2' if mirror_2 else ""
vt_html = f' 100% Safe - Verified by VirusTotal Scan
' if vt_link else ' Links encrypted. Checked for safety.
'
coffee_html = f'☕ Buy Me a Coffee' if coffee_link else ""
# 4. Optional Blocks (Changelog, Companion, Related)
changelog_block = f'What\'s New
{recent_changes}
' if recent_changes else ""
related_html = f'' if related_name and related_link else ""
req_app_html = f'Requirements
' if req_name and req_link else ""
tutorial_btn = f' View Tutorial' if tutorial_link else ""
# Media Blocks
screenshots_html = f'App Screenshots
' + "".join([f'

' for s in screenshots]) + '
' if screenshots else ""
video_html = f'Official Trailer
' if video_url else ""
root_color = "#10b981" if "No" in root_req else "#ef4444"
# Schemas
schema_app = {"@context": "https://schema.org", "@type": "SoftwareApplication", "name": title, "operatingSystem": "ANDROID", "applicationCategory": category, "image": icon_url, "author": { "@type": "Organization", "name": developer }, "aggregateRating": {"@type": "AggregateRating", "ratingValue": str(rating), "ratingCount": str(reviews_count)}, "offers": { "@type": "Offer", "price": "0.00", "priceCurrency": "USD" }}
schema_faq = {"@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [{"@type": "Question", "name": f"Is {title} Mod safe?", "acceptedAnswer": {"@type": "Answer", "text": "Yes, verified by Lexical Space."}}, {"@type": "Question", "name": f"Does {title} require root access?", "acceptedAnswer": {"@type": "Answer", "text": "No, it works on any non-rooted Android device."}}]}
schema_sysreq = {"@context": "https://schema.org", "@type": "SoftwareApplication", "name": title, "operatingSystem": "ANDROID", "applicationCategory": category, "author": { "@type": "Organization", "name": developer }, "requirements": { "@type": "SoftwareApplicationRequirements", "name": "Minimum System Requirements", "operatingSystem": "Android 9.0 (Pie)+", "ram": "4 GB+", "storage": "100 MB+" }}
schema_script = f''
# THE FINAL HTML
html_template = f"""
{schema_script}

{title} MOD
{category} • Max Store Verified
{rating} (Play Store)
{lexical_score}/10 (Lexical Score)
{installs}
Android 9.0+
{req_app_html}
{changelog_block}
App Information
Developer{developer}
Version{version}
Updated{final_date}
File Size{final_size}
Architecture{arch_input}
Root Access{root_req}
Mod Features
Pros & Cons
{video_html}
{screenshots_html}
Installation Guide
- Download the {title} Mod APK file from the secure link above.
- Go to your device Settings > Security and enable "Unknown Sources".
- Open your File Manager, locate the downloaded APK, and install it.
- Launch the app and enjoy all premium features!
Frequently Asked Questions
Is {title} Mod safe to use?
Yes! All files on Lexical Space are strictly tested and verified. Always download directly from our site to ensure device security.
Do I need to root my device?
Please refer to the "Root Access" status in the App Information box above. Most of our mods do not require root.
{related_html}
About Original {title}
{full_description}
DMCA: Lexical Space complies with 17 U.S.C. § 512 and the Digital Millennium Copyright Act.
"""
word_count = str(len(html_template.split()))
keyword_density = str(html_template.lower().count(title.lower()[:10]))
with open("latest_draft.txt", "w", encoding="utf-8") as f:
f.write(html_template)
return html_template, html_template, word_count, keyword_density
except Exception as e:
return f"Error generating HTML: {str(e)}", f"Error occurred: {str(e)}", "0", "0"
# -----------------------------
# OPENROUTER AI ENHANCER (XML FETCH + CLAUDE/GPT/GEMINI)
# -----------------------------
def enhance_with_openrouter(raw_html, style_name, selected_model, state):
"""Downloads XML from Dataset, reads it, and uses OpenRouter API to exact-match the styles."""
if not state.get("logged_in") or (time.time() - state.get("login_time", 0) > 1800):
return "Session expired.", "Session Expired.", "0", "0", gr.update(visible=False)
if not OPENROUTER_API_KEY:
return raw_html, "Error: OPENROUTER_API_KEY not found in HF Space secrets.", "0", "0", gr.update(visible=False)
if not raw_html or raw_html.startswith("Error"):
return raw_html, "Please generate Base HTML first before enhancing.", "0", "0", gr.update(visible=False)
# 1. Fetch the exact XML file from Hugging Face Dataset
xml_content = ""
try:
downloaded_theme_path = hf_hub_download(
repo_id=DATASET_REPO,
filename=THEME_FILE_NAME,
repo_type="dataset",
token=HF_TOKEN
)
with open(downloaded_theme_path, "r", encoding="utf-8") as f:
xml_content = f.read()
except Exception as e:
print(f"Failed to fetch XML: {e}")
xml_content = "WARNING: Could not fetch website_theme.xml from dataset. Please apply generic high-quality CSS styling based on the requested style name."
# 2. Configure OpenRouter Request
prompt = f"""
I am providing you with the raw source code of my website's theme XML. It contains the exact CSS definitions, classes, ID's, CSS variables (like colors, fonts), and HTML structures used for the site.
{xml_content}
TASK:
I want you to re-format and re-style the following Base HTML App Post to match the style known as: '{style_name}'.
Look through the provided above. Find the CSS classes, inline styles, or component structures that correspond to '{style_name}'. Apply those exact classes, color hexes, and layout structures to the Base HTML. DO NOT invent styles—extract them from the XML.
STRICT RULES:
1. CRITICAL: DO NOT remove or alter the `