Spaces:
Running
Running
nifleisch commited on
Commit ·
94e1698
1
Parent(s): 7db7792
fix: fix several erros
Browse filesFiles changed (15)
- .env.exampleAdded+4
- .gitignore+4
- README.md+8
- api/__init__.py+16-1
- api/fal.py+1-1
- api/pruna_dev.pyAdded+49
- benchmark/hps.py+2-2
- benchmark/metrics/__init__.py+3-2
- benchmark/metrics/arniqa.py+3-2
- benchmark/metrics/clip_iqa.py+1-1
- benchmark/metrics/vqa.py+4-9
- environment.ymlAdded+27
- evaluate.py+15-7
- pyproject.tomlDeleted-22
- uv.lockDeleted
1234FIREWORKS_API_TOKEN=your_fireworks_api_token_hereREPLICATE_API_TOKEN=your_replicate_api_token_hereFAL_KEY=your_fal_key_hereTOGETHER_API_KEY=your_together_api_key_here171 unmodified lines172173174171 unmodified lines# PyPI configuration file.pypirc171 unmodified lines172173174175176177178171 unmodified lines# PyPI configuration file.pypircevaluation_results/images/hf_cache/
12# InferBench-Evaluate the quality and efficiency of image gen api's.12345678910# InferBench-Evaluate the quality and efficiency of image gen api's.Install dependencies with conda like that:conda env create -f environment.ymlCreate .env file with all the files you will need.python sample.py replicate draw_bench genai_bench geneval hps parti
1234567891011121313 unmodified lines272829303132from typing import Optional, Typefrom api.baseline import BaselineAPIfrom api.fireworks import FireworksAPIfrom api.flux import FluxAPIfrom api.pruna import PrunaAPIfrom api.replicate import ReplicateAPIfrom api.together import TogetherAPIfrom api.fal import FalAPIdef create_api(api_type: str) -> FluxAPI:"""Factory function to create API instances.13 unmodified linesRaises:ValueError: If an invalid API type is provided"""if api_type.startswith("pruna_"):speed_mode = api_type[6:] # Remove "pruna_" prefixreturn PrunaAPI(speed_mode)123456789101112131415161718192021222324252613 unmodified lines4041424344454647from typing import Typefrom api.baseline import BaselineAPIfrom api.fireworks import FireworksAPIfrom api.flux import FluxAPIfrom api.pruna import PrunaAPIfrom api.pruna_dev import PrunaDevAPIfrom api.replicate import ReplicateAPIfrom api.together import TogetherAPIfrom api.fal import FalAPI__all__ = ['create_api','FluxAPI','BaselineAPI','FireworksAPI','PrunaAPI','ReplicateAPI','TogetherAPI','FalAPI','PrunaDevAPI',]def create_api(api_type: str) -> FluxAPI:"""Factory function to create API instances.13 unmodified linesRaises:ValueError: If an invalid API type is provided"""if api_type == "pruna_dev":return PrunaDevAPI()if api_type.startswith("pruna_"):speed_mode = api_type[6:] # Remove "pruna_" prefixreturn PrunaAPI(speed_mode)
6 unmodified lines789101112136 unmodified linesimport requestsfrom PIL import Imagefrom flux import FluxAPIclass FalAPI(FluxAPI):6 unmodified lines789101112136 unmodified linesimport requestsfrom PIL import Imagefrom api.flux import FluxAPIclass FalAPI(FluxAPI):
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import osimport timefrom pathlib import Pathfrom typing import Any
from dotenv import load_dotenvimport replicate
from api.flux import FluxAPI
class PrunaDevAPI(FluxAPI): def __init__(self): load_dotenv() self._api_key = os.getenv("REPLICATE_API_TOKEN") if not self._api_key: raise ValueError("REPLICATE_API_TOKEN not found in environment variables")
@property def name(self) -> str: return "pruna_dev"
def generate_image(self, prompt: str, save_path: Path) -> float: start_time = time.time() result = replicate.run( "prunaai/flux.1-dev:938a4eb31a87d65fb7b23fc300fb5b7ab88a36844bb26e54e1d1dec7acf4eefe", input={ "seed": 0, "prompt": prompt, "guidance": 3.5, "num_outputs": 1, "aspect_ratio": "1:1", "output_format": "png", "speed_mode": "Juiced 🔥 (default)", "num_inference_steps": 28, }, ) end_time = time.time() if result: self._save_image_from_result(result, save_path) else: raise Exception("No result returned from Replicate API") return end_time - start_time
def _save_image_from_result(self, result: Any, save_path: Path): save_path.parent.mkdir(parents=True, exist_ok=True) with open(save_path, "wb") as f: f.write(result.read())14 unmodified lines151617181920214 unmodified lines2627282930313214 unmodified linesself._size = 0for file in self.hps_prompt_files:category = file.replace('.json', '')with open(os.path.join('datasets/hps', file), 'r') as f:prompts = json.load(f)for i, prompt in enumerate(prompts):if i == 100:4 unmodified linesdef __iter__(self) -> Iterator[Tuple[str, Path]]:for filename, prompt in self.prompts.items():yield prompt, filename@propertydef name(self) -> str:14 unmodified lines151617181920214 unmodified lines2627282930313214 unmodified linesself._size = 0for file in self.hps_prompt_files:category = file.replace('.json', '')with open(os.path.join('downloads/hps', file), 'r') as f:prompts = json.load(f)for i, prompt in enumerate(prompts):if i == 100:4 unmodified linesdef __iter__(self) -> Iterator[Tuple[str, Path]]:for filename, prompt in self.prompts.items():yield prompt, Path(filename)@propertydef name(self) -> str:
5 unmodified lines67891011127 unmodified lines202122232425267 unmodified lines3435363738395 unmodified linesfrom benchmark.metrics.image_reward import ImageRewardMetricfrom benchmark.metrics.sharpness import SharpnessMetricfrom benchmark.metrics.vqa import VQAMetricdef create_metric(metric_type: str) -> Type[ARNIQAMetric | CLIPMetric | CLIPIQAMetric | ImageRewardMetric | SharpnessMetric | VQAMetric]:"""7 unmodified lines- "image_reward"- "sharpness"- "vqa"Returns:An instance of the requested metric implementation7 unmodified lines"image_reward": ImageRewardMetric,"sharpness": SharpnessMetric,"vqa": VQAMetric,}if metric_type not in metric_map:5 unmodified lines67891011127 unmodified lines202122232425267 unmodified lines343536373839405 unmodified linesfrom benchmark.metrics.image_reward import ImageRewardMetricfrom benchmark.metrics.sharpness import SharpnessMetricfrom benchmark.metrics.vqa import VQAMetricfrom benchmark.metrics.hps import HPSMetricdef create_metric(metric_type: str) -> Type[ARNIQAMetric | CLIPMetric | CLIPIQAMetric | ImageRewardMetric | SharpnessMetric | VQAMetric]:"""7 unmodified lines- "image_reward"- "sharpness"- "vqa"- "hps"Returns:An instance of the requested metric implementation7 unmodified lines"image_reward": ImageRewardMetric,"sharpness": SharpnessMetric,"vqa": VQAMetric,"hps": HPSMetric,}if metric_type not in metric_map:
7 unmodified lines8910111213141516171819202122232425267 unmodified linesclass ARNIQAMetric:def __init__(self):self.metric = ARNIQA(regressor_dataset="koniq10k",reduction="mean",normalize=True,autocast=False)@propertydef name(self) -> str:return "arniqa"def compute_score(self, image: Image.Image, prompt: str) -> Dict[str, float]:image_tensor = torch.from_numpy(np.array(image)).permute(2, 0, 1).float() / 255.0image_tensor = image_tensor.unsqueeze(0)score = self.metric(image_tensor)return {"arniqa": score.item()}7 unmodified lines891011121314151617181920212223242526277 unmodified linesclass ARNIQAMetric:def __init__(self):self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")self.metric = ARNIQA(regressor_dataset="koniq10k",reduction="mean",normalize=True,autocast=False)self.metric.to(self.device)@propertydef name(self) -> str:return "arniqa"def compute_score(self, image: Image.Image, prompt: str) -> Dict[str, float]:image_tensor = torch.from_numpy(np.array(image)).permute(2, 0, 1).float() / 255.0image_tensor = image_tensor.unsqueeze(0).to(self.device)score = self.metric(image_tensor)return {"arniqa": score.item()}
11 unmodified lines1213141516171811 unmodified linesself.metric = CLIPImageQualityAssessment(model_name_or_path="clip_iqa",data_range=255.0,prompts=["quality"])self.metric.to(self.device)11 unmodified lines1213141516171811 unmodified linesself.metric = CLIPImageQualityAssessment(model_name_or_path="clip_iqa",data_range=255.0,prompts=("quality",))self.metric.to(self.device)
1234567895 unmodified lines1516171819202122232425import osimport tempfilefrom typing import Dictimport t2v_metricsfrom PIL import Imageclass VQAMetric:def __init__(self):5 unmodified linesdef compute_score(self,image: Image.Image,prompt: str,) -> Dict[str, float]:with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:image.save(tmp.name)score = self.metric(images=[tmp.name], texts=[prompt])os.unlink(tmp.name)return {"vqa_score": score[0][0].item()}12345675 unmodified lines1314151617181920from pathlib import Pathfrom typing import Dictimport t2v_metricsclass VQAMetric:def __init__(self):5 unmodified linesdef compute_score(self,image_path: Path,prompt: str,) -> Dict[str, float]:score = self.metric(images=[str(image_path)], texts=[prompt])return {"vqa": score[0][0].item()}
123456789101112131415161718192021222324252627name: inferbenchchannels: - conda-forge - defaultsdependencies: - python=3.12 - numpy - opencv - pillow - python-dotenv - requests - tqdm - pip - pip: - datasets>=3.5.0 - fal-client>=0.5.9 - hpsv2>=1.2.0 - huggingface-hub>=0.30.2 - image-reward>=1.5 - replicate>=1.0.4 - t2v-metrics>=1.2 - together>=1.5.5 - torch>=2.7.0 - torchmetrics>=1.7.1 - clip - diffusers<=0.31 - piq>=0.8.01 unmodified line23456789101127 unmodified lines39404142434445464748495051525354555657585960616263646566671 unmodified lineimport jsonfrom pathlib import Pathfrom typing import Dictfrom benchmark import create_benchmarkfrom benchmark.metrics import create_metricfrom PIL import Imagedef evaluate_benchmark(benchmark_type: str, api_type: str, images_dir: Path = Path("images")) -> Dict:27 unmodified lines"api": api_type,"benchmark": benchmark_type,"metrics": {metric: 0.0 for metric in benchmark.metrics},"avg_inference_time": 0.0,"total_images": len(metadata)}for entry in metadata:image_path = benchmark_dir / entry["filepath"]if not image_path.exists():continueimage = Image.open(image_path)for metric_type, metric in metrics.items():try:score = metric.compute_score(image, entry["prompt"])results["metrics"][metric_type] += score[metric_type]except Exception as e:print(f"Error computing {metric_type} for {image_path}: {str(e)}")results["avg_inference_time"] += entry["inference_time"]for metric in results["metrics"]:results["metrics"][metric] /= len(metadata)results["avg_inference_time"] /= len(metadata)return results1 unmodified line23456789101112131415161727 unmodified lines454647484950515253545556575859606162636465666768697071727374751 unmodified lineimport jsonfrom pathlib import Pathfrom typing import Dictimport warningsfrom benchmark import create_benchmarkfrom benchmark.metrics import create_metricimport numpy as npfrom PIL import Imagefrom tqdm import tqdmwarnings.filterwarnings("ignore", category=FutureWarning)def evaluate_benchmark(benchmark_type: str, api_type: str, images_dir: Path = Path("images")) -> Dict:27 unmodified lines"api": api_type,"benchmark": benchmark_type,"metrics": {metric: 0.0 for metric in benchmark.metrics},"total_images": len(metadata)}inference_times = []for entry in tqdm(metadata):image_path = benchmark_dir / entry["filepath"]if not image_path.exists():continuefor metric_type, metric in metrics.items():try:if metric_type == "vqa":score = metric.compute_score(image_path, entry["prompt"])else:image = Image.open(image_path)score = metric.compute_score(image, entry["prompt"])results["metrics"][metric_type] += score[metric_type]except Exception as e:print(f"Error computing {metric_type} for {image_path}: {str(e)}")inference_times.append(entry["inference_time"])for metric in results["metrics"]:results["metrics"][metric] /= len(metadata)results["median_inference_time"] = np.median(inference_times).item()return results
12345678910111213141516171819202122[project]name = "inferbench"version = "0.1.0"requires-python = ">=3.12"dependencies = [ "datasets>=3.5.0", "fal-client>=0.5.9", "hpsv2>=1.2.0", "huggingface-hub>=0.30.2", "image-reward>=1.5", "numpy>=2.2.5", "opencv-python>=4.11.0.86", "pillow>=11.2.1", "python-dotenv>=1.1.0", "replicate>=1.0.4", "requests>=2.32.3", "t2v-metrics>=1.2", "together>=1.5.5", "torch>=2.7.0", "torchmetrics>=1.7.1", "tqdm>=4.67.1",].env.exampleAdded+4
.gitignore+4
README.md+8
api/__init__.py+16-1
api/fal.py+1-1
api/pruna_dev.pyAdded+49
benchmark/hps.py+2-2
benchmark/metrics/__init__.py+3-2
benchmark/metrics/arniqa.py+3-2
benchmark/metrics/clip_iqa.py+1-1
benchmark/metrics/vqa.py+4-9
environment.ymlAdded+27
evaluate.py+15-7
pyproject.tomlDeleted-22
uv.lockDeleted