| import os |
| from PIL import Image |
| from mantis.models.mllava import chat_mllava, MLlavaProcessor, LlavaForConditionalGeneration |
|
|
| |
|
|
|
|
| model_path = "TIGER-Lab/Mantis-8B-siglip-llama3" |
| processor = MLlavaProcessor.from_pretrained(model_path, cache_dir=".") |
| model = LlavaForConditionalGeneration.from_pretrained( |
| model_path, |
| cache_dir=".", |
| device_map="cuda", |
| torch_dtype="bfloat16", |
| attn_implementation=None |
| ) |
|
|
|
|
| generation_kwargs = { |
| "max_new_tokens": 1024, |
| "num_beams": 1, |
| "do_sample": False |
| } |
|
|
| question = ( |
| ''' |
| 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: |
| 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] |
| ''' |
| ) |
|
|
| root_folder = "../data/" |
| output_root = "result" |
| os.makedirs(output_root, exist_ok=True) |
|
|
| for fruit in os.listdir(root_folder): |
| fruit_path = os.path.join(root_folder, 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 |
|
|
| image_files = [f for f in os.listdir(subfolder_path) if f.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp'))] |
| if not image_files: |
| continue |
|
|
| output_file = os.path.join(output_root, f"{fruit}_{subfolder}.txt") |
| |
| with open(output_file, "w", encoding="utf-8") as fout: |
| for image_file in image_files: |
| image_path = os.path.join(subfolder_path, image_file) |
| try: |
| image = Image.open(image_path).convert("RGB") |
|
|
| response, history = chat_mllava( |
| question, [image], model, processor, **generation_kwargs |
| ) |
|
|
| print(f"{image_file} ✅ -> {response}") |
| fout.write(f"{'=' * 25} IMAGE START {'=' * 25}\n") |
| fout.write(f"🖼️ Image Name: {image_file}\n") |
| fout.write(f"📝 Answer:\n{response.strip()}\n") |
| fout.write(f"{'=' * 25} IMAGE END {'=' * 25}\n\n") |
|
|
| except Exception as e: |
| print(f"[ERROR] {fruit}/{subfolder}/{image_file} -> {e}") |
| fout.write(f"{'=' * 25} IMAGE START {'=' * 25}\n") |
| fout.write(f"🖼️ Image Name: {image_file}\n") |
| fout.write(f"❌ ERROR:\n{str(e)}\n") |
| fout.write(f"{'=' * 25} IMAGE END {'=' * 25}\n\n") |
|
|