File size: 10,048 Bytes
630f877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29f1f02
 
630f877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40a0234
 
 
630f877
40a0234
630f877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Durable shared upload queue, one commit for many fully verified samples."""
import fcntl
import json
import os
from pathlib import Path
import re
import time
from email.utils import parsedate_to_datetime

from common import REPO,REV,atomic,sha

DEFAULT_ROOT=Path('/opt/styleedit-root-20261025/batch-upload')
FILES=['source.mp4','edited.mp4','depth.mp4','depth.json','filter.json']


class CommitDeferred(Exception):
    def __init__(self,until):
        self.until=until
        super().__init__('HF commit deferred until '+time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime(until)))


def retry_delay(error,now):
    response=getattr(error,'response',None)
    if getattr(response,'status_code',None)!=429:return None
    headers=getattr(response,'headers',{})
    retry=headers.get('Retry-After') or headers.get('retry-after')
    if retry:
        try:return max(1,float(retry))
        except ValueError:
            try:return max(1,parsedate_to_datetime(retry).timestamp()-now)
            except (ValueError,TypeError):pass
    match=re.search(r'in (?:about )?(\d+)\s*(second|minute|hour)',str(error),re.I)
    if match:return int(match[1])*{'second':1,'minute':60,'hour':3600}[match[2].lower()]
    return 3600


def guarded_commit(root,action,clock=time.time):
    """Media and metadata publishers share a durable 60-second commit budget."""
    root=Path(root);root.mkdir(parents=True,exist_ok=True)
    with (root/'commit.lock').open('a') as lock:
        try:fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
        except BlockingIOError:raise CommitDeferred(clock()+5)
        path=root/'commit-gate.json';state=json.loads(path.read_text()) if path.exists() else {}
        now=clock();until=state.get('not_before',0)
        if now<until:raise CommitDeferred(until)
        atomic(path,{'not_before':now+60,'last_attempt_at':now})
        try:return action()
        except Exception as error:
            delay=retry_delay(error,now)
            if delay is None:raise
            atomic(path,{'not_before':clock()+delay,'last_attempt_at':now,'reason':'HF HTTP 429'})
            raise CommitDeferred(clock()+delay) from None


def enqueue(root,row,directory,filtered,depth,repo):
    root=Path(root);directory=Path(directory).resolve();(root/'pending').mkdir(parents=True,exist_ok=True)
    prefix='data/'+row['style_id']+'/'+row['id']
    hashes={name:{'sha256':sha(directory/name),'bytes':(directory/name).stat().st_size} for name in FILES}
    record={k:row[k] for k in ['id','style_id','style_label','instruction','source_path','edited_path']}
    record.update(source_repo=REPO,source_revision=REV,source_video=prefix+'/source.mp4',source_depth_video=prefix+'/depth.mp4',style_video=prefix+'/edited.mp4',depth_metadata=prefix+'/depth.json',filter_metadata=prefix+'/filter.json',files=dict(hashes),filter_version='core-v1',distance=filtered['distance'],depth=depth)
    atomic(directory/'record.json',record)
    hashes['record.json']={'sha256':sha(directory/'record.json'),'bytes':(directory/'record.json').stat().st_size}
    record['files']=hashes
    job={'row':row,'record':record,'files':hashes,'directory':str(directory),'prefix':prefix,'repo':repo,'queued_at':time.time()}
    done=root/'done'/(row['id']+'.json')
    if not done.exists():atomic(root/'pending'/(row['id']+'.json'),job)
    return job


def load_recovery(row,directory):
    """Reuse completed outputs only after checking their persisted checksums."""
    directory=Path(directory)
    if not all((directory/name).exists() for name in FILES+['record.json']):return None
    record=json.loads((directory/'record.json').read_text())
    for key in ['id','style_id','source_path','edited_path','instruction']:
        if record[key]!=row[key]:raise ValueError('Retained sample identity mismatch: '+row['id'])
    for name in FILES:
        expected=record['files'][name]
        if (directory/name).stat().st_size!=expected['bytes'] or sha(directory/name)!=expected['sha256']:
            raise ValueError('Retained sample checksum mismatch: '+row['id']+'/'+name)
    filtered=json.loads((directory/'filter.json').read_text());depth=json.loads((directory/'depth.json').read_text())
    if filtered.get('status')!='keep':raise ValueError('Retained sample was not accepted')
    return filtered,depth


def wait_receipt(root,jid):
    path=Path(root)/'done'/(jid+'.json')
    while not path.exists():time.sleep(1)
    return json.loads(path.read_text())


class BatchUploader:
    def __init__(self,root,api,clock=time.time,operation_factory=None,fetch_small=None):
        self.root=Path(root);self.api=api;self.clock=clock;self.fetch_small=fetch_small
        self.root.mkdir(parents=True,exist_ok=True)
        for name in ['pending','done']:(self.root/name).mkdir(exist_ok=True)
        if operation_factory is None:
            from huggingface_hub import CommitOperationAdd
            operation_factory=CommitOperationAdd
        self.operation_factory=operation_factory

    def run_once(self,force=False):
        journal=self.root/'inflight.json'
        if journal.exists():batch=json.loads(journal.read_text());jobs=batch['jobs']
        else:
            jobs=[]
            for path in (self.root/'pending').glob('*.json'):
                if (self.root/'done'/path.name).exists():path.unlink();continue
                jobs.append(json.loads(path.read_text()))
            jobs.sort(key=lambda job:job['queued_at']);jobs=jobs[:128]
            if not jobs or (not force and len(jobs)<128 and self.clock()-jobs[0]['queued_at']<60):return 0
            gate=self.root/'commit-gate.json'
            if gate.exists():
                until=json.loads(gate.read_text()).get('not_before',0)
                if self.clock()<until:raise CommitDeferred(until)
            repo=jobs[0]['repo']
            if any(job['repo']!=repo for job in jobs):raise ValueError('Mixed destination repositories')
            operations=[]
            for job in jobs:
                for name,expected in job['files'].items():
                    path=Path(job['directory'])/name
                    if path.stat().st_size!=expected['bytes'] or sha(path)!=expected['sha256']:
                        raise ValueError('Queued local file changed: '+job['row']['id']+'/'+name)
                    operations.append(self.operation_factory(path_in_repo=job['prefix']+'/'+name,path_or_fileobj=str(path)))
            print('BATCH_COMMIT_START','samples',len(jobs),'files',len(operations),flush=True)
            commit=guarded_commit(self.root,lambda:self.api.create_commit(repo_id=repo,repo_type='dataset',operations=operations,commit_message=f'Add verified Ditto + DA3 batch: {len(jobs)} tuples'),clock=self.clock)
            batch={'commit':commit.oid,'jobs':jobs,'committed_at':self.clock()};atomic(journal,batch)
        # Persist the returned commit before verification. A restart reuses it.
        all_paths=[job['prefix']+'/'+name for job in jobs for name in job['files']]
        infos={info.path:info for info in self.api.get_paths_info(jobs[0]['repo'],all_paths,repo_type='dataset',revision=batch['commit'])}
        for job in jobs:
            for name,expected in job['files'].items():
                path=job['prefix']+'/'+name;info=infos[path]
                if info.size!=expected['bytes']:raise ValueError('Batch remote size mismatch: '+path)
                lfs=getattr(info,'lfs',None)
                if lfs:digest=lfs.sha256 if hasattr(lfs,'sha256') else lfs['sha256']
                elif self.fetch_small:digest=self.fetch_small(job['repo'],path,batch['commit'])
                else:
                    import requests
                    from huggingface_hub import hf_hub_url,get_token
                    response=requests.get(hf_hub_url(job['repo'],path,repo_type='dataset',revision=batch['commit']),headers={'Authorization':'Bearer '+get_token()},timeout=120);response.raise_for_status()
                    digest=__import__('hashlib').sha256(response.content).hexdigest()
                if digest!=expected['sha256']:raise ValueError('Batch remote SHA256 mismatch: '+path)
        # No receipt is emitted until every file in the batch passes verification.
        for job in jobs:
            receipt={'commit':batch['commit'],'verification':'all file sizes and SHA256 at immutable batch commit','record':job['record'],'seconds':self.clock()-job['queued_at'],'batch_samples':len(jobs)}
            atomic(self.root/'done'/(job['row']['id']+'.json'),receipt)
            (self.root/'pending'/(job['row']['id']+'.json')).unlink(missing_ok=True)
        journal.unlink();print('BATCH_VERIFIED',len(jobs),batch['commit'],flush=True)
        return len(jobs)


def main():
    # Set before importing the SDK: its transport flag is cached on import.
    # A failed hf_xet session can retain a poisoned task lock across retries.
    os.environ['HF_HUB_DISABLE_XET']='1'
    from huggingface_hub import HfApi
    print('UPLOAD_TRANSPORT HTTP/LFS (Xet disabled)',flush=True)
    root=Path(os.environ.get('STYLEEDIT_BATCH_ROOT',str(DEFAULT_ROOT)));root.mkdir(parents=True,exist_ok=True)
    lock=(root/'uploader.lock').open('a');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
    atomic(root/'process.json',{'pid':os.getpid()})
    uploader=BatchUploader(root,HfApi())
    while True:
        delay=5;state={'utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'state':'running'}
        try:state['new_verified']=uploader.run_once()
        except CommitDeferred as deferred:
            state.update(state='waiting_for_commit_budget',retry_at=deferred.until);delay=min(30,max(1,deferred.until-time.time()))
        except Exception as error:
            state.update(state='retrying_retained_batch',error=type(error).__name__+': '+str(error)[:240]);delay=30
            print('BATCH_RETRY',state['error'],flush=True)
        state['pending']=len(list((root/'pending').glob('*.json')));state['verified_receipts']=len(list((root/'done').glob('*.json')))
        atomic(root/'status.json',state);time.sleep(delay)


if __name__=='__main__':main()