Spaces:
Sleeping
Sleeping
Download app.py from dejavuwk/AITaskProject: direct link, hf CLI and curl.
- Browser
- Download file 22 kB
-
https://huggingface.co/spaces/dejavuwk/AITaskProject/resolve/main/app.py
- Command line
-
hf download hf://spaces/dejavuwk/AITaskProject/app.py
-
curl -L -o app.py https://huggingface.co/spaces/dejavuwk/AITaskProject/resolve/main/app.py
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() |