import gradio as gr from transformers import pipeline from PIL import Image import torch import os import json from openai import OpenAI # -------------------------- 模型初始化(使用轻量级视觉模型) -------------------------- device = "cuda" if torch.cuda.is_available() else "cpu" print(f"使用设备:{device}") # 使用BLIP图像描述模型(轻量级,适合Hugging Face Spaces) try: image_to_text = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base", device=0 if device == "cuda" else -1) print("模型加载成功") except Exception as e: print(f"模型加载失败: {e}") image_to_text = None # 文本评价用的大语言模型(可选,通过 OpenAI 兼容接口) LLM_API_KEY = os.getenv("OPENAI_API_KEY") LLM_BASE_URL = os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1") LLM_MODEL = os.getenv("LLM_MODEL", "gpt-4o-mini") llm_client = OpenAI(api_key=LLM_API_KEY, base_url=LLM_BASE_URL) if LLM_API_KEY else None # -------------------------- 打分核心逻辑 -------------------------- def score_photo(image, judge_personality="中立专业的评审"): """基于图像描述和评审性格对照片打分""" if image is None: return "0分", "请先上传照片" try: # 获取图像描述(英文简要描述) if image_to_text is None: return "6分", "图像描述模型未加载,无法打分" caption = image_to_text(image)[0]['generated_text'] # 使用大语言模型按照性格进行主观评价 score, formatted_reason = llm_evaluate_photo(caption, judge_personality) if score is None: # 回退到规则打分 score = calculate_score(caption, "综合评分", image) formatted_reason = generate_reason(caption, "综合评分", score) return f"{score}分", formatted_reason except Exception as e: return "6分", f"打分过程出错:{str(e)}" def llm_evaluate_photo(caption, judge_personality): """调用文本大模型,根据描述和评审性格打多维度分""" if llm_client is None: return None, None system_prompt = "你是一位会根据照片内容进行主观评分的摄影评审,可以根据不同性格风格来点评照片。" user_prompt = f"""下面是由视觉模型给出的英文简要描述,请你先在脑海中将其扩展成更细致的中文场景描述,然后以指定性格来打分和评价。 [评审性格] {judge_personality} [英文描述] {caption} 评分要求: 1. 请你先根据照片内容,自行设计3-5个最合适的评价维度(例如但不限于:颜值/美感、氛围感/情绪、清晰度/画质、构图感、故事感等),每个维度0-10的整数。 2. 再给出一个综合总分(0-10的整数)。 3. 根据评审性格,用不超过80字的中文写一段总体评价,要有明显风格差异。 4. 额外给出一段更详细的中文场景描写(100字左右),让人“脑补出照片”。 请严格只输出下面结构的 JSON: {{ "overall_score": 整数, "dimensions": [ {{"name": "维度名称1", "score": 整数, "comment": "一句中文评价"}}, {{"name": "维度名称2", "score": 整数, "comment": "一句中文评价"}}, {{"name": "维度名称3", "score": 整数, "comment": "一句中文评价"}} ], "style_comment": "不超过80字的总体评价", "detailed_description": "约100字的中文场景描写" }}""" try: response = llm_client.chat.completions.create( model=LLM_MODEL, messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}, ], temperature=0.8, ) content = response.choices[0].message.content.strip() try: data = json.loads(content) overall_score = int(data.get("overall_score", 6)) dims = data.get("dimensions", []) style_comment = str(data.get("style_comment", "")).strip() detailed_desc = str(data.get("detailed_description", "")).strip() except Exception: # 解析失败则直接返回原始内容 return None, content overall_score = max(0, min(10, overall_score)) # 组装展示文本:多维度 + 总结 + 场景描写 lines = [] lines.append(f"评审性格:{judge_personality}\n") lines.append("各维度评分:") for d in dims: name = d.get("name", "维度") sc = d.get("score", "-") cm = d.get("comment", "") lines.append(f"- {name}: {sc}/10,{cm}") if style_comment: lines.append("\n总体评价:" + style_comment) if detailed_desc: lines.append("\n脑补场景描述:" + detailed_desc) formatted = "\n".join(lines) return overall_score, formatted except Exception: return None, None def calculate_score(caption, dimension, image): """根据图像特征计算分数""" import numpy as np # 获取图像基本特征 img_array = np.array(image) # 计算亮度 brightness = np.mean(img_array) # 计算对比度 contrast = np.std(img_array) # 计算颜色丰富度 if len(img_array.shape) == 3: color_variance = np.mean([np.var(img_array[:,:,i]) for i in range(3)]) else: color_variance = np.var(img_array) # 根据维度调整评分逻辑 base_score = 5.0 if dimension == "颜值分": # 综合亮度、对比度、描述内容 if 100 < brightness < 200: base_score += 1.5 if contrast > 30: base_score += 1.0 if any(word in caption.lower() for word in ['person', 'face', 'portrait', 'smile', 'people']): base_score += 1.5 elif dimension == "氛围感分": # 关注色彩和场景 if color_variance > 500: base_score += 2.0 if any(word in caption.lower() for word in ['sunset', 'nature', 'landscape', 'sky', 'beach']): base_score += 2.0 elif dimension == "清晰度分": # 关注对比度和细节 if contrast > 40: base_score += 2.5 if brightness > 80: base_score += 1.5 elif dimension == "阳光感分": # 关注亮度 if brightness > 130: base_score += 2.5 if any(word in caption.lower() for word in ['sunny', 'bright', 'day', 'outdoor', 'light']): base_score += 1.5 # 限制在0-10分范围内 score = max(0, min(10, round(base_score, 1))) return int(score) def generate_reason(caption, dimension, score): """生成打分理由""" reasons = { "颜值分": [ f"照片整体表现{'优秀' if score >= 8 else '良好' if score >= 6 else '一般'},", f"画面主体{caption[:50]},", f"视觉呈现{'很有吸引力' if score >= 8 else '较为舒适' if score >= 6 else '还有提升空间'}。" ], "氛围感分": [ f"照片氛围{'浓厚' if score >= 8 else '适中' if score >= 6 else '较弱'},", f"场景展现了{caption[:40]},", f"情绪传达{'很到位' if score >= 8 else '比较自然' if score >= 6 else '可以加强'}。" ], "清晰度分": [ f"照片清晰度{'很高' if score >= 8 else '中等' if score >= 6 else '偏低'},", f"画面细节{'丰富' if score >= 7 else '可见'},", f"整体锐度{'优秀' if score >= 8 else '合格' if score >= 6 else '需要改进'}。" ], "阳光感分": [ f"照片光线{'充足' if score >= 8 else '适中' if score >= 6 else '不足'},", f"明亮程度{'很好' if score >= 7 else '一般'},", f"整体{'阳光明媚' if score >= 8 else '光线柔和' if score >= 6 else '略显暗淡'}。" ] } return "".join(reasons.get(dimension, reasons["颜值分"])) # -------------------------- Gradio界面 -------------------------- with gr.Blocks(title="照片解读 Photo Insights", theme=gr.themes.Soft()) as demo: gr.Markdown("# 📸 照片解读 Photo Insights") gr.Markdown("上传照片,选择解读者性格,由AI自动描述和多维度解读") with gr.Row(): with gr.Column(scale=1): image_input = gr.Image(type="pil", label="上传照片", height=300) personality_select = gr.Dropdown( choices=[ "中立专业的评审", "和蔼温柔的评审", "毒舌刻薄的评审", "电影角色:钢铁侠", "卡通角色:小黄人", "母狗的主人", ], label="解读者性格/角色", value="中立专业的评审" ) submit_btn = gr.Button("开始解读", variant="primary") with gr.Column(scale=1): score_output = gr.Textbox(label="综合评价", placeholder="等待解读...") reason_output = gr.Textbox(label="详细解读(含各维度)", placeholder="等待生成...", lines=10) submit_btn.click( fn=score_photo, inputs=[image_input, personality_select], outputs=[score_output, reason_output] ) gr.Examples( examples=[ ["https://images.unsplash.com/photo-1506794778202-cad84cf45f1d", "中立专业的评审"], ], inputs=[image_input, personality_select], ) # 启动应用 if __name__ == "__main__": demo.launch()