AITaskProject / app.py
dejavuwk's picture
upload file
6d6bd90 verified
Raw History Blame Contribute Delete
22 kB
# app.py โ€” Dotstagram (๋‹ท์Šคํƒ€๊ทธ๋žจ)
# Hugging Face Spaces: Space SDK = Gradio, Public, CPU Basic ๊ถŒ์žฅ
import io, os, re, time, random, datetime, zipfile
import numpy as np
from PIL import Image, ImageOps
import gradio as gr
import plotly.graph_objects as go
# ์„ ํƒ ์˜์กด์„ฑ (์—†์–ด๋„ ๋™์ž‘ํ•˜๋„๋ก ์˜ˆ์™ธ ์ฒ˜๋ฆฌ)
try:
import pillow_heif
except Exception:
pillow_heif = None
try:
import piexif
except Exception:
piexif = None
# ์„ ํƒ(Torch) โ€” ์žˆ์œผ๋ฉด ๋ถ„๋ฅ˜ ๋ณด์กฐ, ์—†์–ด๋„ ํœด๋ฆฌ์Šคํ‹ฑ์œผ๋กœ ๋™์ž‘
USE_TORCH = True
try:
import torch
from torchvision.models import mobilenet_v3_small, MobileNet_V3_Small_Weights
WEIGHTS = MobileNet_V3_Small_Weights.DEFAULT
TRANS = WEIGHTS.transforms()
MODEL = mobilenet_v3_small(weights=WEIGHTS).eval()
LABELS = WEIGHTS.meta["categories"]
except Exception:
USE_TORCH, MODEL, LABELS = False, None, []
# ----------------- ๋ผ๋ฒจ/๊ทœ์น™ -----------------
STYLES = ["์ •๋ณดํ˜•","๊ฐ์„ฑํ˜•","์œ ๋จธํ˜•","์˜์–ดํ˜•"]
FOOD_KEYWORDS = {
# ์‹๊ธฐ/์กฐ๋ฆฌ๋„๊ตฌ
"bowl","soup bowl","cup","mug","coffee mug","teapot","plate","dinner plate",
"spoon","ladle","fork","knife","chopsticks","cooking pot","cauldron","skillet","pan","tray","dish",
# ๐Ÿ”ฅ ๊ณ ๊ธฐ/๊ทธ๋ฆด/ํ™”๋กœ ๋ณด๊ฐ•
"meat","beef","steak","grill","barbecue","barbeque","bbq","kebab","yakitori",
"charcoal","fire","roast","rib","brisket"
}
CITY_KEYWORDS = {"traffic light","street sign","streetcar","bus","train","trailer truck","taxi","building","skyscraper","viaduct","steel arch bridge","dam","castle"}
BEACH_KEYWORDS = {"seashore","sandbar","pier","harbor","breakwater","lakeside"}
MOUNTAIN_KEYWORDS = {"alp","volcano","valley","mountain tent"}
INDOOR_KEYWORDS = {"dining table","restaurant","bar","bookcase","desk","sofa","refrigerator","microwave","oven","stove"}
def coarse_category_from_labels(top_labels):
s = {lbl.lower() for lbl in top_labels}
if FOOD_KEYWORDS & s: return "food"
if BEACH_KEYWORDS & s: return "beach"
if MOUNTAIN_KEYWORDS & s: return "mountain"
if CITY_KEYWORDS & s: return "city"
if INDOOR_KEYWORDS & s: return "indoors"
return "nature"
def coarse_category_fallback(img: Image.Image):
arr = np.asarray(img.convert("RGB").resize((128,128)))
mean = arr.mean(axis=(0,1))
bright = mean.mean()
blue_ratio = mean[2] / (mean.mean()+1e-6)
green_ratio = mean[1] / (mean.mean()+1e-6)
warm_hint = (mean[0] > mean[2] + 10) and (bright > 60)
if warm_hint: return "food"
if blue_ratio > 1.15 and bright > 120: return "beach"
if green_ratio > 1.15: return "nature"
if bright < 65: return "night"
return "city"
def detect_category(img: Image.Image):
try:
if USE_TORCH and MODEL is not None:
x = TRANS(img).unsqueeze(0)
with torch.no_grad():
logits = MODEL(x)[0]
topk = logits.topk(7).indices.cpu().numpy().tolist()
top_labels = [LABELS[i].lower() for i in topk]
cat = coarse_category_from_labels(top_labels)
else:
cat = coarse_category_fallback(img)
except Exception:
cat = coarse_category_fallback(img)
# ๐Ÿ”ฅ ๋ถ‰์€์ƒ‰(๊ณ ๊ธฐ/๋ถˆ) + ๊ทธ๋ฆด ์งˆ๊ฐ ๋ณด์ •
arr = np.asarray(img.convert("RGB").resize((160,160)))
r,g,b = arr[:,:,0], arr[:,:,1], arr[:,:,2]
red_mask = (r > (g+18)) & (r > (b+18))
grill_mask = ((r+g+b)/3 < 110) & (r<120) & (g<120) & (b<120)
if red_mask.mean() > 0.22 or (red_mask & grill_mask).mean() > 0.12:
cat = "food"
# ์•ผ๊ฐ„ ๋ณด์ •(์Œ์‹์ด๋ฉด ์œ ์ง€)
if cat != "food":
if np.asarray(img.convert("L")).mean() < 65:
cat = "night"
return cat
HASHTAGS = {
"food":["#๋ง›์ง‘","#๋จน์Šคํƒ€๊ทธ๋žจ","#ํ‘ธ๋“œ","#๋””๋„ˆ","#์˜ค๋Š˜๋ญ๋จน์ง€","#yummy","#foodie","#foodpics"],
"city":["#๋„์‹œ","#์•ผ๊ฒฝ","#์Šค๋ƒ…","#์‹œํ‹ฐ๋ผ์ดํ”„","#urban","#cityscape"],
"nature":["#์ž์—ฐ","#ํ’๊ฒฝ","#ํž๋ง","#์—ฌํ–‰","#ํ•˜์ดํ‚น","#nature","#scenery"],
"beach":["#๋ฐ”๋‹ค","#ํ•ด๋ณ€","#์—ฌ๋ฆ„","#๋ฐ”์บ‰์Šค","#sunset","#ocean"],
"mountain":["#์‚ฐ","#ํŠธ๋ ˆํ‚น","#๋“ฑ์‚ฐ","#์ „๋ง","#mountain"],
"indoors":["#์‹ค๋‚ด","#์นดํŽ˜","#์ธํ…Œ๋ฆฌ์–ด","#cozy","#์ผ์ƒ"],
"night":["#์•ผ๊ฒฝ","#๋ฐค์‚ฐ์ฑ…","#๋„ค์˜จ์‚ฌ์ธ","#night","#citylights"]
}
def tags_for(cat):
base = HASHTAGS.get(cat, HASHTAGS["nature"])
k = random.randint(5, min(8, len(base)))
return " ".join(random.sample(base, k))
CAPTION_LIB = {
"food":{
"์ •๋ณดํ˜•":["์˜ค๋Š˜์˜ ๋ฉ”๋‰ด ๊ธฐ๋ก.","๋”ฐ๋ˆํ•œ ํ•œ ๊ทธ๋ฆ‡."],
"๊ฐ์„ฑํ˜•":["ํ•œ ์ž…์— ํ–‰๋ณต์ด ํผ์ง€๋Š” ์‹œ๊ฐ„ ๐Ÿ˜‹","ํ–ฅ๊ณผ ์˜จ๋„๊ฐ€ ๋จผ์ € ์™€๋‹ฟ๋Š” ์ˆœ๊ฐ„.","์ž‘์€ ๊ทธ๋ฆ‡์— ๋‹ด๊ธด ํฐ ์œ„๋กœ."],
"์œ ๋จธํ˜•":["์นผ๋กœ๋ฆฌ๋Š” ๋น„๋ฐ€, ๋ง›์€ ๊ณต๊ฐœ ๐Ÿคซ","๋‹ค์ด์–ดํŠธ๋Š” ๋‚ด์ผ๋ถ€ํ„ฐ, ์‚ฌ์ง„์€ ์˜ค๋Š˜๋ถ€ํ„ฐ!","์ง€๊ธ€์ง€๊ธ€ ์†Œ๋ฆฌ์— ์‹ฌ์žฅ๋„ ์ต๋Š”๋‹ค."],
"์˜์–ดํ˜•":["Comfort in a bowl.","Little bites, big joy โœจ","Savoring this moment."]
},
"city":{
"์ •๋ณดํ˜•":["๋„์‹œ์˜ ๋‹จ๋ฉด์„ ๊ธฐ๋กํ•ฉ๋‹ˆ๋‹ค."],
"๊ฐ์„ฑํ˜•":["๋น›๊ณผ ์†Œ์Œ ์‚ฌ์ด๋กœ ์Šค๋ฉฐ๋“œ๋Š” ํ•œ ์žฅ๋ฉด."],
"์œ ๋จธํ˜•":["๋„ค์˜จ์‚ฌ์ธ ์•„๋ž˜์„œ ๊ธธ์น˜ ํƒˆ์ถœ!"],
"์˜์–ดํ˜•":["City pace, quiet frame."]
},
"nature":{
"์ •๋ณดํ˜•":["ํ’๊ฒฝ์˜ ๊ธฐ๋ก ํ•œ ์ปท."],
"๊ฐ์„ฑํ˜•":["๋ฐ”๋žŒ์ด ๋จผ์ € ๋ง์„ ๊ฑฐ๋Š” ๊ณณ ๐ŸŒฟ"],
"์œ ๋จธํ˜•":["๋ฒŒ๋ ˆ๋Š” ์‹ซ์ง€๋งŒ ํ’๊ฒฝ์€ ์‚ฌ๋ž‘ํ•ด ๐Ÿ"],
"์˜์–ดํ˜•":["Slow steps, soft light."]
},
"beach":{
"์ •๋ณดํ˜•":["ํ•ด๋ณ€์˜ ํ•œ ์žฅ๋ฉด."],
"๊ฐ์„ฑํ˜•":["๋ชจ๋ž˜์™€ ๋ฐ”๋žŒ์ด ๋งŒ๋“  ์˜คํ›„ ๐ŸŒŠ"],
"์œ ๋จธํ˜•":["์ฌ์Šคํฌ๋ฆฐ ํ’€์˜ต์…˜ ON."],
"์˜์–ดํ˜•":["Salt air, simple joy."]
},
"mountain":{
"์ •๋ณดํ˜•":["๋Šฅ์„  ์œ„์—์„œ ๊ธฐ๋ก."],
"๊ฐ์„ฑํ˜•":["์ˆจ์ด ์ฐจ๋ฉด ๋งˆ์Œ์ด ์—ด๋ฆฐ๋‹ค."],
"์œ ๋จธํ˜•":["์ •์ƒ์—์„œ์˜ ํ•œ ๋ชจ๊ธˆ์ด ์ธ์ƒ๋ง›."],
"์˜์–ดํ˜•":["Closer to the clouds."]
},
"indoors":{
"์ •๋ณดํ˜•":["์‹ค๋‚ด์˜ ์˜จ๋„๋ฅผ ์‚ฌ์ง„์—."],
"๊ฐ์„ฑํ˜•":["์กฐ๋ช…์ด ๋งํ•ด์ฃผ๋Š” ์˜คํ›„ โ˜•๏ธ"],
"์œ ๋จธํ˜•":["์นด๊ณต์€ ํ•‘๊ณ„, ๋””์ €ํŠธ๊ฐ€ ์ง„์‹ฌ ๐Ÿฐ"],
"์˜์–ดํ˜•":["Cozy light, easy pace."]
},
"night":{
"์ •๋ณดํ˜•":["๋ฐค์˜ ๊ฒฐ์„ ๊ธฐ๋กํ•ฉ๋‹ˆ๋‹ค."],
"๊ฐ์„ฑํ˜•":["์–ด๋‘ ์ด ๋น›์„ ๋” ์„ ๋ช…ํ•˜๊ฒŒ."],
"์œ ๋จธํ˜•":["ISO๋Š” ์˜ฌ๋ฆฌ๊ณ  ๊ฑฑ์ •์€ ๋‚ด๋ฆฌ๊ณ  โœจ"],
"์˜์–ดํ˜•":["Neon hum, quiet heart."]
}
}
HOOKS = {
"food":["์ง€๊ธ€์ง€๊ธ€, ์˜ค๋Š˜์˜ ํ–‰๋ณต","ํ•œ ์ˆŸ๊ฐ€๋ฝ์˜ ์œ„๋กœ","์ž…์•ˆ์—์„œ ์‚ฌ๋ฅด๋ฅด"],
"city":["์˜ค๋Š˜์˜ ๊ฑฐ๋ฆฌ","๋ฐœ๊ฑธ์Œ์ด ๊ฐ€๋ฆฌํ‚ค๋Š” ๊ณณ"],
"nature":["์ˆจ ์‰ฌ๋Š” ํ’๊ฒฝ","์ฒœ์ฒœํžˆ ์Šค๋ฉฐ๋“œ๋Š” ๋น›"],
"beach":["ํŒŒ๋„์™€ ํ•œ ๊ฑธ์Œ","์†Œ๊ธˆ๊ธฐ ๊ฐ€๋“ํ•œ ์˜คํ›„"],
"mountain":["๊ณ ๋„๋ฅผ ์˜ฌ๋ฆฐ ๋ณด์ƒ","๋Šฅ์„  ์œ„์˜ ํ˜ธํก"],
"indoors":["๋”ฐ๋œปํ•œ ์กฐ๋„","์กฐ์šฉํ•œ ์˜จ๋„"],
"night":["๋ฐค์ด ๋ฌผ๋“œ๋Š” ์‹œ๊ฐ„","๋„ค์˜จ์˜ ๋งฅ๋ฐ•"]
}
def smart_caption(style, img):
cat = detect_category(img)
hook = random.choice(HOOKS.get(cat, HOOKS["nature"]))
sent = random.choice(CAPTION_LIB.get(cat, CAPTION_LIB["nature"]).get(style, CAPTION_LIB["nature"]["๊ฐ์„ฑํ˜•"]))
return f"{hook}. {sent}", cat
# ----------------- ์ด๋ฏธ์ง€ ๋กœ๋“œ/ํšŒ์ „ ๋ณด์ • -----------------
def open_image_any(path):
p = str(path).lower()
if pillow_heif and p.endswith((".heic",".heif")):
he = pillow_heif.read_heif(path)
img = Image.frombytes(he.mode, he.size, he.data).convert("RGB")
else:
img = Image.open(path).convert("RGB")
return ImageOps.exif_transpose(img), "IMG"
# ----------------- GPS ์ถ”์ถœ(๊ฒฌ๊ณ ) -----------------
def _to_float(x):
try:
num = getattr(x, "numerator", None); den = getattr(x, "denominator", None)
if num is not None and den is not None: return float(num)/float(den)
if isinstance(x,(tuple,list)) and len(x)==2: return float(x[0])/float(x[1])
return float(x)
except: return None
def _dms2deg(dms, ref):
if not dms or ref is None: return None
if isinstance(ref,(bytes,bytearray)): ref = ref.decode(errors="ignore").upper()
parts = dms if isinstance(dms,(list,tuple)) else [dms,0,0]
vals = [_to_float(v) for v in parts[:3]]
if any(v is None for v in vals): return None
d,m,s = vals; val = d + m/60.0 + s/3600.0
if ref in ('S','W'): val = -val
return val
def _clamp(lat, lon):
if lat is None or lon is None: return None
if -90<=lat<=90 and -180<=lon<=180: return (round(float(lat),6), round(float(lon),6))
return None
def extract_gps_any(path):
# 1) Pillow info.exif
try:
img,_=open_image_any(path); info=getattr(img,"info",{}) or {}
exif_bytes = info.get("exif")
if exif_bytes and piexif:
ex=piexif.load(exif_bytes); gps=ex.get("GPS") or {}
la=_dms2deg(gps.get(piexif.GPSIFD.GPSLatitude),gps.get(piexif.GPSIFD.GPSLatitudeRef,b'N'))
lo=_dms2deg(gps.get(piexif.GPSIFD.GPSLongitude),gps.get(piexif.GPSIFD.GPSLongitudeRef,b'E'))
cl=_clamp(la,lo)
if cl: return cl,"โœ” info['exif']"
except Exception:
pass
# 2) ํŒŒ์ผ ๊ฒฝ๋กœ๋กœ piexif
try:
if piexif:
ex=piexif.load(path); gps=ex.get("GPS") or {}
la=_dms2deg(gps.get(piexif.GPSIFD.GPSLatitude),gps.get(piexif.GPSIFD.GPSLatitudeRef,b'N'))
lo=_dms2deg(gps.get(piexif.GPSIFD.GPSLongitude),gps.get(piexif.GPSIFD.GPSLongitudeRef,b'E'))
cl=_clamp(la,lo)
if cl: return cl,"โœ” piexif(path)"
except Exception:
pass
# 3) exifread ํด๋ฐฑ
try:
import exifread
with open(path,'rb') as f:
tags = exifread.process_file(f, details=False)
def _val(tag):
return tags.get(tag)
lat = _val('GPS GPSLatitude'); lat_ref = _val('GPS GPSLatitudeRef')
lon = _val('GPS GPSLongitude'); lon_ref = _val('GPS GPSLongitudeRef')
if lat and lon and lat_ref and lon_ref:
def _to_tuple(v):
parts = [float(n.num)/float(n.den) for n in v.values]
return parts
la = _dms2deg(_to_tuple(lat), str(lat_ref.values))
lo = _dms2deg(_to_tuple(lon), str(lon_ref.values))
cl=_clamp(la,lo)
if cl: return cl,"โœ” exifread"
except Exception:
pass
return None,"GPS ์ถ”์ถœ ์‹คํŒจ"
# ----------------- IG ์บ”๋ฒ„์Šค -----------------
def avg_color(img):
arr = np.asarray(img.convert("RGB").resize((32,32))).reshape(-1,3).mean(axis=0)
r,g,b = [int(0.65*c + 0.35*255) for c in arr]
return (r,g,b)
def to_instagram_canvas(img, target_w=1080, min_h=566, max_h=1350):
w,h = img.size; ratio = w/h if h else 1
calc_h = int(round(target_w/max(ratio,1e-6)))
target_h = min(max(calc_h, min_h), max_h)
scale = min(target_w/w, target_h/h)
new_w,new_h = int(round(w*scale)), int(round(h*scale))
resized = img.resize((new_w,new_h), Image.LANCZOS)
bg = avg_color(img)
canvas = Image.new("RGB",(target_w,target_h),bg)
canvas.paste(resized,((target_w-new_w)//2,(target_h-new_h)//2))
return canvas
# ----------------- ์ง€๋„ ๊ณ„์‚ฐ (Plotly Figure ๋ฐ˜ํ™˜) -----------------
def _auto_zoom_ranges(coords, pad=0.25):
if not coords:
return 0,0,[-60,60],[-180,180]
lats=[c[0] for c in coords]; lons=[c[1] for c in coords]
min_lat,max_lat=min(lats),max(lats); min_lon,max_lon=min(lons),max(lons)
dlat=(max_lat-min_lat)*(1+pad); dlon=(max_lon-min_lon)*(1+pad)
MIN_LAT_SPAN, MIN_LON_SPAN = 25.0, 40.0
dlat=max(dlat, MIN_LAT_SPAN); dlon=max(dlon, MIN_LON_SPAN)
clat=(min_lat+max_lat)/2; clon=(min_lon+max_lon)/2
lat_range=[max(-85,clat-dlat/2), min(85,clat+dlat/2)]
lon_range=[max(-180,clon-dlon/2), min(180,clon+dlon/2)]
return clat,clon,lat_range,lon_range
def _half_globe_ranges(center_lat, center_lon):
LAT_SPAN = 90.0
LON_SPAN = 180.0
lat_min = max(-85, center_lat - LAT_SPAN/2)
lat_max = min( 85, center_lat + LAT_SPAN/2)
lon_min = max(-180, center_lon - LON_SPAN/2)
lon_max = min( 180, center_lon + LON_SPAN/2)
return [lat_min, lat_max], [lon_min, lon_max]
def build_dot_world(coords, step=5, dot_size=6, ranges=None, center=None):
# ์ค‘์‹ฌ/๋ฒ”์œ„ ๊ณ„์‚ฐ
if ranges is None:
if coords:
clat,clon,lat_range,lon_range=_auto_zoom_ranges(coords)
else:
clat,clon=0,0
lat_range,lon_range=[-60,60],[-180,180]
else:
lat_range, lon_range = ranges
if center:
clat,clon = center
else:
clat = sum(lat_range)/2; clon = sum(lon_range)/2
span = max(lon_range[1]-lon_range[0], lat_range[1]-lat_range[0])
step_dyn = min(20, max(2, span/12))
lon_edges=np.arange(-180,180,step_dyn)
lat_edges=np.arange(-90,90,step_dyn)
lon_centers=lon_edges+(lon_edges[1]-lon_edges[0])/2
lat_centers=lat_edges+(lat_edges[1]-lat_edges[0])/2
LON,LAT=np.meshgrid(lon_centers,lat_centers)
fig=go.Figure()
# ํฐ ๋ฐ”ํƒ• + ์—ฐํšŒ์ƒ‰ ๋„ํŠธ
fig.add_trace(go.Scattergeo(
lon=LON.ravel(), lat=LAT.ravel(), mode="markers",
marker=dict(size=dot_size, color="rgba(180,180,180,0.55)"),
hoverinfo="skip", showlegend=False
))
# ๋นจ๊ฐ„ ์ (์—…๋กœ๋“œ ์ขŒํ‘œ)
if coords:
total=len(coords); bins={}
for (la,lo) in coords: bins[(la,lo)]=bins.get((la,lo),0)+1
for (la,lo),cnt in bins.items():
intensity=int(50+205*(cnt/total))
fig.add_trace(go.Scattergeo(
lon=[lo], lat=[la], mode="markers",
marker=dict(size=dot_size*2, color=f"rgba({intensity},0,0,0.95)"),
hoverinfo="skip", showlegend=False
))
fig.update_geos(
projection_type="natural earth",
center=dict(lat=clat, lon=clon),
lataxis=dict(range=lat_range), lonaxis=dict(range=lon_range),
showcoastlines=True, coastlinecolor="#444",
showcountries=False, showland=False, showocean=False,
lataxis_showgrid=False, lonaxis_showgrid=False
)
fig.update_layout(
paper_bgcolor="white", plot_bgcolor="white",
margin=dict(l=0, r=0, t=0, b=0), height=420, showlegend=False
)
fig.update_layout(modebar=dict(remove=['lasso2d','select2d']))
return fig
# ----------------- ๋‚ด๋ณด๋‚ด๊ธฐ ZIP -----------------
def export_instagram(ig_canvas_pil, combined_text):
if ig_canvas_pil is None or not combined_text:
return None
ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
base = f"/tmp/dotstagram_export_{ts}"
img_path = f"{base}.jpg"
txt_path = f"{base}_caption.txt"
readme_path = f"{base}_README.txt"
zip_path = f"{base}.zip"
# JPG ์ €์žฅ (+๊ฐ€๋Šฅํ•˜๋ฉด EXIF UserComment์— ์บก์…˜ ๊ธฐ๋ก)
if piexif:
try:
exif_dict = {"0th":{}, "Exif":{}, "GPS":{}, "1st":{}, "thumbnail":None}
user_comment = ("ASCII\0\0\0" + combined_text).encode("ascii","ignore")
exif_dict["Exif"][piexif.ExifIFD.UserComment] = user_comment
exif_bytes = piexif.dump(exif_dict)
ig_canvas_pil.save(img_path, "JPEG", quality=95, exif=exif_bytes)
except Exception:
ig_canvas_pil.save(img_path, "JPEG", quality=95)
else:
ig_canvas_pil.save(img_path, "JPEG", quality=95)
with open(txt_path, "w", encoding="utf-8") as f:
f.write(combined_text)
with open(readme_path, "w", encoding="utf-8") as f:
f.write(
"Dotstagram Export\n"
"- dotstagram.jpg : 1080px ์ธ์Šคํƒ€๊ทธ๋žจ ์—…๋กœ๋“œ์šฉ ์ด๋ฏธ์ง€\n"
"- caption.txt : ์บก์…˜ + ํ•ด์‹œํƒœ๊ทธ (๋ณต์‚ฌํ•ด์„œ IG์— ๋ถ™์—ฌ๋„ฃ๊ธฐ)\n"
"โ€ป ๋ธŒ๋ผ์šฐ์ €/์•ฑ์— ๋”ฐ๋ผ EXIF(UserComment)๋Š” ํ‘œ์‹œ๋˜์ง€ ์•Š์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.\n"
)
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as z:
z.write(img_path, arcname="dotstagram.jpg")
z.write(txt_path, arcname="caption.txt")
z.write(readme_path, arcname="README.txt")
return zip_path
# ----------------- ํ•ธ๋“ค๋Ÿฌ -----------------
def on_upload(file, style, coords_state, step, dot_size):
if file is None:
empty_fig = build_dot_world(coords_state or [], step, dot_size)
return None, None, coords_state or [], "", empty_fig, "ํŒŒ์ผ ์—†์Œ", None
path = file.name
img,_ = open_image_any(path)
gps,_ = extract_gps_any(path)
coords_state = coords_state or []
# โœ… GPS ์—†์œผ๋ฉด ์„œ์šธ(37.5665, 126.9780) ๊ธฐ๋ณธ๊ฐ’
if gps:
coords_state.append(gps)
else:
gps = (37.5665, 126.9780)
coords_state.append(gps)
caption,cat = smart_caption(style, img)
combined = f"{caption}\n{tags_for(cat)}"
ig_img = to_instagram_canvas(img)
fig = build_dot_world(coords_state, step, dot_size)
status = f"Dotstagram ยท category={cat} | GPS: {gps if gps else '์—†์Œ'}"
last_pt = coords_state[-1] if coords_state else None
return img, ig_img, coords_state, combined, fig, status, last_pt
def retry_caption(image_state, style):
if image_state is None: return "๋จผ์ € ์‚ฌ์ง„์„ ์—…๋กœ๋“œํ•ด์ฃผ์„ธ์š”."
caption,cat = smart_caption(style, image_state)
return f"{caption}\n{tags_for(cat)}"
def manual_add(coords_state, lat, lon, step, dot_size):
coords_state = coords_state or []
try:
la=float(lat); lo=float(lon)
if -90<=la<=90 and -180<=lo<=180:
coords_state.append((round(la,6), round(lo,6)))
return coords_state, build_dot_world(coords_state, step, dot_size), "์ˆ˜๋™ ์ขŒํ‘œ ์ถ”๊ฐ€๋จ โœ…"
else:
return coords_state, build_dot_world(coords_state, step, dot_size), "์œ„๋„/๊ฒฝ๋„ ๋ฒ”์œ„๋ฅผ ํ™•์ธํ•˜์„ธ์š”."
except:
return coords_state, build_dot_world(coords_state, step, dot_size), "์ˆซ์ž ํ˜•์‹์˜ ์œ„๋„/๊ฒฝ๋„๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”."
def update_map(coords_state, step, dot_size):
return build_dot_world(coords_state or [], step, dot_size)
def reset_all(step, dot_size):
empty = build_dot_world([], step, dot_size)
return None, None, [], "", empty, None, None, "์ดˆ๊ธฐํ™” ์™„๋ฃŒ"
def on_export(ig_canvas_pil, combined_text):
path = export_instagram(ig_canvas_pil, combined_text)
return path or None
# ์ง€๋„ ๋ณด๊ธฐ ๋ชจ๋“œ
def view_world(coords_state, step, dsize):
ranges = ([-60,60], [-180,180])
fig = build_dot_world(coords_state or [], step, dsize, ranges=ranges, center=(0,0))
return fig
def view_half(coords_state, last_pt, step, dsize):
if last_pt is None and coords_state:
last_pt = coords_state[-1]
center = last_pt if last_pt else (0,0)
ranges = _half_globe_ranges(center[0], center[1])
fig = build_dot_world(coords_state or [], step, dsize, ranges=ranges, center=center)
return fig
# ----------------- UI -----------------
with gr.Blocks(title="Dotstagram (๋‹ท์Šคํƒ€๊ทธ๋žจ)") as demo:
gr.Markdown("# **Dotstagram (๋‹ท์Šคํƒ€๊ทธ๋žจ)**")
gr.Markdown("๋„ํŠธ๋กœ ๊ธฐ์–ต์„ ์ฐ๊ณ , ๋ฌธ์žฅ์œผ๋กœ ์ˆœ๊ฐ„์„ ๋‚จ๊ฒจ์š”.")
image_state = gr.State(None) # ์›๋ณธ PIL(ํšŒ์ „ ๋ณด์ •)
ig_canvas_state = gr.State(None) # IG ์บ”๋ฒ„์Šค PIL
coords_state = gr.State([]) # GPS ํฌ์ธํŠธ๋“ค
last_point = gr.State(None) # ๋งˆ์ง€๋ง‰ ์—…๋กœ๋“œ ์ขŒํ‘œ(์ค‘์•™์šฉ)
with gr.Row():
style = gr.Radio(STYLES, value="๊ฐ์„ฑํ˜•", label="์บก์…˜ ์Šคํƒ€์ผ")
step = gr.Slider(1, 20, value=5, step=1, label="๋„ํŠธ ๊ฐ„๊ฒฉ(ยฐ)")
dsize = gr.Slider(4, 14, value=6, step=1, label="๋„ํŠธ ํฌ๊ธฐ(px)")
reset_btn = gr.Button("๐Ÿ”„ ์ดˆ๊ธฐํ™”")
file_in = gr.File(file_types=["image"], label="์‚ฌ์ง„ ์—…๋กœ๋“œ (์›๋ณธ EXIF ๊ถŒ์žฅ)")
with gr.Row():
ig_preview = gr.Image(type="pil", label="๐Ÿ“ฑ ์ธ์Šคํƒ€๊ทธ๋žจ ๋А๋‚Œ ๋ฏธ๋ฆฌ๋ณด๊ธฐ")
map_out = gr.Plot(label="๐Ÿ—บ๏ธ ์ง€๋„(๋„ํŠธ ํƒ€๊ณตํŒ)")
with gr.Row():
world_btn = gr.Button("๐ŸŒ ์ง€๋„ ์ „์ฒด๋ณด๊ธฐ")
half_btn = gr.Button("๐Ÿ”Ž ๋ฐ˜์ง€๊ตฌ ๋ณด๊ธฐ(๋นจ๊ฐ„์  ์ค‘์•™)")
combined_box = gr.Textbox(label="โœจ ์บก์…˜ + ํ•ด์‹œํƒœ๊ทธ (๋ณต์‚ฌ ๋ฒ„ํŠผ)", lines=4, show_copy_button=True)
with gr.Row():
retry_btn = gr.Button("โ™ป๏ธ ์บก์…˜๋งŒ ๋‹ค์‹œ ์ƒ์„ฑ")
export_btn = gr.DownloadButton(label="๐Ÿ“ค Instagram ๋‚ด๋ณด๋‚ด๊ธฐ(.zip)", value=None)
status_md = gr.Markdown("")
with gr.Accordion("๐Ÿ“ EXIF๊ฐ€ ์—†์œผ๋ฉด ์ˆ˜๋™์œผ๋กœ ์œ„์น˜ ์ถ”๊ฐ€", open=False):
lat_in = gr.Textbox(label="์œ„๋„ ์˜ˆ: 37.5665")
lon_in = gr.Textbox(label="๊ฒฝ๋„ ์˜ˆ: 126.9780")
add_btn = gr.Button("์ขŒํ‘œ ์ถ”๊ฐ€")
# ์—…๋กœ๋“œ ์—ฐ๋™
def _store_and_process(file, style, coords, step, dsize):
img, ig_img, coords, combined, fig, status, lp = on_upload(file, style, coords, step, dsize)
return img, ig_img, ig_img, coords, combined, fig, status, lp
file_in.upload(
fn=_store_and_process,
inputs=[file_in, style, coords_state, step, dsize],
outputs=[image_state, ig_preview, ig_canvas_state, coords_state, combined_box, map_out, status_md, last_point]
)
retry_btn.click(fn=retry_caption, inputs=[image_state, style], outputs=combined_box)
add_btn.click(fn=manual_add, inputs=[coords_state, lat_in, lon_in, step, dsize],
outputs=[coords_state, map_out, status_md])
step.change(fn=update_map, inputs=[coords_state, step, dsize], outputs=map_out)
dsize.change(fn=update_map, inputs=[coords_state, step, dsize], outputs=map_out)
world_btn.click(fn=view_world, inputs=[coords_state, step, dsize], outputs=map_out)
half_btn.click(fn=view_half, inputs=[coords_state, last_point, step, dsize], outputs=map_out)
reset_btn.click(fn=reset_all, inputs=[step, dsize],
outputs=[image_state, ig_canvas_state, coords_state, combined_box, map_out, file_in, ig_preview, status_md])
export_btn.click(fn=on_export, inputs=[ig_canvas_state, combined_box], outputs=export_btn)
# ๋กœ์ปฌ ์‹คํ–‰์šฉ
if __name__ == "__main__":
demo.launch()