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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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409

import os, io, csv, json, math
from pathlib import Path
from typing import List, Tuple, Dict, Optional

import gradio as gr
from PIL import Image, ImageDraw, ImageFont

ROOT = Path(__file__).parent
TEMPLATE = json.loads((ROOT / "template.json").read_text(encoding="utf-8"))

def parse_csv_text(text: str) -> List[List[str]]:
    rows = []
    reader = csv.reader(io.StringIO(text))
    for r in reader:
        # strip BOM/whitespace
        rows.append([c.strip("\ufeff ").strip() for c in r])
    return rows

def ensure_font(path: str, size: int):
    try:
        if path and Path(ROOT / path).exists():
            return ImageFont.truetype(str(ROOT / path), size=size)
        # try common system font
        return ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", size=size)
    except:
        return ImageFont.load_default()

def apply_pos_keyword(base_xy: Tuple[int,int], w: int, h: int, keyword_xy):
    # keyword_xy supports ["right-80","bottom-60"] etc.
    x, y = base_xy
    kwx, kwy = keyword_xy
    if isinstance(kwx, str) and kwx.startswith("right-"):
        pad = int(kwx.split("-")[1])
        x = w - pad
    elif isinstance(kwx, str) and kwx.startswith("left-"):
        pad = int(kwx.split("-")[1])
        x = pad
    elif isinstance(kwx, (int, float)):
        x = int(kwx)

    if isinstance(kwy, str) and kwy.startswith("bottom-"):
        pad = int(kwy.split("-")[1])
        y = h - pad
    elif isinstance(kwy, str) and kwy.startswith("top-"):
        pad = int(kwy.split("-")[1])
        y = pad
    elif isinstance(kwy, (int, float)):
        y = int(kwy)
    return x, y

def draw_linear_gradient(size, top_color, bottom_color):
    w, h = size
    grad = Image.new("RGBA", (w, h), 0)
    top = Image.new("RGBA", (w, 1), top_color)
    bottom = Image.new("RGBA", (w, 1), bottom_color)
    for y in range(h):
        ratio = y / max(1, h-1)
        r = int((1-ratio)*int(top_color[1:3], 16) + ratio*int(bottom_color[1:3], 16))
        g = int((1-ratio)*int(top_color[3:5], 16) + ratio*int(bottom_color[3:5], 16))
        b = int((1-ratio)*int(top_color[5:7], 16) + ratio*int(bottom_color[5:7], 16))
        ImageDraw.Draw(grad).line([(0, y), (w, y)], fill=(r, g, b, 255))
    return grad

def wrap_text(draw, text, font, max_width):
    # simple single-line clamp if > max_width; else return as-is
    if not text:
        return text
    w, _ = draw.textbbox((0,0), text, font=font)[2:4]
    if w <= max_width:
        return text
    # try trim with ellipsis
    ell = ".."
    for i in range(len(text), 0, -1):
        candidate = text[:i] + ell
        w2, _ = draw.textbbox((0,0), candidate, font=font)[2:4]
        if w2 <= max_width:
            return candidate
    return text

def compose_image(
    title_text: str,
    csv_text: str,
    override_rows: int,
    override_cols: int,
    header_height: int,
    line_width: int,
    padding_x: int,
    padding_y: int,
    scale: float,
    col_widths_csv: str,
    row_heights_csv: str,
    icon_files: List[Optional[gr.File]],
    icon_cells_csv: str,
    align: str,
    valign: str,
    header_top_color: str,
    header_bottom_color: str,
    first_col_color: str,
    text_color: str,
):
    cfg = json.loads((ROOT / "template.json").read_text(encoding="utf-8"))
    W = int(cfg["canvas"]["width"] * scale)
    H = int(cfg["canvas"]["height"] * scale)
    padding = int(cfg["canvas"]["padding"] * scale)

    bg_path = ROOT / cfg["canvas"]["background"]
    if bg_path.exists():
        base = Image.open(bg_path).convert("RGBA").resize((W, H))
    else:
        base = Image.new("RGBA", (W, H), (255,255,255,255))

    draw = ImageDraw.Draw(base)

    # Grid config
    rows_default = cfg["grid"]["rows"]
    cols_default = cfg["grid"]["cols"]
    rows = override_rows or rows_default
    cols = override_cols or cols_default

    col_widths = [0]*cols
    row_heights = [0]*rows
    # overrides from UI CSV (comma separated values)
    if col_widths_csv.strip():
        parts = [p.strip() for p in col_widths_csv.split(",") if p.strip()]
        for i, v in enumerate(parts[:cols]):
            try: col_widths[i] = int(int(v) * scale)
            except: pass
    if row_heights_csv.strip():
        parts = [p.strip() for p in row_heights_csv.split(",") if p.strip()]
        for i, v in enumerate(parts[:rows]):
            try: row_heights[i] = int(int(v) * scale)
            except: pass

    # layout area for table
    table_left = padding
    table_top = padding + (cfg["title"]["font_size"] if cfg["title"]["enabled"] else 0) + 24
    table_right = W - padding
    table_bottom = H - padding - 80  # leave space for logo etc.

    table_w = table_right - table_left
    table_h = table_bottom - table_top

    # compute automatic widths/heights if not specified
    auto_cols = [i for i, wv in enumerate(col_widths) if wv <= 0]
    auto_rows = [i for i, hv in enumerate(row_heights) if hv <= 0]
    if auto_cols:
        rest_w = table_w - sum([wv for wv in col_widths if wv > 0])
        even = max(20, rest_w // max(1, len(auto_cols)))
        for i in auto_cols:
            col_widths[i] = even
    if auto_rows:
        rest_h = table_h - sum([hv for hv in row_heights if hv > 0])
        even = max(20, rest_h // max(1, len(auto_rows)))
        for i in auto_rows:
            row_heights[i] = even

    # draw header gradient bar (under the first row lines)
    header_h = int(header_height * scale)
    if header_h > 0:
        grad = draw_linear_gradient((table_w, header_h), header_top_color, header_bottom_color)
        base.alpha_composite(grad, dest=(table_left, table_top))

    # draw grid lines
    line_col = cfg["grid"]["line_color"]
    line_w = int(line_width * scale)

    # vertical lines
    x = table_left
    for c in range(cols + 1):
        draw.line([(x, table_top), (x, table_top + table_h)], fill=line_col, width=line_w)
        if c < cols:
            x += col_widths[c]
    # horizontal lines
    y = table_top
    for r in range(rows + 1):
        draw.line([(table_left, y), (table_left + table_w, y)], fill=line_col, width=line_w)
        if r < rows:
            y += row_heights[r]

    # parse CSV text into matrix
    data = parse_csv_text(csv_text)
    # normalize to (rows x cols)
    mat = [["" for _ in range(cols)] for __ in range(rows)]
    for r in range(min(rows, len(data))):
        for c in range(min(cols, len(data[r]))):
            mat[r][c] = data[r][c]

    # text fonts
    body_font = ensure_font(cfg["typography"]["font_path"], int(cfg["typography"]["font_size"]*scale))
    header_font = body_font
    firstcol_color = first_col_color
    header_text_color = "#FFFFFF"  # forced white for header text
    body_text_color = text_color

    # icon placement map: "r,c" -> index in icon_files
    icon_map = {}
    if icon_cells_csv.strip():
        parts = [p.strip() for p in icon_cells_csv.split(";") if p.strip()]
        # e.g. "1,1->0; 2,3->1"
        for seg in parts:
            if "->" in seg:
                rc, idx = seg.split("->", 1)
                rc = rc.strip()
                idx = idx.strip()
                try:
                    icon_map[rc] = int(idx)
                except:
                    pass

    # pre-load icons
    pil_icons: Dict[int, Image.Image] = {}
    for i, f in enumerate(icon_files or []):
        if f is None: continue
        try:
            img = Image.open(f.name).convert("RGBA")
            pil_icons[i] = img
        except:
            pass

    # draw cell texts + icons
    cur_y = table_top
    for r in range(rows):
        cur_x = table_left
        for c in range(cols):
            cell_w = col_widths[c]
            cell_h = row_heights[r]
            # text area
            tx = cur_x + padding_x * scale
            ty = cur_y + padding_y * scale
            tw = cell_w - 2*padding_x*scale
            th = cell_h - 2*padding_y*scale

            # choose colors
            color = body_text_color
            if r == 0:
                color = header_text_color
            elif c == 0:
                color = firstcol_color

            # select alignment
            text = mat[r][c]
            font = header_font if r == 0 else body_font
            # clamp one line
            wrapped = wrap_text(draw, text, font, int(tw))

            # measure
            bbox = draw.textbbox((0,0), wrapped, font=font)
            twi = bbox[2] - bbox[0]
            thi = bbox[3] - bbox[1]

            # horizontal align
            if align == "left":
                text_x = int(tx)
            elif align == "right":
                text_x = int(cur_x + cell_w - padding_x*scale - twi)
            else:  # center
                text_x = int(cur_x + (cell_w - twi) / 2)

            # vertical align
            if valign == "top":
                text_y = int(ty)
            elif valign == "bottom":
                text_y = int(cur_y + cell_h - padding_y*scale - thi)
            else:
                text_y = int(cur_y + (cell_h - thi) / 2)

            # render icon if present
            key = f"{r+1},{c+1}"
            if key in icon_map and icon_map[key] in pil_icons:
                icon_img = pil_icons[icon_map[key]].copy()
                # scale icon height
                icon_h = int(TEMPLATE["icons"]["size"] * scale)
                w0, h0 = icon_img.size
                if h0 > 0:
                    icon_w = int(w0 * icon_h / h0)
                    icon_img = icon_img.resize((icon_w, icon_h), Image.LANCZOS)
                else:
                    icon_w = icon_h
                gap = int(TEMPLATE["icons"]["gap"] * scale)

                # place icon at left of text
                icon_x = max(cur_x + int(padding_x*scale), text_x - icon_w - gap)
                icon_y = int(cur_y + (cell_h - icon_h)/2)
                base.alpha_composite(icon_img, dest=(icon_x, icon_y))

                # move text if icon was placed at left and aligning left
                if align == "left":
                    text_x = icon_x + icon_w + gap

            draw.text((text_x, text_y), wrapped, font=font, fill=color)

            cur_x += cell_w
        cur_y += row_heights[r]

    # draw title
    if TEMPLATE["title"]["enabled"] and title_text.strip():
        title_font = ensure_font(TEMPLATE["title"]["font_path"], int(TEMPLATE["title"]["font_size"]*scale))
        tx, ty = TEMPLATE["title"]["position"]
        tx = int(tx * scale); ty = int(ty * scale)
        draw.text((tx, ty), title_text.strip(), font=title_font, fill=TEMPLATE["title"]["text_color"])

    # draw logo
    logo_cfg = TEMPLATE["logo"]
    logo_path = ROOT / logo_cfg["path"]
    if logo_path.exists():
        logo_img = Image.open(logo_path).convert("RGBA")
        max_w = int(logo_cfg["max_width"] * scale)
        if logo_img.width > max_w:
            nh = int(logo_img.height * max_w / logo_img.width)
            logo_img = logo_img.resize((max_w, nh), Image.LANCZOS)
        lx, ly = apply_pos_keyword((W - max_w, H - logo_img.height), W, H, logo_cfg["position"])
        lx = min(max(0, lx - logo_img.width), W - logo_img.width) if "right" in str(logo_cfg["position"][0]) else lx
        ly = min(max(0, ly - logo_img.height), H - logo_img.height) if "bottom" in str(logo_cfg["position"][1]) else ly
        base.alpha_composite(logo_img, dest=(lx, ly))

    out = io.BytesIO()
    base.convert("RGB").save(out, "PNG", optimize=True)
    out.seek(0)
    return out

with gr.Blocks(css=".gradio-container {max-width: 1060px !important;}") as demo:
    gr.Markdown("## 🧩 固定样式表格生成器 · Table Image Generator")
    with gr.Row():
        with gr.Column(scale=1):
            title = gr.Textbox(label="标题 Title", value="每周工作推进表 | Weekly Progress")
            rows = gr.Slider(2, 30, value=TEMPLATE["grid"]["rows"], step=1, label="行数 Rows")
            cols = gr.Slider(2, 20, value=TEMPLATE["grid"]["cols"], step=1, label="列数 Cols")
            csv_text = gr.Textbox(lines=12, label="CSV 文本(第一行是表头)", value=(Path(ROOT/"data_sample.csv").read_text(encoding="utf-8")))
            csv_file = gr.File(label="或上传 CSV 文件", file_types=[".csv"], visible=True)
            with gr.Accordion("可选:图标 Icon(多个),并指定落在哪个格子", open=False):
                icons = gr.Files(label="上传多个 Icon(PNG/SVG/JPG)")
                icon_cells = gr.Textbox(label="Icon 位置映射(例:`1,1->0; 2,3->1`,索引从0开始)", placeholder="1,1->0; 2,3->1")
            with gr.Accordion("可选:布局微调", open=False):
                col_widths = gr.Textbox(label="列宽(逗号分隔,留空=等分)", placeholder="220,320,260,260,260,260")
                row_heights = gr.Textbox(label="行高(逗号分隔,留空=等分)", placeholder="100,100,120,120,120,120,120,120")
                header_height = gr.Slider(0, 200, value=TEMPLATE["header"]["height"], step=2, label="表头渐变高度")
                line_width = gr.Slider(1, 8, value=TEMPLATE["grid"]["line_width"], step=1, label="线条粗细")
                pad_x = gr.Slider(8, 64, value=TEMPLATE["cell"]["padding_x"], step=1, label="左右内边距")
                pad_y = gr.Slider(4, 48, value=TEMPLATE["cell"]["padding_y"], step=1, label="上下内边距")
                align = gr.Radio(["left","center","right"], value=TEMPLATE["typography"]["align"], label="水平对齐")
                valign = gr.Radio(["top","middle","bottom"], value=TEMPLATE["typography"]["valign"], label="垂直对齐")
            with gr.Accordion("可选:颜色覆盖(默认用模板里的颜色)", open=False):
                header_top = gr.ColorPicker(value=TEMPLATE["header"]["gradient_top"], label="表头渐变上色")
                header_bottom = gr.ColorPicker(value=TEMPLATE["header"]["gradient_bottom"], label="表头渐变下色")
                first_col = gr.ColorPicker(value="#1639E7", label="第一列文字颜色")
                text_col = gr.ColorPicker(value="#0B1020", label="正文文字颜色")
            scale = gr.Slider(0.5, 2.0, value=TEMPLATE["export"]["scale"], step=0.1, label="导出缩放倍数(1.0=1920×1080)")
            generate_btn = gr.Button("🔄 生成预览 / Generate")
            export_btn = gr.Button("⬇️ 导出PNG / Export")

        with gr.Column(scale=1):
            preview = gr.Image(label="预览 Preview", interactive=False)
            download = gr.File(label="导出文件", interactive=False)

    def coalesce_csv(csv_text, csv_file):
        if csv_file is None:
            return csv_text
        try:
            return Path(csv_file.name).read_text(encoding="utf-8")
        except:
            return csv_text

    def do_generate(title_text, rows, cols, csv_text, csv_file, icons, icon_cells, col_widths, row_heights, header_height, line_width, pad_x, pad_y, align, valign, header_top, header_bottom, first_col, text_col, scale):
        csv_final = coalesce_csv(csv_text, csv_file)
        out = compose_image(
            title_text=title_text,
            csv_text=csv_final,
            override_rows=int(rows),
            override_cols=int(cols),
            header_height=int(header_height),
            line_width=int(line_width),
            padding_x=int(pad_x),
            padding_y=int(pad_y),
            scale=float(scale),
            col_widths_csv=col_widths or "",
            row_heights_csv=row_heights or "",
            icon_files=icons or [],
            icon_cells_csv=icon_cells or "",
            align=align,
            valign=valign,
            header_top_color=header_top,
            header_bottom_color=header_bottom,
            first_col_color=first_col,
            text_color=text_col,
        )
        return out

    def do_export(title_text, rows, cols, csv_text, csv_file, icons, icon_cells, col_widths, row_heights, header_height, line_width, pad_x, pad_y, align, valign, header_top, header_bottom, first_col, text_col, scale):
        buf = do_generate(title_text, rows, cols, csv_text, csv_file, icons, icon_cells, col_widths, row_heights, header_height, line_width, pad_x, pad_y, align, valign, header_top, header_bottom, first_col, text_col, scale)
        out_path = ROOT / "output.png"
        with open(out_path, "wb") as f:
            f.write(buf.getbuffer())
        return gr.File.update(value=str(out_path), visible=True)

    generate_btn.click(
        fn=do_generate,
        inputs=[title, rows, cols, csv_text, csv_file, icons, icon_cells, col_widths, row_heights, header_height, line_width, pad_x, pad_y, align, valign, header_top, header_bottom, first_col, text_col, scale],
        outputs=preview
    )
    export_btn.click(
        fn=do_export,
        inputs=[title, rows, cols, csv_text, csv_file, icons, icon_cells, col_widths, row_heights, header_height, line_width, pad_x, pad_y, align, valign, header_top, header_bottom, first_col, text_col, scale],
        outputs=download
    )

if __name__ == "__main__":
    demo.launch()