Spaces:
Sleeping

File size: 17,529 Bytes
8106906
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
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)