tugrulkaya commited on
Commit
79a2fa0
·
verified ·
1 Parent(s): 2859d4c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +3 -122
app.py CHANGED
@@ -31,7 +31,7 @@ def load_model():
31
  adapter_id = "tugrulkaya/GeoQwen-VL-2B-EuroSAT"
32
 
33
  if DEVICE == "cuda":
34
- # GPU Varsa: 4-bit quantization ile yükle
35
  bnb_config = BitsAndBytesConfig(
36
  load_in_4bit=True,
37
  bnb_4bit_quant_type="nf4",
@@ -45,124 +45,5 @@ def load_model():
45
  _attn_implementation="flash_attention_2"
46
  )
47
  else:
48
- # CPU (Hugging Face Spaces Free Tier):
49
- # 'offload_folder' ve 'device_map="auto"' KALDIRILDI.
50
- # 2B model RAM'e (16GB) rahatça sığar. Diske taşımak hataya sebep oluyor.
51
- base_model = Qwen2VLForConditionalGeneration.from_pretrained(
52
- model_id,
53
- torch_dtype=torch.float32,
54
- trust_remote_code=True,
55
- _attn_implementation="eager" # CPU için kritik
56
- ).to("cpu")
57
-
58
- # LoRA Adaptörünü Yükle
59
- # Burada da offload_folder argümanını kaldırdık
60
- model = PeftModel.from_pretrained(
61
- base_model,
62
- adapter_id
63
- )
64
-
65
- # Modeli değerlendirme moduna al
66
- model.eval()
67
-
68
- processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
69
- print("✅ Model başarıyla yüklendi!")
70
- return model, processor
71
-
72
- except Exception as e:
73
- print(f"❌ Model yükleme hatası detaylı: {str(e)}")
74
- # Hatayı gradio ekranında da görmek için tekrar fırlatabiliriz ama
75
- # uygulamanın çökmemesi için loglayıp devam ediyoruz.
76
- raise e
77
-
78
- # Global değişkenler
79
- model, processor = load_model()
80
-
81
- # --- SINIFLANDIRMA FONKSİYONU ---
82
- def classify_satellite_image(image):
83
- if image is None:
84
- return "⚠️ Lütfen bir görüntü yükleyin.", ""
85
-
86
- try:
87
- if not isinstance(image, Image.Image):
88
- image = Image.fromarray(image)
89
-
90
- # Prompt
91
- messages = [
92
- {
93
- "role": "user",
94
- "content": [
95
- {"type": "image", "image": image},
96
- {"type": "text", "text": "Classify this satellite image into one of the following land use categories: AnnualCrop, Forest, HerbaceousVegetation, Highway, Industrial, Pasture, PermanentCrop, Residential, River, SeaLake. Only respond with the category name."}
97
- ]
98
- }
99
- ]
100
-
101
- # Girdileri hazırla
102
- text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
103
- image_inputs, video_inputs = process_vision_info(messages)
104
-
105
- inputs = processor(
106
- text=[text],
107
- images=image_inputs,
108
- videos=video_inputs,
109
- padding=True,
110
- return_tensors="pt"
111
- ).to(model.device)
112
-
113
- # Tahmin
114
- with torch.no_grad():
115
- generated_ids = model.generate(
116
- **inputs,
117
- max_new_tokens=32,
118
- do_sample=False
119
- )
120
-
121
- # Çıktıyı işle
122
- generated_ids_trimmed = [
123
- out_ids[len(in_ids):]
124
- for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
125
- ]
126
-
127
- result = processor.batch_decode(
128
- generated_ids_trimmed,
129
- skip_special_tokens=True,
130
- clean_up_tokenization_spaces=False
131
- )[0].strip()
132
-
133
- # Temizlik
134
- clean_result = result.replace('.', '').strip()
135
-
136
- if clean_result in CLASS_DESCRIPTIONS:
137
- formatted_result = CLASS_DESCRIPTIONS[clean_result]
138
- display_text = f"### 🎯 Sonuç: {formatted_result}\n\n**Orijinal Sınıf:** `{clean_result}`"
139
- else:
140
- display_text = f"### 🤖 Model Çıktısı: {result}"
141
-
142
- return display_text, result
143
-
144
- except Exception as e:
145
- return f"❌ Hata: {str(e)}", "Error"
146
-
147
- # --- ARAYÜZ ---
148
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
149
-
150
- gr.HTML("""
151
- <div style="text-align: center; padding: 20px;">
152
- <h1 style="font-size: 2.5em; margin-bottom: 10px;">🛰️ GeoQwen-VL-2B-EuroSAT</h1>
153
- <p style="font-size: 1.2em; color: #666;">Uydu Görüntülerinden Arazi Sınıflandırma</p>
154
- </div>
155
- """)
156
-
157
- with gr.Row():
158
- with gr.Column():
159
- input_image = gr.Image(label="Uydu Görüntüsü Yükle", type="pil", height=300)
160
- classify_btn = gr.Button("🔍 Sınıflandır", variant="primary", size="lg")
161
-
162
- with gr.Column():
163
- output_text = gr.Markdown(label="Analiz Sonucu", value="*Görüntü bekleniyor...*")
164
- output_raw = gr.Textbox(label="Ham Çıktı", interactive=False)
165
-
166
- gr.HTML("""
167
- <div style="margin-top: 20px; padding: 10px; background-color: #f0f0f0; border-radius: 5px;">
168
- <p style="margin:0"><b>Not:</b>
 
31
  adapter_id = "tugrulkaya/GeoQwen-VL-2B-EuroSAT"
32
 
33
  if DEVICE == "cuda":
34
+ # GPU Varsa: 4-bit quantization
35
  bnb_config = BitsAndBytesConfig(
36
  load_in_4bit=True,
37
  bnb_4bit_quant_type="nf4",
 
45
  _attn_implementation="flash_attention_2"
46
  )
47
  else:
48
+ # CPU (Hugging Face Spaces Free Tier)
49
+ # Offload ve device_map="auto" KAL