crawling-datas / app_hf.py
dimdimm's picture
fix: tambah dummy @spaces.GPU biar HF Zero hardware tidak error No GPU function
e929b74
Raw History Blame Contribute Delete
8.44 kB
"""
app_hf.py β€” Gradio UI untuk Hugging Face Spaces (SDK: Gradio, gratis tanpa Docker)
Wrap logic yang sama dari run.py + app.py, limit 2 keyword (hemat RAM HF free).
Deploy HF:
1. New Space β†’ SDK: Gradio β†’ Hardware: CPU basic (free)
2. Upload: app_hf.py, requirements.txt, packages.txt
3. Settings β†’ Variables: SUPABASE_URL, SUPABASE_ANON_KEY
4. Space auto-build β†’ klik "Mulai Crawling"
Lokal test: python app_hf.py β†’ http://127.0.0.1:7860
"""
import logging
import time
from datetime import datetime
# HF Spaces: gradio 4.44.0 masih import HfFolder yang sudah dihapus di huggingface_hub terbaru.
# Shim biar kompatibel dengan hub >=0.30 yang dipakai oleh spaces==0.51.1
try:
import huggingface_hub
if not hasattr(huggingface_hub, "HfFolder"):
# hub terbaru pakai HfApi, buat alias dummy agar gradio 4.x tidak ImportError
class _HfFolder:
@staticmethod
def get_token():
return None
huggingface_hub.HfFolder = _HfFolder
except Exception:
pass
import gradio as gr
# HF Zero hardware butuh minimal 1 fungsi @spaces.GPU biar tidak "No @spaces.GPU function detected"
try:
import spaces
@spaces.GPU
def _zero_keepalive(): # dummy, tidak dipanggil β€” cuma satisfy Zero check
return "ok"
except Exception:
pass
# HF: gradio-client 1.3.0 butuh websockets<13.0, sedangkan supabase butuh websockets.asyncio (baru di 13.1)
# Shim dummy agar supabase tetap import dengan websockets 12.0
try:
import sys, types
import websockets
if not hasattr(websockets, "asyncio"):
asyncio_mod = types.ModuleType("websockets.asyncio")
client_mod = types.ModuleType("websockets.asyncio.client")
class _DummyConn: pass
client_mod.ClientConnection = _DummyConn
asyncio_mod.client = client_mod
sys.modules["websockets.asyncio"] = asyncio_mod
sys.modules["websockets.asyncio.client"] = client_mod
except Exception:
pass
import run as scraper_run
from supabase_client import supabase
# ── Setup logging ke buffer string ────────────────────────────
log_buffer: list[str] = []
class BufferHandler(logging.Handler):
def emit(self, record):
msg = self.format(record)
log_buffer.append(msg)
handler = BufferHandler()
handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s", datefmt="%H:%M:%S"))
for name in ("scraper", "linkedin", "jobstreet", "app", ""):
lg = logging.getLogger(name)
lg.addHandler(handler)
lg.setLevel(logging.INFO)
log = logging.getLogger("app_hf")
KEYWORDS = scraper_run.KEYWORDS # 13 keyword (8 IT + 5 non-IT) dari run.py:21
def get_stats():
try:
total = supabase.table("jobs").select("id", count="exact").limit(1).execute()
li = supabase.table("jobs").select("id", count="exact").eq("source", "LinkedIn").limit(1).execute()
js = supabase.table("jobs").select("id", count="exact").eq("source", "JobStreet").limit(1).execute()
return total.count or 0, li.count or 0, js.count or 0
except Exception as e:
log.error("Stats gagal: %s", e)
return 0, 0, 0
def get_recent_jobs(limit=20):
try:
res = supabase.table("jobs").select("*").order("created_at", desc=True).limit(limit).execute()
rows = []
for j in res.data:
rows.append([
j.get("title",""),
j.get("company",""),
j.get("location",""),
j.get("source",""),
", ".join(j.get("skills",[])[:5]),
j.get("url",""),
])
return rows
except Exception as e:
log.error("Load jobs gagal: %s", e)
return []
def run_scraping(selected: list[str]):
# validasi
if not selected:
return "❌ Pilih minimal 1 keyword.", [], "β€”", "β€”", "β€”"
if len(selected) > 2:
return f"❌ Maksimal 2 keyword (kamu pilih {len(selected)}). Hapus satu dulu.", [], "β€”", "β€”", "β€”"
log_buffer.clear()
start = time.time()
started_at = datetime.now().isoformat(timespec="seconds")
total_found = 0
total_inserted = 0
log.info("=== Scraping dimulai: %d keyword ===", len(selected))
yield "\n".join(log_buffer), [], "Berjalan...", "β€”", "β€”"
for kw in selected:
log.info("β†’ Keyword: %s", kw)
yield "\n".join(log_buffer), [], f"Proses: {kw}", "β€”", "β€”"
# LinkedIn
try:
jobs_li = scraper_run.scrape_linkedin(kw)
ins = scraper_run.push(jobs_li, "LinkedIn")
total_inserted += ins
total_found += len(jobs_li)
log.info("[LinkedIn] %s: %d ditemukan, %d dimasukkan", kw, len(jobs_li), ins)
except Exception as e:
log.error("[LinkedIn] gagal %s: %s", kw, e)
yield "\n".join(log_buffer), [], f"Selesai LinkedIn: {kw}", "β€”", "β€”"
# JobStreet
try:
jobs_js = scraper_run.scrape_jobstreet(kw)
ins = scraper_run.push(jobs_js, "JobStreet")
total_inserted += ins
total_found += len(jobs_js)
log.info("[JobStreet] %s: %d ditemukan, %d dimasukkan", kw, len(jobs_js), ins)
except Exception as e:
log.error("[JobStreet] gagal %s: %s", kw, e)
yield "\n".join(log_buffer), [], f"Selesai JobStreet: {kw}", "β€”", "β€”"
duration = round(time.time() - start, 1)
log.info("=== Selesai: %d ditemukan, %d dimasukkan dalam %ss ===", total_found, total_inserted, duration)
total, li_cnt, js_cnt = get_stats()
rows = get_recent_jobs(20)
final_log = "\n".join(log_buffer)
status = f"βœ… Selesai {started_at} β†’ {duration}s | {total_found} ditemukan, {total_inserted} dimasukkan"
yield final_log, rows, status, str(total), f"{li_cnt} / {js_cnt}"
# ── Gradio UI ─────────────────────────────────────────────────
with gr.Blocks(title="Job Scraper β€” 1-Klik Crawling") as demo:
gr.Markdown("""
# πŸ•·οΈ Job Scraper β€” 1-Klik Crawling
**LinkedIn & JobStreet β†’ Supabase** | Limit **2 keyword/klik** (hemat RAM HF Free) | Pilih subset untuk demo skripsi
""")
with gr.Row():
total_box = gr.Textbox(label="Total di DB", value="β€”", interactive=False, scale=1)
li_js_box = gr.Textbox(label="LinkedIn / JobStreet", value="β€”", interactive=False, scale=1)
status_box = gr.Textbox(label="Status", value="Siap", interactive=False, scale=2)
with gr.Row():
with gr.Column(scale=1):
kw_check = gr.CheckboxGroup(
choices=KEYWORDS,
value=KEYWORDS[:2],
label="Keywords (maks 2)",
)
run_btn = gr.Button("▢️ Mulai Crawling", variant="primary", size="lg")
refresh_btn = gr.Button("πŸ”„ Refresh Data", size="sm")
gr.Markdown(f"<span style='color:#64748b;font-size:12px'>Total {len(KEYWORDS)} keyword tersedia (8 IT + 5 non-IT). Backend limit 2 β€” `app.py:207`</span>")
with gr.Column(scale=2):
log_box = gr.Textbox(label="Live Log", lines=18, max_lines=24, interactive=False)
jobs_table = gr.Dataframe(
headers=["Title","Company","Location","Source","Skills","URL"],
label="Hasil Terbaru (20 teratas)",
interactive=False,
)
# events
def refresh_data():
total, li_cnt, js_cnt = get_stats()
rows = get_recent_jobs(20)
return rows, str(total), f"{li_cnt} / {js_cnt}", "Data di-refresh"
refresh_btn.click(fn=refresh_data, outputs=[jobs_table, total_box, li_js_box, status_box])
# scraping dengan streaming log (generator)
run_btn.click(fn=run_scraping, inputs=[kw_check], outputs=[log_box, jobs_table, status_box, total_box, li_js_box])
# load awal
demo.load(fn=refresh_data, outputs=[jobs_table, total_box, li_js_box, status_box])
if __name__ == "__main__":
# HF Spaces: jangan set server_name/port manual β€” biar HF proxy yang handle
# (set share=False biar tidak buat link gradio.live)
try:
import subprocess
subprocess.run(["playwright", "install", "chromium"], check=False, capture_output=True)
except Exception:
pass
demo.launch()