Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,3 @@
|
|
1 |
-
import os
|
2 |
import gradio as gr
|
3 |
import numpy as np
|
4 |
import matplotlib.pyplot as plt
|
@@ -6,53 +5,70 @@ from skimage.transform import radon, iradon
|
|
6 |
from scipy.fft import fft, ifft
|
7 |
from io import BytesIO
|
8 |
import base64
|
9 |
-
|
10 |
import requests
|
|
|
11 |
|
12 |
-
# Hugging Face API
|
13 |
-
HF_TOKEN = os.environ.get("HF_TOKEN") # Fetching the token from environment variables
|
14 |
API_URL = "https://api-inference.huggingface.co/models/openai-community/gpt2-large"
|
15 |
-
|
|
|
16 |
|
17 |
def query_gpt2(payload):
|
18 |
-
|
19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
def process_and_query(image):
|
22 |
-
|
23 |
-
|
|
|
24 |
image = np.array(image)
|
25 |
|
26 |
-
#
|
27 |
theta = np.linspace(0., 180., max(image.shape), endpoint=False)
|
28 |
sinogram = radon(image, theta=theta, circle=True)
|
29 |
|
30 |
-
#
|
31 |
sinogram_text = "\n".join([", ".join(map(str, row)) for row in sinogram])
|
32 |
-
print("Sinogram
|
33 |
print(sinogram_text)
|
34 |
|
35 |
-
#
|
36 |
gpt_response = query_gpt2({"inputs": sinogram_text})
|
37 |
-
gpt_output = gpt_response.get("generated_text", "
|
38 |
|
39 |
-
#
|
40 |
fourier = fft(sinogram, axis=0)
|
41 |
|
42 |
-
#
|
43 |
freq = np.fft.fftfreq(sinogram.shape[0]).reshape(-1, 1)
|
44 |
ramp_filter = np.abs(freq)
|
45 |
filtered_fourier = fourier * ramp_filter
|
46 |
|
47 |
-
#
|
48 |
filtered_sinogram = np.real(ifft(filtered_fourier, axis=0))
|
49 |
|
50 |
-
#
|
51 |
reconstructed_image = iradon(filtered_sinogram, theta=theta, circle=True)
|
52 |
|
53 |
-
#
|
54 |
fig, axes = plt.subplots(2, 2, figsize=(10, 10))
|
55 |
-
axes[0, 0].set_title("
|
56 |
axes[0, 0].imshow(image, cmap="gray")
|
57 |
axes[0, 0].axis("off")
|
58 |
|
@@ -60,17 +76,17 @@ def process_and_query(image):
|
|
60 |
axes[0, 1].imshow(sinogram, cmap="gray", aspect="auto")
|
61 |
axes[0, 1].axis("off")
|
62 |
|
63 |
-
axes[1, 0].set_title("
|
64 |
axes[1, 0].imshow(filtered_sinogram, cmap="gray", aspect="auto")
|
65 |
axes[1, 0].axis("off")
|
66 |
|
67 |
-
axes[1, 1].set_title("
|
68 |
axes[1, 1].imshow(reconstructed_image, cmap="gray")
|
69 |
axes[1, 1].axis("off")
|
70 |
|
71 |
plt.tight_layout()
|
72 |
|
73 |
-
#
|
74 |
buf = BytesIO()
|
75 |
plt.savefig(buf, format="png")
|
76 |
buf.seek(0)
|
@@ -78,20 +94,21 @@ def process_and_query(image):
|
|
78 |
buf.close()
|
79 |
plt.close()
|
80 |
|
|
|
81 |
return f"<img src='data:image/png;base64,{encoded_image}'/>", sinogram_text, gpt_output
|
82 |
|
83 |
-
# Gradio
|
84 |
with gr.Blocks() as demo:
|
85 |
-
gr.Markdown("# Sinogram
|
86 |
-
gr.Markdown("
|
87 |
|
88 |
with gr.Row():
|
89 |
-
image_input = gr.Image(type="pil", label="
|
90 |
-
output = gr.HTML(label="
|
91 |
-
sinogram_output = gr.Textbox(label="Sinogram
|
92 |
-
gpt_output = gr.Textbox(label="GPT-2
|
93 |
|
94 |
-
process_button = gr.Button("
|
95 |
|
96 |
process_button.click(process_and_query, inputs=[image_input], outputs=[output, sinogram_output, gpt_output])
|
97 |
|
|
|
|
|
1 |
import gradio as gr
|
2 |
import numpy as np
|
3 |
import matplotlib.pyplot as plt
|
|
|
5 |
from scipy.fft import fft, ifft
|
6 |
from io import BytesIO
|
7 |
import base64
|
8 |
+
import os
|
9 |
import requests
|
10 |
+
from PIL import Image
|
11 |
|
12 |
+
# Hugging Face API ayarları
|
|
|
13 |
API_URL = "https://api-inference.huggingface.co/models/openai-community/gpt2-large"
|
14 |
+
HF_TOKEN = os.environ.get("HF_TOKEN") # Environment variable'dan token'ı al
|
15 |
+
headers = {"Authorization": f"Bearer {HF_TOKEN}"} # API anahtarını başlıkta gönder
|
16 |
|
17 |
def query_gpt2(payload):
|
18 |
+
"""Hugging Face API'sine istek gönderir ve yanıtı döner."""
|
19 |
+
try:
|
20 |
+
response = requests.post(API_URL, headers=headers, json=payload)
|
21 |
+
print("Status Code:", response.status_code) # Durum kodunu yazdır
|
22 |
+
response.raise_for_status() # Hata durumunda istisna fırlatır
|
23 |
+
response_json = response.json()
|
24 |
+
print("Response JSON:", response_json) # Yanıtın içeriğini yazdır
|
25 |
+
return response_json
|
26 |
+
except requests.exceptions.HTTPError as errh:
|
27 |
+
print(f"HTTP Error: {errh}")
|
28 |
+
except requests.exceptions.ConnectionError as errc:
|
29 |
+
print(f"Error Connecting: {errc}")
|
30 |
+
except requests.exceptions.Timeout as errt:
|
31 |
+
print(f"Timeout Error: {errt}")
|
32 |
+
except requests.exceptions.RequestException as err:
|
33 |
+
print(f"Something went wrong: {err}")
|
34 |
+
return {"generated_text": "No response from GPT-2."}
|
35 |
|
36 |
def process_and_query(image):
|
37 |
+
"""Görüntüyü işleyip GPT-2'ye gönderir."""
|
38 |
+
# Orijinal görüntüyü işleme (grayscale'e çevirme)
|
39 |
+
image = image.convert("L") # Grayscale'e çevirme
|
40 |
image = np.array(image)
|
41 |
|
42 |
+
# Sinogram oluşturma (projeksiyon verileri)
|
43 |
theta = np.linspace(0., 180., max(image.shape), endpoint=False)
|
44 |
sinogram = radon(image, theta=theta, circle=True)
|
45 |
|
46 |
+
# Sinogram verilerini metin olarak çıkarma
|
47 |
sinogram_text = "\n".join([", ".join(map(str, row)) for row in sinogram])
|
48 |
+
print("Sinogram Verileri (Text):")
|
49 |
print(sinogram_text)
|
50 |
|
51 |
+
# GPT-2 modeline sinogram verilerini gönderme
|
52 |
gpt_response = query_gpt2({"inputs": sinogram_text})
|
53 |
+
gpt_output = gpt_response.get("generated_text", "GPT-2'den yanıt alınamadı.")
|
54 |
|
55 |
+
# Projeksiyon verilerine Fourier dönüşümü uygulama
|
56 |
fourier = fft(sinogram, axis=0)
|
57 |
|
58 |
+
# Ramp filtre uygulama
|
59 |
freq = np.fft.fftfreq(sinogram.shape[0]).reshape(-1, 1)
|
60 |
ramp_filter = np.abs(freq)
|
61 |
filtered_fourier = fourier * ramp_filter
|
62 |
|
63 |
+
# Ters Fourier dönüşümü uygulama
|
64 |
filtered_sinogram = np.real(ifft(filtered_fourier, axis=0))
|
65 |
|
66 |
+
# Geri yansıtma (back projection) ile görüntü oluşturma
|
67 |
reconstructed_image = iradon(filtered_sinogram, theta=theta, circle=True)
|
68 |
|
69 |
+
# Görselleştirme için görüntüler
|
70 |
fig, axes = plt.subplots(2, 2, figsize=(10, 10))
|
71 |
+
axes[0, 0].set_title("Orijinal Görüntü")
|
72 |
axes[0, 0].imshow(image, cmap="gray")
|
73 |
axes[0, 0].axis("off")
|
74 |
|
|
|
76 |
axes[0, 1].imshow(sinogram, cmap="gray", aspect="auto")
|
77 |
axes[0, 1].axis("off")
|
78 |
|
79 |
+
axes[1, 0].set_title("Filtrelenmiş Sinogram")
|
80 |
axes[1, 0].imshow(filtered_sinogram, cmap="gray", aspect="auto")
|
81 |
axes[1, 0].axis("off")
|
82 |
|
83 |
+
axes[1, 1].set_title("Rekonstürülen Görüntü")
|
84 |
axes[1, 1].imshow(reconstructed_image, cmap="gray")
|
85 |
axes[1, 1].axis("off")
|
86 |
|
87 |
plt.tight_layout()
|
88 |
|
89 |
+
# Görüntüleri base64 formatında döndürme
|
90 |
buf = BytesIO()
|
91 |
plt.savefig(buf, format="png")
|
92 |
buf.seek(0)
|
|
|
94 |
buf.close()
|
95 |
plt.close()
|
96 |
|
97 |
+
# Görüntü ve sinogram verisini döndürme
|
98 |
return f"<img src='data:image/png;base64,{encoded_image}'/>", sinogram_text, gpt_output
|
99 |
|
100 |
+
# Gradio arayüzü tanımlama
|
101 |
with gr.Blocks() as demo:
|
102 |
+
gr.Markdown("# Sinogram Görüntüleme ve GPT-2 İşlemleri")
|
103 |
+
gr.Markdown("Bir görüntü yükleyin, sinogram verilerini işleyin ve GPT-2'ye gönderin.")
|
104 |
|
105 |
with gr.Row():
|
106 |
+
image_input = gr.Image(type="pil", label="Görüntü Yükle")
|
107 |
+
output = gr.HTML(label="Sonuç Görselleştirme")
|
108 |
+
sinogram_output = gr.Textbox(label="Sinogram Verileri (Text)")
|
109 |
+
gpt_output = gr.Textbox(label="GPT-2 Yanıtı")
|
110 |
|
111 |
+
process_button = gr.Button("İşle ve GPT-2'ye Gönder")
|
112 |
|
113 |
process_button.click(process_and_query, inputs=[image_input], outputs=[output, sinogram_output, gpt_output])
|
114 |
|