Spaces:
Configuration error
Configuration error
| import gradio as gr | |
| from pytrends.request import TrendReq | |
| import sqlite3, json, time, os, pandas as pd | |
| from io import BytesIO | |
| DB_PATH = "data/cache.db" | |
| os.makedirs("data", exist_ok=True) | |
| def init_db(): | |
| conn = sqlite3.connect(DB_PATH) | |
| conn.execute("CREATE TABLE IF NOT EXISTS cache (id INTEGER PRIMARY KEY, key TEXT UNIQUE, response TEXT, ts INTEGER)") | |
| conn.commit() | |
| conn.close() | |
| init_db() | |
| def fetch_trends(query): | |
| pytrends = TrendReq() | |
| pytrends.build_payload([query]) | |
| try: | |
| related = pytrends.related_queries() | |
| iot = pytrends.interest_over_time() | |
| return {"related": related, "iot": iot.to_dict() if iot is not None else {}} | |
| except Exception as e: | |
| return {"error": str(e)} | |
| def explore_keyword(keyword): | |
| if not keyword.strip(): | |
| return {"error": "Empty query"} | |
| data = fetch_trends(keyword) | |
| return data | |
| def download_csv(keyword): | |
| data = fetch_trends(keyword) | |
| buf = BytesIO() | |
| pd.DataFrame([data]).to_csv(buf, index=False) | |
| buf.seek(0) | |
| return ("trends.csv", buf.read()) | |
| with gr.Blocks() as demo: | |
| keyword = gr.Textbox(label="Keyword / الكلمة المفتاحية") | |
| btn_search = gr.Button("Search / بحث") | |
| output = gr.JSON() | |
| btn_search.click(explore_keyword, inputs=[keyword], outputs=[output]) | |
| btn_csv = gr.Button("Export CSV / تصدير CSV") | |
| btn_csv.click(download_csv, inputs=[keyword], outputs=[gr.File(label='CSV file')]) | |
| demo.launch(server_name="0.0.0.0", server_port=7860) | |