| import os |
| import torch |
| from PIL import Image |
| from transformers import AutoModel, AutoTokenizer |
| from tqdm import tqdm |
|
|
| MODEL_PATH = 'openbmb/MiniCPM-o-2_6' |
|
|
|
|
| model = AutoModel.from_pretrained( |
| MODEL_PATH, |
| trust_remote_code=True, |
| cache_dir=".", |
| attn_implementation='sdpa', |
| torch_dtype=torch.bfloat16, |
| init_vision=True, |
| init_audio=True, |
| init_tts=True |
| ).eval().cuda() |
|
|
| tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, cache_dir=".",trust_remote_code=True) |
|
|
|
|
| model.init_tts() |
|
|
|
|
| question = ( |
| '''You are an agricultural expert. Analyze the image and answer the following questions: |
| |
| 1. Identify the type of fruit or crop shown in the image. |
| 2. Determine its current growth stage. (Options: unripe, mature, pest-damaged, rotten) |
| 3. Recommend the farmer’s next action. (Options: keep for further growth, try to recover it, discard it) |
| 4. Evaluate the consumer’s willingness to consume this fruit, from 1 (very unlikely) to 100 (very likely). |
| |
| Please respond in the following format, and do not include explanations: |
| |
| - Type: [Fruit/Crop Name] |
| - Growth Stage: [unripe / mature / pest-damaged / rotten] |
| - Recommendation: [keep for further growth / pick it / try to recover it / discard it] |
| - Consumer Score: [1-100] |
| ''' |
| ) |
|
|
| image_root = "../data" |
| output_root = "result" |
| os.makedirs(output_root, exist_ok=True) |
|
|
|
|
| for fruit in os.listdir(image_root): |
| fruit_path = os.path.join(image_root, fruit) |
| if not os.path.isdir(fruit_path): |
| continue |
|
|
| for subfolder in os.listdir(fruit_path): |
| subfolder_path = os.path.join(fruit_path, subfolder) |
| if not os.path.isdir(subfolder_path): |
| continue |
|
|
| output_file = os.path.join(output_root, f"{fruit}_{subfolder}.txt") |
| image_files = [f for f in os.listdir(subfolder_path) if f.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp', '.webp'))] |
|
|
| with open(output_file, "w", encoding="utf-8") as out_file: |
| for filename in tqdm(image_files, desc=f"Processing {fruit}/{subfolder}"): |
| image_path = os.path.join(subfolder_path, filename) |
| try: |
| image = Image.open(image_path).convert('RGB') |
| msgs = [{'role': 'user', 'content': [image, question]}] |
|
|
| response = model.chat( |
| msgs=msgs, |
| tokenizer=tokenizer |
| ) |
|
|
| out_file.write(f"{'=' * 25} IMAGE START {'=' * 25}\n") |
| out_file.write(f"🖼️ Image Name: {filename}\n\n") |
| out_file.write("📝 Answer:\n" + response.strip() + "\n") |
| out_file.write(f"{'=' * 25} IMAGE END {'=' * 25}\n\n") |
| except Exception as e: |
| out_file.write(f"{'=' * 25} IMAGE START {'=' * 25}\n") |
| out_file.write(f"🖼️ Image Name: {filename}\n") |
| out_file.write("❌ ERROR:\n" + str(e) + "\n") |
| out_file.write(f"{'=' * 25} IMAGE END {'=' * 25}\n\n") |
| print(f"[ERROR] {fruit}/{subfolder}/{filename}: {e}") |