Update app.py
Browse files
app.py
CHANGED
|
@@ -19,14 +19,52 @@ from torchvision import models, transforms
|
|
| 19 |
import matplotlib.pyplot as plt
|
| 20 |
import seaborn as sns
|
| 21 |
from collections import Counter
|
|
|
|
|
|
|
| 22 |
|
| 23 |
# Set up logging
|
| 24 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
# Load engagement_metrics.json (your company's data)
|
| 32 |
logging.info("Loading your company's engagement metrics...")
|
|
@@ -121,33 +159,30 @@ logging.info("Combining your company's data and competitor data for model traini
|
|
| 121 |
combined_df = pd.concat([your_df, competitor_df], ignore_index=True)
|
| 122 |
|
| 123 |
# Handle missing or invalid image URLs
|
| 124 |
-
combined_df['image_url'] = combined_df['image_url'].fillna('')
|
| 125 |
|
| 126 |
-
#
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
# Skip empty or invalid URLs
|
| 131 |
-
return ""
|
| 132 |
-
try:
|
| 133 |
-
response = requests.get(image_url)
|
| 134 |
-
response.raise_for_status() # Raise an error for bad responses (4xx, 5xx)
|
| 135 |
-
image = Image.open(BytesIO(response.content))
|
| 136 |
-
text = pytesseract.image_to_string(image)
|
| 137 |
-
return text
|
| 138 |
-
except Exception as e:
|
| 139 |
-
logging.error(f"Error extracting text from image: {e}")
|
| 140 |
-
return ""
|
| 141 |
|
| 142 |
-
|
| 143 |
-
combined_df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
# Analyze image content using a pre-trained model
|
| 146 |
def analyze_image(image_url):
|
| 147 |
"""Analyze image content using a pre-trained model."""
|
| 148 |
if not image_url or not isinstance(image_url, str) or not image_url.startswith(('http://', 'https://')):
|
| 149 |
-
# Skip
|
| 150 |
-
return None
|
| 151 |
try:
|
| 152 |
response = requests.get(image_url)
|
| 153 |
response.raise_for_status() # Raise an error for bad responses (4xx, 5xx)
|
|
|
|
| 19 |
import matplotlib.pyplot as plt
|
| 20 |
import seaborn as sns
|
| 21 |
from collections import Counter
|
| 22 |
+
import os
|
| 23 |
+
import pickle
|
| 24 |
|
| 25 |
# Set up logging
|
| 26 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 27 |
|
| 28 |
+
# Cache file to store extracted text
|
| 29 |
+
CACHE_FILE = "image_text_cache.pkl"
|
| 30 |
+
|
| 31 |
+
# Load cache if it exists
|
| 32 |
+
if os.path.exists(CACHE_FILE):
|
| 33 |
+
with open(CACHE_FILE, "rb") as f:
|
| 34 |
+
cache = pickle.load(f)
|
| 35 |
+
else:
|
| 36 |
+
cache = {}
|
| 37 |
+
|
| 38 |
+
# Function to resize images
|
| 39 |
+
def resize_image(image, max_size=(800, 600)):
|
| 40 |
+
"""Resize an image to the specified maximum size."""
|
| 41 |
+
image.thumbnail(max_size)
|
| 42 |
+
return image
|
| 43 |
+
|
| 44 |
+
# Function to extract text from an image
|
| 45 |
+
def extract_text_from_image(image_url):
|
| 46 |
+
"""Extract text from an image using OCR."""
|
| 47 |
+
if image_url in cache:
|
| 48 |
+
return cache[image_url] # Return cached text if available
|
| 49 |
+
if not image_url or not isinstance(image_url, str) or not image_url.startswith(('http://', 'https://')):
|
| 50 |
+
return "" # Skip invalid URLs
|
| 51 |
+
try:
|
| 52 |
+
response = requests.get(image_url)
|
| 53 |
+
response.raise_for_status() # Raise an error for bad responses (4xx, 5xx)
|
| 54 |
+
image = Image.open(BytesIO(response.content))
|
| 55 |
+
image = resize_image(image) # Resize the image
|
| 56 |
+
text = pytesseract.image_to_string(image)
|
| 57 |
+
cache[image_url] = text # Cache the extracted text
|
| 58 |
+
return text
|
| 59 |
+
except Exception as e:
|
| 60 |
+
logging.error(f"Error extracting text from image: {e}")
|
| 61 |
+
return ""
|
| 62 |
+
|
| 63 |
+
# Function to process new images
|
| 64 |
+
def process_new_images(new_images):
|
| 65 |
+
"""Process new images and return a DataFrame with extracted text."""
|
| 66 |
+
new_images['image_text'] = new_images['image_url'].apply(extract_text_from_image)
|
| 67 |
+
return new_images
|
| 68 |
|
| 69 |
# Load engagement_metrics.json (your company's data)
|
| 70 |
logging.info("Loading your company's engagement metrics...")
|
|
|
|
| 159 |
combined_df = pd.concat([your_df, competitor_df], ignore_index=True)
|
| 160 |
|
| 161 |
# Handle missing or invalid image URLs
|
| 162 |
+
combined_df['image_url'] = combined_df['image_url'].fillna('')
|
| 163 |
|
| 164 |
+
# Process only new images (those not in the cache)
|
| 165 |
+
logging.info("Extracting text from new images...")
|
| 166 |
+
new_images = combined_df[~combined_df['image_url'].isin(cache.keys())]
|
| 167 |
+
new_images = process_new_images(new_images)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
+
# Update the combined DataFrame with extracted text
|
| 170 |
+
combined_df.update(new_images)
|
| 171 |
+
|
| 172 |
+
# Save the updated dataset
|
| 173 |
+
combined_df.to_csv('data_with_extracted_text.csv', index=False)
|
| 174 |
+
|
| 175 |
+
# Save the cache
|
| 176 |
+
with open(CACHE_FILE, "wb") as f:
|
| 177 |
+
pickle.dump(cache, f)
|
| 178 |
+
|
| 179 |
+
logging.info("Incremental processing complete!")
|
| 180 |
|
| 181 |
# Analyze image content using a pre-trained model
|
| 182 |
def analyze_image(image_url):
|
| 183 |
"""Analyze image content using a pre-trained model."""
|
| 184 |
if not image_url or not isinstance(image_url, str) or not image_url.startswith(('http://', 'https://')):
|
| 185 |
+
return None # Skip invalid URLs
|
|
|
|
| 186 |
try:
|
| 187 |
response = requests.get(image_url)
|
| 188 |
response.raise_for_status() # Raise an error for bad responses (4xx, 5xx)
|