Spaces:
Sleeping

README / app.py
hiroyanakamura2's picture
Upload 4 files
8106906 verified
Raw History Blame Contribute Delete
17.5 kB
import os, json, time, re, io, tempfile, uuid, threading
from flask import Flask, request, jsonify, send_from_directory, send_file
import openpyxl
import requests as req
app = Flask(__name__)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
jobs = {}
# ===================================================================
# HTML Assembly - builds WP Gutenberg blocks from headings + body
# ===================================================================
def build_html(sections, cta=True):
html_parts = []
for heading, body in sections:
if not heading or not body:
continue
h = heading.strip()
b = body.strip()
html_parts.append(f'<!-- wp:heading -->\n<h2 class="wp-block-heading">{h}</h2>\n<!-- /wp:heading -->')
for para in b.split("\n"):
p = para.strip()
if p:
html_parts.append(f'<!-- wp:paragraph -->\n<p>{p}</p>\n<!-- /wp:paragraph -->')
if cta:
html_parts.append('<!-- wp:paragraph -->\n<p>地域の課題解決に挑戦してみませんか?<a href="https://flaspo.jp/">FLASPO</a>では、全国の地方創生コンテストに参加できます。あなたのアイデアが地域を変えるきっかけになるかもしれません。</p>\n<!-- /wp:paragraph -->')
return "\n\n".join(html_parts)
# ===================================================================
# WordPress helpers
# ===================================================================
def wp_call(method, url, user, pw, ep, data=None, files=None):
full = f"{url}/wp-json/wp/v2/{ep}"
auth = (user, pw)
try:
if files:
r = req.post(full, auth=auth, files=files, data=data, timeout=60)
elif method == "GET":
r = req.get(full, auth=auth, timeout=30)
else:
r = req.post(full, auth=auth, json=data, timeout=30)
return r.json() if r.status_code in [200, 201] else None
except:
return None
def get_or_create(url, user, pw, t, name):
items = wp_call("GET", url, user, pw, f"{t}?search={req.utils.quote(name)}&per_page=100") or []
for i in items:
if i.get("name") == name:
return i["id"]
r = wp_call("POST", url, user, pw, t, {"name": name, "slug": name.replace("・", "-").replace(" ", "-")})
return r["id"] if r else None
def make_eyecatch(pk, pt, title):
if not pk or not pt:
return None
try:
r = req.post("https://api.placid.app/api/rest/images",
headers={"Authorization": f"Bearer {pk}", "Content-Type": "application/json"},
json={"template_uuid": pt, "layers": {"title": {"text": title},
"feature-1": {"text": "FLASPO MAGAZINE"}, "feature-2": {"text": ""}, "feature-3": {"text": ""}}},
timeout=60)
if r.status_code in [200, 201]:
d = r.json()
u = d.get("image_url") or d.get("url")
if not u and d.get("status") in ("queued", "processing"):
for _ in range(15):
time.sleep(3)
pr = req.get(f"https://api.placid.app/api/rest/images/{d.get('id', '')}",
headers={"Authorization": f"Bearer {pk}"}, timeout=30)
if pr.status_code == 200 and pr.json().get("status") == "finished":
u = pr.json().get("image_url") or pr.json().get("url")
break
if u:
return req.get(u, timeout=30).content
except:
pass
return None
def post_one(wp_url, wp_user, wp_pass, pk, pt, title, content, category, tags_str, meta, slug, kw):
mid = None
img = make_eyecatch(pk, pt, title)
if img:
r = wp_call("POST", wp_url, wp_user, wp_pass, "media",
data={"title": slug or title[:30], "alt_text": title},
files={"file": (f"eyecatch-{slug or 'img'}.jpg", img, "image/jpeg")})
if r:
mid = r["id"]
cat_id = get_or_create(wp_url, wp_user, wp_pass, "categories", category) if category else None
tag_ids = []
if tags_str:
for t in [x.strip() for x in tags_str.split(",") if x.strip()][:10]:
tid = get_or_create(wp_url, wp_user, wp_pass, "tags", t)
if tid:
tag_ids.append(tid)
pd = {"title": title, "slug": slug or "", "content": content, "excerpt": meta or "",
"status": "draft", "categories": [cat_id] if cat_id else [], "tags": tag_ids}
if mid:
pd["featured_media"] = mid
r = wp_call("POST", wp_url, wp_user, wp_pass, "posts", pd)
if r:
try:
wp_call("POST", wp_url, wp_user, wp_pass, f"posts/{r['id']}", {
"meta": {"_yoast_wpseo_metadesc": meta or "", "_yoast_wpseo_focuskw": kw or ""}})
except:
pass
return {"status": "ok", "id": r["id"],
"url": f"{wp_url}/wp-admin/post.php?post={r['id']}&action=edit", "title": title}
return {"status": "fail", "title": title, "error": "WordPress投稿失敗"}
# ===================================================================
# Excel reading
# ===================================================================
def read_batch(data):
wb = openpyxl.load_workbook(io.BytesIO(data))
ws = wb.active
articles = []
for row in range(2, ws.max_row + 1):
title = ws.cell(row=row, column=1).value
if not title or not str(title).strip():
continue
sections = []
for i in range(5):
h = ws.cell(row=row, column=7 + i * 2).value
b = ws.cell(row=row, column=8 + i * 2).value
if h and str(h).strip():
sections.append((str(h).strip(), str(b).strip() if b else ""))
content = build_html(sections)
articles.append({
"title": str(title).strip(),
"content": content,
"category": str(ws.cell(row=row, column=2).value or "").strip(),
"tags": str(ws.cell(row=row, column=3).value or "").strip(),
"meta": str(ws.cell(row=row, column=4).value or "").strip(),
"slug": str(ws.cell(row=row, column=5).value or "").strip(),
"keyword": str(ws.cell(row=row, column=6).value or "").strip(),
"section_count": len(sections),
})
return articles
# ===================================================================
# Async job
# ===================================================================
def start_job(fn, *args):
job_id = str(uuid.uuid4())[:8]
jobs[job_id] = {"status": "running", "result": None, "progress": 0, "total": 0, "current": ""}
def wrapper():
try:
result = fn(job_id, *args)
jobs[job_id]["status"] = "done"
jobs[job_id]["result"] = result
except Exception as e:
jobs[job_id]["status"] = "error"
jobs[job_id]["result"] = str(e)
threading.Thread(target=wrapper, daemon=True).start()
return job_id
# ===================================================================
# Routes
# ===================================================================
@app.route("/")
def index():
return send_from_directory(BASE_DIR, "index.html")
@app.route("/api/testwp", methods=["POST"])
def test_wp():
d = request.json
u = wp_call("GET", d["wp_url"], d["wp_user"], d["wp_pass"], "users/me")
if u and u.get("id"):
return jsonify({"ok": True, "name": u.get("name", "")})
return jsonify({"ok": False})
@app.route("/api/post-single", methods=["POST"])
def post_single():
d = request.json
job_id = start_job(do_post_single, d)
return jsonify({"job_id": job_id})
def do_post_single(job_id, d):
jobs[job_id]["total"] = 1
jobs[job_id]["current"] = d.get("title", "")
sections = []
for i in range(1, 6):
h = d.get(f"h{i}", "")
b = d.get(f"b{i}", "")
if h:
sections.append((h, b))
content = build_html(sections)
result = post_one(d["wp_url"], d["wp_user"], d["wp_pass"], d.get("pk", ""), d.get("pt", ""),
d["title"], content, d.get("category", ""), d.get("tags", ""),
d.get("meta", ""), d.get("slug", ""), d.get("keyword", ""))
jobs[job_id]["progress"] = 1
return result
@app.route("/api/upload-batch", methods=["POST"])
def upload_batch():
f = request.files.get("file")
if not f:
return jsonify({"ok": False})
path = os.path.join(tempfile.gettempdir(), "batch.xlsx")
f.save(path)
articles = read_batch(open(path, "rb").read())
return jsonify({"ok": True, "path": path, "count": len(articles),
"articles": [{"title": a["title"], "category": a["category"],
"sections": a["section_count"]} for a in articles]})
@app.route("/api/post-batch", methods=["POST"])
def post_batch():
d = request.json
job_id = start_job(do_post_batch, d)
return jsonify({"job_id": job_id})
def do_post_batch(job_id, d):
path = d.get("excel_path", "")
if not path or not os.path.exists(path):
return {"ok": False, "error": "ファイルなし"}
articles = read_batch(open(path, "rb").read())
if not articles:
return {"ok": False, "error": "記事なし。Excelのフォーマットを確認してください。"}
jobs[job_id]["total"] = len(articles)
results = []
for i, art in enumerate(articles):
jobs[job_id]["progress"] = i
jobs[job_id]["current"] = art["title"][:30]
r = post_one(d["wp_url"], d["wp_user"], d["wp_pass"], d.get("pk", ""), d.get("pt", ""),
art["title"], art["content"], art["category"], art["tags"],
art["meta"], art["slug"], art["keyword"])
results.append(r)
time.sleep(2)
jobs[job_id]["progress"] = len(articles)
return {"ok": True, "results": results}
@app.route("/api/status/<job_id>")
def job_status(job_id):
job = jobs.get(job_id)
if not job:
return jsonify({"status": "not_found"})
return jsonify(job)
@app.route("/api/template")
def download_template():
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "記事一覧"
headers = ["タイトル", "カテゴリ", "タグ", "メタディスクリプション", "スラッグ", "キーワード",
"見出し1", "本文1", "見出し2", "本文2", "見出し3", "本文3", "見出し4", "本文4", "見出し5", "本文5"]
for i, h in enumerate(headers, 1):
c = ws.cell(row=1, column=i, value=h)
c.font = openpyxl.styles.Font(bold=True, size=10)
# Example row
ex = ["ふるさと納税の仕組みとは?図解でわかる税控除・やり方・メリット",
"地方創生・社会課題",
"ふるさと納税, 地方創生, 税金控除",
"ふるさと納税の仕組みを図解で解説。税控除の流れ、やり方、メリットまで初心者にもわかりやすく紹介します。",
"furusato-nouzei-shikumi",
"ふるさと納税 仕組み",
"ふるさと納税とは?制度の概要をわかりやすく解説",
"ふるさと納税とは、自分が応援したい自治体に寄付をすることで、所得税や住民税の控除を受けられる制度です。2008年に創設されたこの制度は、地方と都市の税収格差を是正する目的で始まりました。寄付額のうち2,000円を超える部分が税金から控除されるため、実質2,000円の自己負担で各地の返礼品を受け取ることができます。総務省の発表によると、2024年度の寄付総額は約1兆円を超え、年々利用者が増加しています。特に20代〜30代の若者の利用が急増しており、「お得に社会貢献ができる」として注目を集めています。手続きもワンストップ特例制度を使えば確定申告なしで完了するため、初心者でも簡単に始められます。",
"ふるさと納税の仕組み|税金控除の流れを図解で解説",
"ふるさと納税の税金控除は、大きく分けて「所得税からの還付」と「住民税からの控除」の2つで構成されています。まず、寄付をした年の所得税から一定額が還付されます。次に、翌年の住民税から残りの控除額が差し引かれます。控除の上限額は、年収や家族構成によって異なります。例えば、年収400万円の独身者の場合、控除上限額の目安は約42,000円です。つまり、42,000円を寄付しても実質的な自己負担は2,000円ということになります。注意点として、控除を受けるためには確定申告またはワンストップ特例制度の申請が必要です。ワンストップ特例は、寄付先が5自治体以内であれば利用可能で、寄付のたびに申請書を提出するだけで手続きが完了します。",
"ふるさと納税の3つのメリット",
"ふるさと納税の最大のメリットは、実質2,000円で全国各地の特産品や体験を楽しめることです。北海道のカニ、宮崎県の牛肉、山梨県のワインなど、普段は手が届かない高級食材も返礼品として受け取れます。2つ目のメリットは、寄付金の使い道を自分で選べること。「子育て支援」「環境保全」「地域の教育」など、自治体が設定したプロジェクトから応援したいものを指定できます。自分のお金がどう使われるかが明確なので、社会貢献の実感が得られます。3つ目は、地方経済の活性化に直接貢献できることです。都市部に集中しがちな税収を地方に還流させることで、過疎化が進む地域の産業支援や雇用創出につながります。特に若者がふるさと納税をきっかけに地方に興味を持ち、関係人口の増加にもつながっています。",
"ふるさと納税のやり方|5ステップで簡単に始める方法",
"ふるさと納税は5つのステップで簡単に始められます。ステップ1は控除上限額の確認です。年収と家族構成から上限額を計算しましょう。各ふるさと納税サイトにシミュレーターが用意されています。ステップ2は寄付先と返礼品を選ぶこと。ふるさとチョイス、さとふる、楽天ふるさと納税などのポータルサイトから、気になる自治体や返礼品を探します。ステップ3は実際に寄付(申し込み)をします。クレジットカード決済が一般的で、ネットショッピングと同じ感覚で手続きできます。ステップ4は返礼品と寄付金受領証明書を受け取ります。返礼品は通常1〜2ヶ月で届きます。ステップ5は税金の控除手続きです。ワンストップ特例制度を利用する場合は、翌年1月10日までに申請書を寄付先の自治体に送付すれば完了です。",
"よくある質問(FAQ)",
"Q: ふるさと納税はいつまでにすればいいですか? A: その年の1月1日〜12月31日までの寄付が対象です。12月末までに決済が完了していれば、その年の控除対象になります。年末は駆け込み需要で人気の返礼品が品切れになることもあるので、早めの申し込みがおすすめです。Q: 学生でもふるさと納税できますか? A: アルバイト収入があり、所得税・住民税を納めている場合は可能です。ただし、収入が少ない場合は控除上限額も低くなるため、メリットが限られる場合があります。Q: 返礼品を受け取らずに寄付だけすることはできますか? A: はい、可能です。返礼品なしの寄付を受け付けている自治体も多く、その場合は寄付金がより多く地域のために使われます。"]
for i, v in enumerate(ex, 1):
ws.cell(row=2, column=i, value=v)
# Column widths
ws.column_dimensions['A'].width = 40
ws.column_dimensions['B'].width = 18
ws.column_dimensions['C'].width = 25
ws.column_dimensions['D'].width = 40
ws.column_dimensions['E'].width = 20
ws.column_dimensions['F'].width = 18
for c in range(7, 17):
ws.column_dimensions[chr(64 + c) if c < 27 else 'A' + chr(64 + c - 26)].width = 40 if c % 2 == 1 else 60
# Color headers
from openpyxl.styles import PatternFill
blue = PatternFill("solid", fgColor="DBEAFE")
green = PatternFill("solid", fgColor="D1FAE5")
for c in range(1, 7):
ws.cell(row=1, column=c).fill = blue
for c in range(7, 17):
ws.cell(row=1, column=c).fill = green
buf = io.BytesIO()
wb.save(buf)
buf.seek(0)
return send_file(buf, mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
as_attachment=True, download_name="FLASPO_投稿テンプレート.xlsx")
@app.route("/api/preview", methods=["POST"])
def preview():
d = request.json
sections = []
for i in range(1, 6):
h = d.get(f"h{i}", "")
b = d.get(f"b{i}", "")
if h:
sections.append((h, b))
html = build_html(sections)
return jsonify({"ok": True, "html": html, "chars": len(html)})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860, threaded=True)