Prajwall11 commited on
Commit
d0f0dbd
·
verified ·
1 Parent(s): a73667a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -151
app.py CHANGED
@@ -1,154 +1,103 @@
 
 
 
 
1
  import gradio as gr
2
- import numpy as np
3
- import random
4
-
5
- # import spaces #[uncomment to use ZeroGPU]
6
- from diffusers import DiffusionPipeline
7
- import torch
8
-
9
- device = "cuda" if torch.cuda.is_available() else "cpu"
10
- model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
11
-
12
- if torch.cuda.is_available():
13
- torch_dtype = torch.float16
14
- else:
15
- torch_dtype = torch.float32
16
-
17
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
18
- pipe = pipe.to(device)
19
-
20
- MAX_SEED = np.iinfo(np.int32).max
21
- MAX_IMAGE_SIZE = 1024
22
-
23
-
24
- # @spaces.GPU #[uncomment to use ZeroGPU]
25
- def infer(
26
- prompt,
27
- negative_prompt,
28
- seed,
29
- randomize_seed,
30
- width,
31
- height,
32
- guidance_scale,
33
- num_inference_steps,
34
- progress=gr.Progress(track_tqdm=True),
35
- ):
36
- if randomize_seed:
37
- seed = random.randint(0, MAX_SEED)
38
-
39
- generator = torch.Generator().manual_seed(seed)
40
-
41
- image = pipe(
42
- prompt=prompt,
43
- negative_prompt=negative_prompt,
44
- guidance_scale=guidance_scale,
45
- num_inference_steps=num_inference_steps,
46
- width=width,
47
- height=height,
48
- generator=generator,
49
- ).images[0]
50
-
51
- return image, seed
52
-
53
-
54
- examples = [
55
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
56
- "An astronaut riding a green horse",
57
- "A delicious ceviche cheesecake slice",
58
- ]
59
-
60
- css = """
61
- #col-container {
62
- margin: 0 auto;
63
- max-width: 640px;
64
- }
65
- """
66
-
67
- with gr.Blocks(css=css) as demo:
68
- with gr.Column(elem_id="col-container"):
69
- gr.Markdown(" # Text-to-Image Gradio Template")
70
-
71
- with gr.Row():
72
- prompt = gr.Text(
73
- label="Prompt",
74
- show_label=False,
75
- max_lines=1,
76
- placeholder="Enter your prompt",
77
- container=False,
78
- )
79
-
80
- run_button = gr.Button("Run", scale=0, variant="primary")
81
-
82
- result = gr.Image(label="Result", show_label=False)
83
-
84
- with gr.Accordion("Advanced Settings", open=False):
85
- negative_prompt = gr.Text(
86
- label="Negative prompt",
87
- max_lines=1,
88
- placeholder="Enter a negative prompt",
89
- visible=False,
90
- )
91
-
92
- seed = gr.Slider(
93
- label="Seed",
94
- minimum=0,
95
- maximum=MAX_SEED,
96
- step=1,
97
- value=0,
98
- )
99
-
100
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
101
-
102
- with gr.Row():
103
- width = gr.Slider(
104
- label="Width",
105
- minimum=256,
106
- maximum=MAX_IMAGE_SIZE,
107
- step=32,
108
- value=1024, # Replace with defaults that work for your model
109
- )
110
-
111
- height = gr.Slider(
112
- label="Height",
113
- minimum=256,
114
- maximum=MAX_IMAGE_SIZE,
115
- step=32,
116
- value=1024, # Replace with defaults that work for your model
117
- )
118
-
119
- with gr.Row():
120
- guidance_scale = gr.Slider(
121
- label="Guidance scale",
122
- minimum=0.0,
123
- maximum=10.0,
124
- step=0.1,
125
- value=0.0, # Replace with defaults that work for your model
126
- )
127
-
128
- num_inference_steps = gr.Slider(
129
- label="Number of inference steps",
130
- minimum=1,
131
- maximum=50,
132
- step=1,
133
- value=2, # Replace with defaults that work for your model
134
- )
135
-
136
- gr.Examples(examples=examples, inputs=[prompt])
137
- gr.on(
138
- triggers=[run_button.click, prompt.submit],
139
- fn=infer,
140
- inputs=[
141
- prompt,
142
- negative_prompt,
143
- seed,
144
- randomize_seed,
145
- width,
146
- height,
147
- guidance_scale,
148
- num_inference_steps,
149
- ],
150
- outputs=[result, seed],
151
- )
152
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  if __name__ == "__main__":
154
- demo.launch()
 
1
+ from PIL import Image
2
+ from transformers import ViTFeatureExtractor, ViTForImageClassification
3
+ import warnings
4
+ import requests
5
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ warnings.filterwarnings('ignore')
8
+
9
+ # Load the pre-trained Vision Transformer model and feature extractor
10
+ model_name = "google/vit-base-patch16-224"
11
+ feature_extractor = ViTFeatureExtractor.from_pretrained(model_name)
12
+ model = ViTForImageClassification.from_pretrained(model_name)
13
+
14
+ # API key for the nutrition information
15
+ api_key = 'XshljGSwf/pq3GcgBdHtOg==G9X2wnPqW5c6vp0F'
16
+
17
+ def identify_image(image_path):
18
+ """Identify the food item in the image."""
19
+ image = Image.open(image_path)
20
+ inputs = feature_extractor(images=image, return_tensors="pt")
21
+ outputs = model(**inputs)
22
+ logits = outputs.logits
23
+ predicted_class_idx = logits.argmax(-1).item()
24
+ predicted_label = model.config.id2label[predicted_class_idx]
25
+ food_name = predicted_label.split(',')[0]
26
+ return food_name
27
+
28
+ def get_calories(food_name):
29
+ """Get the calorie information of the identified food item."""
30
+ api_url = 'https://api.api-ninjas.com/v1/nutrition?query={}'.format(food_name)
31
+ response = requests.get(api_url, headers={'X-Api-Key': api_key})
32
+ if response.status_code == requests.codes.ok:
33
+ nutrition_info = response.json()
34
+ else:
35
+ nutrition_info = {"Error": response.status_code, "Message": response.text}
36
+ return nutrition_info
37
+
38
+ def format_nutrition_info(nutrition_info):
39
+ """Format the nutritional information into an HTML table."""
40
+ if "Error" in nutrition_info:
41
+ return f"Error: {nutrition_info['Error']} - {nutrition_info['Message']}"
42
+
43
+ if len(nutrition_info) == 0:
44
+ return "No nutritional information found."
45
+
46
+ nutrition_data = nutrition_info[0]
47
+ table = f"""
48
+ <table border="1" style="width: 100%; border-collapse: collapse;">
49
+ <tr><th colspan="4" style="text-align: center;"><b>Nutrition Facts</b></th></tr>
50
+ <tr><td colspan="4" style="text-align: center;"><b>Food Name: {nutrition_data['name']}</b></td></tr>
51
+ <tr>
52
+ <td style="text-align: left;"><b>Calories</b></td><td style="text-align: right;">{nutrition_data['calories']}</td>
53
+ <td style="text-align: left;"><b>Serving Size (g)</b></td><td style="text-align: right;">{nutrition_data['serving_size_g']}</td>
54
+ </tr>
55
+ <tr>
56
+ <td style="text-align: left;"><b>Total Fat (g)</b></td><td style="text-align: right;">{nutrition_data['fat_total_g']}</td>
57
+ <td style="text-align: left;"><b>Saturated Fat (g)</b></td><td style="text-align: right;">{nutrition_data['fat_saturated_g']}</td>
58
+ </tr>
59
+ <tr>
60
+ <td style="text-align: left;"><b>Protein (g)</b></td><td style="text-align: right;">{nutrition_data['protein_g']}</td>
61
+ <td style="text-align: left;"><b>Sodium (mg)</b></td><td style="text-align: right;">{nutrition_data['sodium_mg']}</td>
62
+ </tr>
63
+ <tr>
64
+ <td style="text-align: left;"><b>Potassium (mg)</b></td><td style="text-align: right;">{nutrition_data['potassium_mg']}</td>
65
+ <td style="text-align: left;"><b>Cholesterol (mg)</b></td><td style="text-align: right;">{nutrition_data['cholesterol_mg']}</td>
66
+ </tr>
67
+ <tr>
68
+ <td style="text-align: left;"><b>Total Carbohydrates (g)</b></td><td style="text-align: right;">{nutrition_data['carbohydrates_total_g']}</td>
69
+ <td style="text-align: left;"><b>Fiber (g)</b></td><td style="text-align: right;">{nutrition_data['fiber_g']}</td>
70
+ </tr>
71
+ <tr>
72
+ <td style="text-align: left;"><b>Sugar (g)</b></td><td style="text-align: right;">{nutrition_data['sugar_g']}</td>
73
+ <td></td><td></td>
74
+ </tr>
75
+ </table>
76
+ """
77
+ return table
78
+
79
+ def main_process(image_path):
80
+ """Identify the food item and fetch its calorie information."""
81
+ food_name = identify_image(image_path)
82
+ nutrition_info = get_calories(food_name)
83
+ formatted_nutrition_info = format_nutrition_info(nutrition_info)
84
+ return formatted_nutrition_info
85
+
86
+ # Define the Gradio interface
87
+ def gradio_interface(image):
88
+ formatted_nutrition_info = main_process(image)
89
+ return formatted_nutrition_info
90
+
91
+ # Create the Gradio UI
92
+ iface = gr.Interface(
93
+ fn=gradio_interface,
94
+ inputs=gr.Image(type="filepath"),
95
+ outputs="html",
96
+ title="Food Identification and Nutrition Info",
97
+ description="Upload an image of food to get nutritional information.",
98
+ allow_flagging="never" # Disable flagging
99
+ )
100
+
101
+ # Launch the Gradio app
102
  if __name__ == "__main__":
103
+ iface.launch()