Spaces:
Build error
Build error
Update app.py
Browse files3 unmodified lines4567891011121314151617181920217 unmodified lines2930313233343536373839404142434445464748495051522 unmodified lines5556575859606162636465666768697071727374757677787980818283848586878889909192939495969798997 unmodified lines1071081091101111121131141151161171181191203 unmodified lines1241251261271281291301311321334 unmodified lines1381391401411421431441451461471481491501511521531544 unmodified lines15916016116216316416516616716816913 unmodified lines1831841851861871881896 unmodified lines1961971981992002012022 unmodified lines2052062072082092102112122132142152162172182192202212222232242252262271 unmodified line2292302312322332342355 unmodified lines24124224324424524624712 unmodified lines2602612622632642652663 unmodified lines2702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364373 unmodified linesimport jsonimport tempfileimport zipfilefrom pathlib import Pathfrom huggingface_hub import hf_hub_downloadfrom llama_cpp import Llamafrom llama_cpp.llama_chat_format import Qwen2VLChatHandlerimport base64from PIL import Imagefrom io import BytesIO# КонстантыREPO_ID = "mradermacher/VisualQuality-R1-7B-GGUF"MODEL_FILE = "VisualQuality-R1-7B.Q4_K_M.gguf" # 4.68 GB - баланс качества/размераMMPROJ_FILE = "VisualQuality-R1-7B.mmproj-Q8_0.gguf" # 853 MB# ПромптыPROMPT = (7 unmodified lines# Глобальные переменныеllm = Nonechat_handler = Nonedef download_models():"""Скачивание моделей из HuggingFace"""print("Downloading model files...")model_path = hf_hub_download(repo_id=REPO_ID,filename=MODEL_FILE,resume_download=True,)print(f"Model downloaded: {model_path}")mmproj_path = hf_hub_download(repo_id=REPO_ID,filename=MMPROJ_FILE,resume_download=True,)print(f"MMProj downloaded: {mmproj_path}")2 unmodified linesdef load_model():"""Загрузка модели"""global llm, chat_handlerif llm is not None:returnmodel_path, mmproj_path = download_models()print("Loading model into memory...")# Создаём chat handler для Qwen2-VLchat_handler = Qwen2VLChatHandler(clip_model_path=mmproj_path,verbose=False)# Загружаем основную модельllm = Llama(model_path=model_path,chat_handler=chat_handler,n_ctx=4096, # Контекстn_threads=4, # Потоки CPUn_gpu_layers=0, # CPU onlyverbose=False,)print("Model loaded successfully!")def image_to_base64_uri(image):"""Конвертация PIL Image в data URI"""if image is None:return None# Конвертируем в RGB если нужноif image.mode != "RGB":image = image.convert("RGB")# Сжимаем для ускоренияmax_size = 1024if max(image.size) > max_size:ratio = max_size / max(image.size)new_size = (int(image.size[0] * ratio), int(image.size[1] * ratio))7 unmodified linesdef extract_score(text):"""Извлечение оценки из текста"""try:model_output_matches = re.findall(r'<answer>(.*?)</answer>', text, re.DOTALL)if model_output_matches:model_answer = model_output_matches[-1].strip()else:model_answer = text.strip()score_match = re.search(r'\d+(\.\d+)?', model_answer)if score_match:score = float(score_match.group())return min(max(score, 1.0), 5.0)3 unmodified linesdef extract_thinking(text):"""Извлечение процесса мышления"""thinking_matches = re.findall(r'<think>(.*?)</think>', text, re.DOTALL)if thinking_matches:return thinking_matches[-1].strip()return ""4 unmodified linesload_model()if image is None:yield "❌ Please upload an image first.", "", ""return# Выбор шаблонаtemplate = QUESTION_TEMPLATE_THINKING if use_thinking else QUESTION_TEMPLATE_NO_THINKINGprompt_text = template.format(Question=PROMPT)# Конвертируем изображениеimage_uri = image_to_base64_uri(image)# Формируем сообщениеmessages = [{"role": "user",4 unmodified lines}]# Генерация со стримингомgenerated_text = ""yield "⏳ Processing...", "", "*Analyzing image...*"try:response = llm.create_chat_completion(messages=messages,13 unmodified linesscore = extract_score(generated_text)if score is not None:score_display = f"⭐ **Quality Score: {score:.2f} / 5.00**"else:score_display = "*Analyzing...*"6 unmodified linesif final_score is not None:score_display = f"⭐ **Quality Score: {final_score:.2f} / 5.00**\n\n📊 **For Leaderboard:** `{final_score:.2f}`"else:score_display = "❌ Could not extract score. Please try again."yield generated_text, final_thinking, score_display2 unmodified linesdef process_batch(files, use_thinking=True, progress=gr.Progress()):"""Обработка пакета изображений"""global llmload_model()if not files:return "❌ No files uploaded", Noneresults = []template = QUESTION_TEMPLATE_THINKING if use_thinking else QUESTION_TEMPLATE_NO_THINKINGprompt_text = template.format(Question=PROMPT)progress(0, desc="Starting batch processing...")for i, file in enumerate(files):try:# Загружаем изображениеif hasattr(file, 'name'):image = Image.open(file.name)filename = os.path.basename(file.name)1 unmodified lineimage = Image.open(file)filename = f"image_{i+1}.jpg"image_uri = image_to_base64_uri(image)messages = [{5 unmodified lines}]# Генерацияresponse = llm.create_chat_completion(messages=messages,max_tokens=2048 if use_thinking else 256,12 unmodified lines"raw_output": generated_text})progress((i + 1) / len(files), desc=f"Processed {i+1}/{len(files)}: {filename}")except Exception as e:results.append({3 unmodified lines"raw_output": str(e)})# Создаём файлы результатовwith tempfile.TemporaryDirectory() as tmpdir:# Текстовый файл для лидербордаleaderboard_file = os.path.join(tmpdir, "leaderboard_scores.txt")with open(leaderboard_file, "w") as f:for r in results:score_str = f"{r['score']:.2f}" if isinstance(r['score'], float) else r['score']f.write(f"{r['filename']}\t{score_str}\n")# JSON с полными результатамиjson_file = os.path.join(tmpdir, "full_results.json")with open(json_file, "w") as f:json.dump(results, f, indent=2, ensure_ascii=False)# CSV файлcsv_file = os.path.join(tmpdir, "scores.csv")with open(csv_file, "w") as f:f.write("filename,score\n")for r in results:score_str = f"{r['score']:.2f}" if isinstance(r['score'], float) else r['score']f.write(f"{r['filename']},{score_str}\n")# Создаём ZIP архивzip_path = os.path.join(tmpdir, "results.zip")with zipfile.ZipFile(zip_path, 'w') as zipf:zipf.write(leaderboard_file, "leaderboard_scores.txt")zipf.write(json_file, "full_results.json")zipf.write(csv_file, "scores.csv")# Копируем ZIP во временную папку, которая не удалитсяfinal_zip = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")with open(zip_path, 'rb') as f:final_zip.write(f.read())final_zip.close()# Формируем summaryvalid_scores = [r['score'] for r in results if isinstance(r['score'], float)]summary = f"""## ✅ Batch Processing Complete!**Processed:** {len(results)} images**Successful:** {len(valid_scores)} images**Failed:** {len(results) - len(valid_scores)} images### Statistics:- **Average Score:** {sum(valid_scores)/len(valid_scores):.2f} (if valid scores exist)- **Min Score:** {min(valid_scores):.2f if valid_scores else 'N/A'}- **Max Score:** {max(valid_scores):.2f if valid_scores else 'N/A'}### Preview (first 10):| Filename | Score ||----------|-------|""" + "\n".join([f"| {r['filename']} | {r['score']:.2f if isinstance(r['score'], float) else r['score']} |" for r in results[:10]])return summary, final_zip.namedef create_interface():"""Создание интерфейса Gradio"""with gr.Blocks(title="VisualQuality-R1 GGUF") as demo:gr.Markdown("""# 🎨 VisualQuality-R1: Image Quality Assessment (GGUF/CPU)**Reasoning-Induced Image Quality Assessment** | Running on CPU with GGUF quantization[](https://arxiv.org/abs/2505.14460)[](https://huggingface.co/TianheWu/VisualQuality-R1-7B)> ⚠️ **CPU Mode**: Processing is slower but works without GPU. ~30-60 sec per image.""")with gr.Tabs():# Вкладка для одного изображенияwith gr.TabItem("📷 Single Image"):with gr.Row():with gr.Column(scale=1):image_input = gr.Image(label="Upload Image",type="pil",height=350)thinking_checkbox = gr.Checkbox(label="🧠 Enable Thinking Mode",value=True)submit_btn = gr.Button("🔍 Analyze Quality",variant="primary",size="lg")with gr.Column(scale=1):score_output = gr.Markdown(value="*Upload an image to see the score*")thinking_output = gr.Textbox(label="🧠 Thinking", lines=6, interactive=False)raw_output = gr.Textbox(label="📝 Full Output", lines=8, interactive=False)submit_btn.click(fn=score_single_image,inputs=[image_input, thinking_checkbox],outputs=[raw_output, thinking_output, score_output],)# Вкладка для batch processingwith gr.TabItem("📁 Batch Processing (1000+ images)"):gr.Markdown("""### Batch Processing for LeaderboardUpload multiple images (ZIP or individual files) to process them all at once.Results will be saved in a format ready for leaderboard submission.""")with gr.Row():with gr.Column():batch_files = gr.File(label="Upload Images",file_count="multiple",file_types=["image"],)batch_thinking = gr.Checkbox(label="🧠 Enable Thinking Mode (slower but more detailed)",value=False # По умолчанию выключено для скорости)batch_btn = gr.Button("🚀 Process All Images",variant="primary",size="lg")with gr.Column():batch_summary = gr.Markdown(value="*Upload images and click Process*")batch_download = gr.File(label="📥 Download Results")batch_btn.click(fn=process_batch,inputs=[batch_files, batch_thinking],outputs=[batch_summary, batch_download],)gr.Markdown("""---### 📊 Score Scale| Score | Quality ||-------|---------|| 1.0 | Very poor || 2.0 | Poor || 3.0 | Fair || 4.0 | Good || 5.0 | Excellent |""")return demoif __name__ == "__main__":demo = create_interface()demo.queue(max_size=5)demo.launch(show_error=True,ssr_mode=False,)3 unmodified lines45678910111213141516171819207 unmodified lines2829303132333435363738394041424344454647482 unmodified lines515253545556575859606162636465666768697071727374757677787980818283848586878889909192937 unmodified lines1011021031041051061071081091101111121131143 unmodified lines1181191201211221231241251261274 unmodified lines1321331341351361371381391401411421431444 unmodified lines14915015115215315415515615713 unmodified lines1711721731741751761776 unmodified lines1841851861871881891902 unmodified lines1931941951961971981992002012022032042052062072082092102112121 unmodified line2142152162172182192205 unmodified lines22622722822923023112 unmodified lines2442452462472482492503 unmodified lines2542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563 unmodified linesimport jsonimport tempfileimport zipfilefrom huggingface_hub import hf_hub_downloadfrom llama_cpp import Llamafrom llama_cpp.llama_chat_format import Llava15ChatHandlerimport base64from PIL import Imagefrom io import BytesIO# КонстантыREPO_ID = "mradermacher/VisualQuality-R1-7B-GGUF"MODEL_FILE = "VisualQuality-R1-7B.Q4_K_M.gguf"MMPROJ_FILE = "VisualQuality-R1-7B.mmproj-Q8_0.gguf"# ПромптыPROMPT = (7 unmodified lines# Глобальные переменныеllm = Nonedef download_models():"""Скачивание моделей"""print("Downloading model files...")model_path = hf_hub_download(repo_id=REPO_ID,filename=MODEL_FILE,)print(f"Model downloaded: {model_path}")mmproj_path = hf_hub_download(repo_id=REPO_ID,filename=MMPROJ_FILE,)print(f"MMProj downloaded: {mmproj_path}")2 unmodified linesdef load_model():"""Загрузка модели"""global llmif llm is not None:returnmodel_path, mmproj_path = download_models()print("Loading model...")# Используем Llava15ChatHandler для vision моделейchat_handler = Llava15ChatHandler(clip_model_path=mmproj_path,verbose=False)llm = Llama(model_path=model_path,chat_handler=chat_handler,n_ctx=4096,n_threads=4,n_gpu_layers=0,verbose=False,)print("Model loaded!")def image_to_data_uri(image):"""Конвертация PIL Image в data URI"""if image is None:return Noneif image.mode != "RGB":image = image.convert("RGB")# Сжимаем для ускоренияmax_size = 768if max(image.size) > max_size:ratio = max_size / max(image.size)new_size = (int(image.size[0] * ratio), int(image.size[1] * ratio))7 unmodified linesdef extract_score(text):"""Извлечение оценки"""try:matches = re.findall(r'<answer>(.*?)</answer>', text, re.DOTALL)if matches:answer = matches[-1].strip()else:answer = text.strip()score_match = re.search(r'\d+(\.\d+)?', answer)if score_match:score = float(score_match.group())return min(max(score, 1.0), 5.0)3 unmodified linesdef extract_thinking(text):"""Извлечение мышления"""matches = re.findall(r'<think>(.*?)</think>', text, re.DOTALL)if matches:return matches[-1].strip()return ""4 unmodified linesload_model()if image is None:return "❌ Upload an image first", "", ""template = QUESTION_TEMPLATE_THINKING if use_thinking else QUESTION_TEMPLATE_NO_THINKINGprompt_text = template.format(Question=PROMPT)image_uri = image_to_data_uri(image)messages = [{"role": "user",4 unmodified lines}]# Стримингgenerated_text = ""try:response = llm.create_chat_completion(messages=messages,13 unmodified linesscore = extract_score(generated_text)if score is not None:score_display = f"⭐ **Score: {score:.2f} / 5.00**"else:score_display = "*Analyzing...*"6 unmodified linesif final_score is not None:score_display = f"⭐ **Quality Score: {final_score:.2f} / 5.00**\n\n📊 **For Leaderboard:** `{final_score:.2f}`"else:score_display = "❌ Could not extract score"yield generated_text, final_thinking, score_display2 unmodified linesdef process_batch(files, use_thinking=True, progress=gr.Progress()):"""Batch processing"""global llmload_model()if not files:return "❌ No files", Noneresults = []template = QUESTION_TEMPLATE_THINKING if use_thinking else QUESTION_TEMPLATE_NO_THINKINGprompt_text = template.format(Question=PROMPT)for i, file in enumerate(files):try:if hasattr(file, 'name'):image = Image.open(file.name)filename = os.path.basename(file.name)1 unmodified lineimage = Image.open(file)filename = f"image_{i+1}.jpg"image_uri = image_to_data_uri(image)messages = [{5 unmodified lines}]response = llm.create_chat_completion(messages=messages,max_tokens=2048 if use_thinking else 256,12 unmodified lines"raw_output": generated_text})progress((i + 1) / len(files), desc=f"Processed {i+1}/{len(files)}")except Exception as e:results.append({3 unmodified lines"raw_output": str(e)})# Создаём файлыwith tempfile.TemporaryDirectory() as tmpdir:# TXT для лидербордаtxt_file = os.path.join(tmpdir, "scores.txt")with open(txt_file, "w") as f:for r in results:score_str = f"{r['score']:.2f}" if isinstance(r['score'], float) else str(r['score'])f.write(f"{r['filename']}\t{score_str}\n")# JSONjson_file = os.path.join(tmpdir, "results.json")with open(json_file, "w") as f:json.dump(results, f, indent=2, ensure_ascii=False)# CSVcsv_file = os.path.join(tmpdir, "scores.csv")with open(csv_file, "w") as f:f.write("filename,score\n")for r in results:score_str = f"{r['score']:.2f}" if isinstance(r['score'], float) else str(r['score'])f.write(f"{r['filename']},{score_str}\n")# ZIPzip_path = os.path.join(tmpdir, "results.zip")with zipfile.ZipFile(zip_path, 'w') as zipf:zipf.write(txt_file, "scores.txt")zipf.write(json_file, "results.json")zipf.write(csv_file, "scores.csv")# Копируемfinal_zip = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")with open(zip_path, 'rb') as f:final_zip.write(f.read())final_zip.close()# Summaryvalid_scores = [r['score'] for r in results if isinstance(r['score'], float)]avg = sum(valid_scores)/len(valid_scores) if valid_scores else 0summary = f"""## ✅ Done!**Processed:** {len(results)} images**Success:** {len(valid_scores)}**Failed:** {len(results) - len(valid_scores)}**Average:** {avg:.2f}**Min:** {min(valid_scores):.2f if valid_scores else 'N/A'}**Max:** {max(valid_scores):.2f if valid_scores else 'N/A'}### Preview:| File | Score ||------|-------|""" + "\n".join([f"| {r['filename'][:30]} | {r['score']:.2f if isinstance(r['score'], float) else r['score']} |" for r in results[:10]])return summary, final_zip.name# Интерфейсwith gr.Blocks(title="VisualQuality-R1") as demo:gr.Markdown("""# 🎨 VisualQuality-R1 (GGUF/CPU)Image Quality Assessment | CPU Mode (~30-60 sec/image)[](https://arxiv.org/abs/2505.14460)""")with gr.Tabs():with gr.TabItem("📷 Single Image"):with gr.Row():with gr.Column():img_input = gr.Image(label="Upload", type="pil", height=350)thinking_cb = gr.Checkbox(label="🧠 Thinking Mode", value=True)btn = gr.Button("🔍 Analyze", variant="primary", size="lg")with gr.Column():score_out = gr.Markdown("*Upload image*")thinking_out = gr.Textbox(label="Thinking", lines=6)raw_out = gr.Textbox(label="Output", lines=8)btn.click(score_single_image, [img_input, thinking_cb], [raw_out, thinking_out, score_out])with gr.TabItem("📁 Batch (1000+ images)"):gr.Markdown("### Upload multiple images for leaderboard submission")with gr.Row():with gr.Column():batch_files = gr.File(label="Images", file_count="multiple", file_types=["image"])batch_thinking = gr.Checkbox(label="🧠 Thinking (slower)", value=False)batch_btn = gr.Button("🚀 Process All", variant="primary", size="lg")with gr.Column():batch_summary = gr.Markdown("*Upload and click Process*")batch_download = gr.File(label="📥 Download Results")batch_btn.click(process_batch, [batch_files, batch_thinking], [batch_summary, batch_download])if __name__ == "__main__":demo.queue(max_size=5)demo.launch(server_name="0.0.0.0", server_port=7860)
app.py+95-176