Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import requests
|
| 3 |
+
from bs4 import BeautifulSoup
|
| 4 |
+
import json
|
| 5 |
+
import time
|
| 6 |
+
import logging
|
| 7 |
+
import re
|
| 8 |
+
from urllib.parse import urlparse
|
| 9 |
+
from groq import Groq
|
| 10 |
+
from requests.exceptions import HTTPError, ReadTimeout
|
| 11 |
+
from http.client import RemoteDisconnected
|
| 12 |
+
import os
|
| 13 |
+
from datetime import datetime
|
| 14 |
+
|
| 15 |
+
# === KONFIGURASI ===
|
| 16 |
+
GAS_URL = os.getenv("GAS_URL", "https://script.google.com/macros/s/AKfycbwstcoUh2CQmuoTgxapW9cUhzQFx6glp25DaCqrvBdwKrb77wqeMN0RzB8UMpiAQ2PtQA/exec")
|
| 17 |
+
GROQ_API_KEY ="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"
|
| 18 |
+
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "7166094967:AAHb5S2hN6L527y1-GoXPzBdU4RB8jnYelk")
|
| 19 |
+
TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID", "6929677613")
|
| 20 |
+
GROQ_MODEL = "gemma2-9b-it"
|
| 21 |
+
REQUEST_TIMEOUT = 10
|
| 22 |
+
GROQ_TIMEOUT = 30
|
| 23 |
+
RETRY_BACKOFF_FACTOR = 2
|
| 24 |
+
MAX_RETRIES = 3
|
| 25 |
+
DELAY_BETWEEN_REQUESTS = 3
|
| 26 |
+
|
| 27 |
+
log_file = f"scrape_rewrite_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
|
| 28 |
+
logging.basicConfig(
|
| 29 |
+
level=logging.INFO,
|
| 30 |
+
format="%(asctime)s - %(levelname)s - %(message)s",
|
| 31 |
+
handlers=[logging.FileHandler(log_file, encoding="utf-8"), logging.StreamHandler()]
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
client = Groq(api_key=GROQ_API_KEY)
|
| 35 |
+
|
| 36 |
+
# --- FUNGSI PENDUKUNG ---
|
| 37 |
+
class RateLimitExceeded(Exception):
|
| 38 |
+
pass
|
| 39 |
+
|
| 40 |
+
def send_telegram_message(message):
|
| 41 |
+
try:
|
| 42 |
+
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
|
| 43 |
+
payload = {"chat_id": TELEGRAM_CHAT_ID, "text": message, "parse_mode": "Markdown"}
|
| 44 |
+
requests.post(url, json=payload, timeout=5)
|
| 45 |
+
except: pass
|
| 46 |
+
|
| 47 |
+
def is_valid_url(url):
|
| 48 |
+
try:
|
| 49 |
+
result = urlparse(url)
|
| 50 |
+
return all([result.scheme in ['http', 'https'], result.netloc])
|
| 51 |
+
except: return False
|
| 52 |
+
|
| 53 |
+
def is_valid_html(html):
|
| 54 |
+
return html and html.strip().startswith('<article') and html.strip().endswith('</article>')
|
| 55 |
+
|
| 56 |
+
def retry_request(func, *args, **kwargs):
|
| 57 |
+
for attempt in range(MAX_RETRIES):
|
| 58 |
+
try:
|
| 59 |
+
return func(*args, **kwargs)
|
| 60 |
+
except (HTTPError, RemoteDisconnected, ReadTimeout):
|
| 61 |
+
time.sleep(RETRY_BACKOFF_FACTOR ** attempt)
|
| 62 |
+
raise Exception("Max retries exceeded")
|
| 63 |
+
|
| 64 |
+
def fetch_links(sheet_name="Sheet2"):
|
| 65 |
+
try:
|
| 66 |
+
def get_links():
|
| 67 |
+
resp = requests.get(GAS_URL, params={"sheetName": sheet_name}, timeout=REQUEST_TIMEOUT)
|
| 68 |
+
return resp.json()
|
| 69 |
+
data = retry_request(get_links)
|
| 70 |
+
return [item for item in data if not item.get("judul") and is_valid_url(item.get("link"))]
|
| 71 |
+
except: return []
|
| 72 |
+
|
| 73 |
+
def clean_html(soup):
|
| 74 |
+
for tag in soup(["script", "iframe"]): tag.decompose()
|
| 75 |
+
return soup
|
| 76 |
+
|
| 77 |
+
def extract_main_image(soup):
|
| 78 |
+
try:
|
| 79 |
+
img = soup.select_one('article img')
|
| 80 |
+
return img['src'] if img and is_valid_url(img['src']) else ""
|
| 81 |
+
except: return ""
|
| 82 |
+
|
| 83 |
+
def scrape_detik(link):
|
| 84 |
+
try:
|
| 85 |
+
resp = retry_request(lambda: requests.get(link, timeout=REQUEST_TIMEOUT))
|
| 86 |
+
soup = BeautifulSoup(resp.text, 'html.parser')
|
| 87 |
+
content = soup.select_one('article')
|
| 88 |
+
image_url = extract_main_image(soup)
|
| 89 |
+
cleaned = clean_html(content)
|
| 90 |
+
return cleaned.get_text("\n", strip=True), image_url
|
| 91 |
+
except: return None, None
|
| 92 |
+
|
| 93 |
+
def rewrite_with_ai(text, image_url):
|
| 94 |
+
prompt = f"""Tulis ulang artikel berikut menjadi HTML <article>...\n\n{text}"""
|
| 95 |
+
try:
|
| 96 |
+
completion = client.chat.completions.create(
|
| 97 |
+
model=GROQ_MODEL,
|
| 98 |
+
messages=[{"role": "user", "content": prompt}],
|
| 99 |
+
stream=True
|
| 100 |
+
)
|
| 101 |
+
html = "".join(chunk.choices[0].delta.content or "" for chunk in completion)
|
| 102 |
+
return html if is_valid_html(html) else None
|
| 103 |
+
except: return None
|
| 104 |
+
|
| 105 |
+
def extract_title_from_html(html):
|
| 106 |
+
try:
|
| 107 |
+
soup = BeautifulSoup(html, 'html.parser')
|
| 108 |
+
return soup.find('h2').get_text(strip=True)
|
| 109 |
+
except: return "Tanpa Judul"
|
| 110 |
+
|
| 111 |
+
def kirim_ke_sheet(judul, konten_html, link):
|
| 112 |
+
try:
|
| 113 |
+
payload = {"method": "updateRowByLink", "link": link, "judul": judul, "konten": konten_html}
|
| 114 |
+
retry_request(lambda: requests.post(GAS_URL, json=payload, timeout=REQUEST_TIMEOUT))
|
| 115 |
+
except: pass
|
| 116 |
+
|
| 117 |
+
# --- FUNGSI UTAMA YANG DIPANGGIL ---
|
| 118 |
+
def jalankan_script():
|
| 119 |
+
processed = 0
|
| 120 |
+
rows = fetch_links()
|
| 121 |
+
for row in rows[:3]: # BATAS 3 LINK
|
| 122 |
+
link = row['link']
|
| 123 |
+
artikel, img = scrape_detik(link)
|
| 124 |
+
if not artikel: continue
|
| 125 |
+
hasil = rewrite_with_ai(artikel, img)
|
| 126 |
+
if not hasil: continue
|
| 127 |
+
judul = extract_title_from_html(hasil)
|
| 128 |
+
kirim_ke_sheet(judul, hasil, link)
|
| 129 |
+
processed += 1
|
| 130 |
+
time.sleep(DELAY_BETWEEN_REQUESTS)
|
| 131 |
+
send_telegram_message(f"Selesai! {processed} artikel diproses.")
|
| 132 |
+
return f"Sukses: {processed} artikel diproses"
|
| 133 |
+
|
| 134 |
+
# --- GRADIO UNTUK HUGGING FACE ---
|
| 135 |
+
iface = gr.Interface(fn=jalankan_script, inputs=[], outputs="text")
|
| 136 |
+
app = gr.mount_gradio_app(app=None, blocks=iface, path="/run")
|