def pick_pics(stdName): # print('stdname:',stdName) pic_title_addr=os.path.join(self.ConsDir,crs_nameInput,crs_name+'.jpg') #课程的标题图 ptn='-.*-' pics_for_crs=[] for root,dirs,files in os.walk(os.path.join(self.picStdDir,stdName)): #学员的照片 for file in files: try: if re.findall(ptn,file)[0][1:-1]==crs_nameInput: PicTags=readConfig.code_to_str(iptcinfo3.IPTCInfo(os.path.join(self.picStdDir,stdName,file))) # print('tags:',PicTags) if '每周课程4+' in PicTags: pics_for_crs.append(os.path.join(self.picStdDir,stdName,file)) except: pass # print(pics_for_crs) # pics=pick_pics(stdName) if len(pics_for_crs)>3: num=4 else: num=2 # print('number:',num) # print(pics_for_crs) pics_stds_addrs=random.sample(pics_for_crs,num) # print(pics_stds_addrs) sorted_pics_stds_addrs=sortPics(pics_stds_addrs) pics=[pic_title_addr] pics.extend(sorted_pics_stds_addrs) return pics
def win_addInfo(F,TagList): if not patched: origianl_IPTCInfo = iptcinfo3.IPTCInfo iptcinfo3.IPTCInfo = patch_IPTCInfo try: info = iptcinfo3.IPTCInfo(F) info['keywords'] = TagList info.save() os.remove(F + '~') except: return
def read_pics_new(): print('正在读取照片……',end='') lst=read_excel() crs,stds=lst[0],lst[1] stdList=stds['学生姓名'].tolist() ptn_pic_src=re.compile(r'[0-9]{8}\-[a-zA-Z].*') ptn_std_name=re.compile(r'^[a-zA-Z]+[\u4e00-\u9fa5]+') infos=[] total_pics_dir=os.path.join(self.totalPics,term,term+'-体验课') # if not os.path.exists(total_pics_dir): # os.makedirs(total_pics_dir) for fileName in os.listdir(total_pics_dir): if fileName[-3:].lower()=='jpg' or fileName[-4:].lower()=='jpeg': fn=fileName.split('-') crsName=fn[1][4:] crsCode=fn[1][0:4] real_addr=os.path.join(total_pics_dir,fileName) tag=self.code_to_str(iptcinfo3.IPTCInfo(real_addr)) # print(tag) if len(tag)>0: for _tag in tag: # print(_tag) _tag.strip() _tag=_tag.replace(' ','') if _tag.lower() in list(self.para.keys()): txt_step=self.para[_tag.lower()][1] step_num=_tag.lower() step_name=self.para[_tag.lower()][0] # print(_tag) if ptn_std_name.match(_tag): # print(_tag) _tag_py=re.findall(r'[a-zA-Z]+',_tag)[0] _tag_zh=re.findall(r'[\u4e00-\u9fa5]+',_tag)[0] if _tag_zh in stdList: # print('80_tag:',_tag) std_class=stds[stds['学生姓名']==_tag_zh]['班级'].tolist()[0] std_name=_tag_zh std_py=_tag_py knlg=crs[crs['课程编号']==crsCode]['知识点'].tolist()[0] infos.append([real_addr,std_name,crsName,knlg,fileName,std_py,txt_step,std_class,step_num,step_name]) print('完成') # print('77infos:',infos) return infos
def read_fn(self): decode_tag=pics() ptn_std_name=re.compile(r'^[a-zA-Z]+[\u4e00-\u9fa5]+') for fn in os.listdir(self.input_dir): if fn[-3:].lower()=='jpg' or fn[-4:].lower()=='jpeg': img_fn=os.path.join(self.input_dir,fn) _tags=iptcinfo3.IPTCInfo(img_fn) tags=decode_tag.code_to_str(_tags) if len(tags)>0: for tag in tags: if tag in list(self.para.keys()): txt=self.para[tag] # print(txt) # self.put_step_txt(txt=txt,fn=img_fn) return txt
def iptc(self): if self._iptc is None: if settings.iptc: tags = _filter_tags(iptc3.c_datasets_r.keys(), settings.iptc.get('include'), settings.iptc.get('exclude')) else: tags = iptc3.c_datasets_r.keys() info = iptc3.IPTCInfo(self.original_path) iptc = {} for k in tags: if type(info[k]) is bytes: iptc[k] = info[k].decode('utf-8') elif type(info[k]) is list: l = [] for v in info[k]: l.append(v.decode('utf-8')) iptc[k] = l else: iptc[k] = info[k] self._iptc = iptc return self._iptc
def dispatch(self): print('将打标签的照片分配到“I:\\每周乐高课_学员\\{}”中……'.format(self.place)) stdInfos = self.read_sig(weekday=self.weekday) dictPY = stdInfos[0] stdNamelist = stdInfos[1] ptn = re.compile(r'^[a-zA-Z]+[\u4e00-\u9fa5]+') #标签为“英文+中文”的正则表达式 ptn_pic_src = '[0-9]{8}\-[a-zA-Z].*' lack_stdName = [] match_num = 0 not_match_num = 0 for fn in os.listdir( os.path.join(self.dir, self.crsDate + '-' + self.crsName)): if fn[-3:].lower() == 'jpg' or fn[-3:].lower() == 'jpeg': # if iptcinfo3.IPTCInfo(os.path.join(self.dir,fn)): tag = code_to_str( iptcinfo3.IPTCInfo( os.path.join(self.dir, self.crsDate + '-' + self.crsName, fn))) if len(tag) > 0: for _tag in tag: _tag = _tag.strip() _tag = _tag.replace(' ', '') if ptn.match(_tag): #如有“英文+中文”的标签格式,提取中文。 _tag = re.findall(r'[\u4e00-\u9fa5]+', _tag)[0] if _tag in stdNamelist: if re.match(ptn_pic_src, fn): stu_dirName = os.path.join( self.stu_dir, self.crsDate + '-' + self.crsName, fn) stu_pic_dirName = os.path.join( self.stu_dir, dictPY[_tag] + _tag) if not os.path.exists(stu_pic_dirName): os.makedirs(stu_pic_dirName) oldName = os.path.join( self.dir, self.crsDate + '-' + self.crsName, fn) newName = os.path.join(stu_pic_dirName, fn) shutil.copyfile(oldName, newName) else: oldName = os.path.join( self.dir, self.crsDate + '-' + self.crsName, fn) newName = os.path.join(stu_pic_dirName, fn) shutil.copyfile(oldName, newName) match_num += 1 else: not_match_num += 1 else: if _tag.lower( ) not in self.other_tags and _tag.lower( ) not in lack_stdName: lack_stdName.append(_tag) # print(lack_stdName) if lack_stdName: except_list = ['积分记录', '老师指导', '阅读'] drop_dup_stdnames = list( set(lack_stdName).difference(set(except_list))) print('未找到 {} 的名字,无法分配照片。'.format(','.join(drop_dup_stdnames))) if not_match_num > 0: print('已分配{0}个文件到学生姓名的文件夹中,未分配文件: {1} 个,请检查文件名是否已按标准修改。'.format( match_num, not_match_num)) else: print('已分配{0}个文件到学生姓名的文件夹中。'.format(match_num)) print('\n完成')
def run(self, client: vision.ImageAnnotatorClient, callback: Callable = None) -> None: """ Optimize, find labels for and tag the file. :param client: The ImageAnnotatorClient to be used for interacting with the Google Vision API. :param callback: Utility kwarg used for threading purposes. """ try: self.optimize( ) # Optimize the file first before sending to the Google Vision API # Open the image, read as bytes, convert to types Image image = Image.open(self.temp_file_path) bytesIO = io.BytesIO() image.save(bytesIO, format="jpeg") image.close() image = vision.types.Image(content=bytesIO.getvalue()) # Performs label detection on the image file # response = client.label_detection(image=image) # labels = [label.description for label in response.label_annotations] time.sleep(random.random() * 3) labels = [ random_characters(8) for _ in range(random.randint(4, 20)) ] logger.info("{} Keywords Identified: {}".format( len(labels), ", ".join([f'[cyan]{label}[/cyan]' for label in labels]))) # XMP sidecar file specified, write to it using XML module if self.xmp: logger.debug(f"Writing {len(labels)} tags to output XMP.") parser = XMPParser(self.input_xmp) parser.add_keywords(labels) # Generate a temporary XMP file name head, tail = os.path.split(self.input_xmp) name, ext = os.path.splitext(tail) temp_name = os.path.join(head, f'{name} temp{ext}') # Finish up processing XMP file os.rename(self.input_xmp, temp_name) # rename the original file parser.save(self.input_xmp) # save the new file shutil.copystat(temp_name, self.input_xmp) # copy file metadata over os.remove(temp_name) # remove the renamed original file logger.debug( "New XMP file saved with original file metadata. Old XMP file removed." ) # No XMP file is specified, using IPTC tagging else: logger.debug(f"Writing {len(labels)} tags to image IPTC") info = iptcinfo3.IPTCInfo( os.path.join(INPUT_PATH, self.file_name)) info["keywords"].extend(labels) info.save() # Remove the weird ghost file created by this iptc read/writer. os.remove(os.path.join(INPUT_PATH, self.file_name + "~")) # Copy dry-run # shutil.copy2(os.path.join(INPUT_PATH, self.file_name), os.path.join(OUTPUT_PATH, self.file_name)) # os.rename(os.path.join(INPUT_PATH, self.file_name), os.path.join(OUTPUT_PATH, self.file_name)) except Exception: raise finally: self._cleanup() callback()
# Copied from StackOverflow for learning purposes import iptcinfo3 import os import random import string import sys # Random string gennerator def rnd(length=3): return ''.join(random.choices(list(string.ascii_letters), k=length)) # Path to the file, open a IPTCInfo object path = os.path.join(sys.path[0], 'DSC_7960.jpg') info = iptcinfo3.IPTCInfo(path) # Show the keywords print(info['keywords']) # Add a keyword and save info['keywords'] = [rnd()] info.save() # Remove the weird ghost file created after saving os.remove(path + '~')
def __call__(self, src_path, src, buf, frames): first_frame = frames[0] if isinstance(frames, list) else frames fmt = self.format or src.format if fmt not in ('GIF', 'PNG', 'JPEG', 'WEBP'): fmt = 'JPEG' if fmt != 'GIF': # or APNG or WEBP - TODO frames = first_frame if fmt == 'GIF': if isinstance(frames, list) and len(frames) > 1: info = src.info """ { 'background': 0, 'duration': 50, 'extension': ('XMP DataXMP', 814), 'loop': 0, 'transparency': 255, 'version': 'GIF89a' } """ duration = info.get('duration', 50) save_params = dict(optimize=self.optimize, save_all=True, append_images=frames[1:], loop=info.get('loop', 0), duration=[ i.info.get('duration', duration) for i in frames ]) else: # FIXME: dlaczego jest potrzebny poniższy hack first_frame.info['duration'] = 0 save_params = dict(optimize=self.optimize) elif fmt == 'JPEG': if first_frame.mode == 'RGBA': background = Image.new('RGBA', first_frame.size, self.bgcolor) first_frame = Image.alpha_composite( background, first_frame) first_frame = first_frame.convert('RGB') save_params = dict(progressive=self.progressive, quality=self.quality, optimize=self.optimize) elif fmt == 'PNG': save_params = dict(progressive=self.progressive, quality=self.quality, optimize=self.optimize) elif fmt == 'WEBP': # lossless - If present and true, instructs the WebP writer to use lossless compression. # quality - Integer, 1-100, Defaults to 80. For lossy, 0 gives the smallest size and 100 the largest. # For lossless, this parameter is the amount of effort put into the compression: 0 is the fastest, # but gives larger files compared to the slowest, but best, 100. # method - Quality/speed trade-off (0=fast, 6=slower-better). Defaults to 0. # TODO: exif=self.metadata save_params = dict(quality=self.quality, lossless=not self.optimize, icc_procfile=False, method=(6 if self.quality == 0 else 2)) else: save_params = {} if self.metadata is True and fmt == 'JPEG' and src.format == 'JPEG': if iptcinfo3 is None: raise ImportError("Cannot import iptcinfo3 module") info = iptcinfo3.IPTCInfo(src_path) if len(info.data) >= 4: buf_tmp = BytesIO() first_frame.save(buf_tmp, fmt, **save_params) buf_tmp.seek(0) try: thumb = iptcinfo3.IPTCInfo(buf_tmp, force=True) for k, v in list(info.data.items()): thumb.data[k] = v thumb.saveToBuf(buf) return except Exception as ex: log.error("Cannot set iptc data to JPEG file: %s", ex, exc_info=ex) first_frame.save(buf, fmt, **save_params)
def write_jpgMark(): img=iptcinfo3.IPTCInfo(pic3) img['keywords']=['H001','揭东豆'] img.save()
def create_image(filename, url): # read current image with PIL with Picture.open(os.path.join(upload_path, filename)) as picture: # extract EXIF data exifdata = picture.getexif() # get exif data to fill image data in db try: # get shooting date EXIF data captured_date = exifdata.get(_TAGS_r['DateTimeOriginal']) except: captured_date = None if captured_date is not None: # decode bytes if isinstance(captured_date, bytes): captured_date = captured_date.decode() captured_date = datetime.datetime.strptime(captured_date, '%Y:%m:%d %H:%M:%S') try: # extract GEOExif data as dictionary, use GEOTAGS to get specific data img_location = exifdata.get(_TAGS_r["GSPInfo"]) except: img_location = None # get IPTC data img_iptc = iptcinfo3.IPTCInfo(os.path.join(upload_path, filename)) if not img_iptc: img_title = None img_description = None img_keywords = None else: # get name, description and keywords from IPTC data img_title = img_iptc['object name'] or img_iptc['headline'] if not img_title: img_title = filename img_title = decode_bytes(img_title) img_description = img_iptc['caption/abstract'] if not img_description: img_description = None img_description = decode_bytes(img_description) keywords_list = img_iptc['keywords'] img_keywords = '' if not keywords_list: img_keywords = None else: for keyword in keywords_list: keyword = decode_bytes(keyword) img_keywords = img_keywords + ', ' + keyword # get current user data user_id = current_user.id for group in current_user.groups: if group is not None: group_id = group.id break # create image object image = Image(name=img_title, filename=filename, url=url, description=img_description, keywords=img_keywords, captured_on=captured_date, location=img_location, owner_id=user_id, group_id=group_id) # get parent album parent_id = session.get("current_album") if parent_id is not None: image.parent_id = int(parent_id) try: # save image to database db.session.add(image) db.session.commit() except: abort(400) return True
""" What: IPTCINFO3 example Author: James Campbell Date: 5 July 2019 """ import iptcinfo3 try: info = iptcinfo3.IPTCInfo('assets/guy881.jpg', inp_charset="cp1250", out_charset='cp1250', force=True) print('-------IPTC DATA FOUND-------') print(info.packedIIMData()) for k, v in info._data.items(): print(f"KEY: {k} VALUE: {str(v)}") # info['city'] = '#magistræde #🇩🇰' # info.save() except Exception as e: if str(e) != "No IPTC data found.": raise
import iptcinfo3 except ModuleNotFoundError as e: print(e, "pip3 install this!") exit(1) # Open image file for reading (binary mode) path_name = 'assets/cat.jpg' f = sys.argv[1] # check to see if image in command line f = open(f, 'rb') # Return Exif tags tags = exifread.process_file(f) totaltags = len(tags) print('-------EXIF DATA FOUND-------') print(f"Total EXIF tags found: {totaltags}") for tag in tags.keys(): print("Key: %s, value %s" % (tag, tags[tag])) print('-----------------END EXIF DATA-------') im = Image.open(sys.argv[1]) try: info = iptcinfo3.IPTCInfo(sys.argv[1]) print('-------IPTC DATA FOUND-------') for k, v in info._data.items(): print(k, v) info['city'] = '#magistræde #🇩🇰' info.save() except Exception as e: if str(e) != "No IPTC data found.": raise