help me write the function fr the background task completion and also check out the code for things that could lead to the behaviour i have:
from fastapi import FastAPI, Request, BackgroundTasks
from fastapi.responses import StreamingResponse
import uvicorn
from fastapi.templating import Jinja2Templates
import numpy as np
import cv2
from paddleocr import PaddleOCR
import requests
import datetime
import logging
import os
import csv
import time
templates = Jinja2Templates(directory="templates")
logging.basicConfig(
filename="app.log", # For file output, set to None if you only want console output
level=logging.INFO, # For catching all info level or higher messages
format="%(asctime)s - %(levelname)s - %(message)s",
)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
console_handler.setFormatter(formatter)
logging.getLogger().addHandler(console_handler)
app = FastAPI()
Paddleocr supports Chinese, English, French, German, Korean and Japanese.
You can set the parameter lang as ch, en, fr, german, korean, japan
to switch the language model in order.
ocr = PaddleOCR(
use_angle_cls=False,
lang="en",
) # need to run only once to download and load model into memory
def check_for_dot(frame, previous_frame, threshold):
# Convert the image to grayscale
current_frame = frame.copy()
# Check if the two images have the same size
if current_frame.shape != previous_frame.shape:
print("The two images have different sizes")
return "Not found"
# Check if the two images have the same number of channels
if current_frame.ndim != previous_frame.ndim:
print("The two images have a different number of channels")
return "Not found"
# Crop the images to the specified area
# Check if the cropped frames are not empty
if current_frame.size != 0 and previous_frame.size != 0:
# Convert the image to grayscale
current_frame = cv2.cvtColor(current_frame, cv2.COLOR_BGR2GRAY)
previous_frame = cv2.cvtColor(previous_frame, cv2.COLOR_BGR2GRAY)
else:
print("The cropped frames are empty")
# Compute the absolute difference between the current frame and the previous frame
frame_diff = cv2.absdiff(current_frame, previous_frame)
# Convert the difference image to binary
_, binary_diff = cv2.threshold(frame_diff, 10, 255, cv2.THRESH_BINARY)
# Count the number of black pixels
num_black_pixels = cv2.countNonZero(binary_diff)
# Check if the number of black pixels is above the threshold
if num_black_pixels > threshold:
print("Found it")
return "Found it"
else:
print("Not found")
return "Not found"
x, y, w, h = 100, 100, 200, 200
threshold = 400
Paths to template images
window_template_path = "shot2Target.png"
dot_template_path = "dottemplate.png"
Load template images
window_template = cv2.imread(window_template_path, 0)
dot_template = cv2.imread(dot_template_path, 0)
Global variable to store the server’s response
SERVER_RESPONSE = None
Image processing function
def process_images():
global SERVER_RESPONSE
logging.info("The process started")
# url = "http://10.30.227.207:8088z/shot.jpg"
frame = cv2.imread("shot(3).jpg")
# url = "http://192.168.229.55:8080/shot.jpg"
window_match_threshold = 0.75 # Adjust according to your needs
dot_match_threshold = 0.75 # Adjust according to your needs
while True:
# Fetch the frame
# img_resp = requests.get(url)
# img_arr = np.frombuffer(img_resp.content, np.uint8)
# frame = cv2.imdecode(img_arr, -1)
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Perform template matching for the window
res = cv2.matchTemplate(gray_frame, window_template, cv2.TM_CCOEFF_NORMED)
loc = np.where(res >= window_match_threshold)
if len(loc[0]) > 0:
logging.info("the window matches")
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = max_loc
bottom_right = (
top_left[0] + window_template.shape[1],
top_left[1] + window_template.shape[0],
)
window_roi = frame[
top_left[1] : bottom_right[1], top_left[0] : bottom_right[0]
]
# Convert the ROI to grayscale for dot detection
gray_window_roi = cv2.cvtColor(window_roi, cv2.COLOR_BGR2GRAY)
thresholded_image = cv2.adaptiveThreshold(
gray_window_roi,
255,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY,
11,
11,
)
blurred_image = cv2.GaussianBlur(thresholded_image, (3, 3), 0)
# Perform template matching for the dot within the window ROI
dot_res = cv2.matchTemplate(
blurred_image, dot_template, cv2.TM_CCOEFF_NORMED
)
dot_loc = np.where(dot_res >= dot_match_threshold)
if len(dot_loc[0]) > 0:
logging.info("The dot matches")
# A dot is found, perform the necessary tasks
# Save the image
if not os.path.isdir("images"):
os.mkdir("images")
image_path = "images/captured_image.jpg"
cv2.imwrite(image_path, blurred_image)
# Check the saved image
result = check_picture(image_path) # Assuming this function is defined
SERVER_RESPONSE = result
# You can break or continue depending on your process
# break
# If you decide to continue, you can throttle the loop
# time.sleep(1) # Pause the loop for a given time (in seconds)
# Throttle the loop to avoid excessive CPU usage
time.sleep(0.5)
@app.post("/start_processing")
async def start_processing(background_tasks: BackgroundTasks):
logging.info("Received start_processing request")
background_tasks.add_task(process_images)
return {"message": "Image processing started"}
@app.get("/get_response")
async def get_response():
return {"response": SERVER_RESPONSE}
async def generate_audio():
global SERVER_RESPONSE
clenedUpResponse = SERVER_RESPONSE
already_exists = False
while float(clenedUpResponse) > 30.0:
clenedUpResponse = float(clenedUpResponse) / 10
if "." in SERVER_RESPONSE:
clenedUpResponse = SERVER_RESPONSE.replace(".", " dot ")
with open("last_number", "r+") as f:
lars = (
f.readline().strip()
) # Read the first line and remove any leading/trailing whitespaces
if lars == clenedUpResponse:
already_exists = True
else:
f.seek(0) # Move the cursor to the beginning of the file
f.write(str(clenedUpResponse))
f.truncate() # Remove any content after the new value
url = "https://api.mandrillai.tech/v1/audio/tts"
headers = {
"Authorization": "Bearer md-tqjJTsIZujWmBUzZZxBXyLsBllHgEFFBydEGhhrRRiScqIKM"
}
data = {
"voice_id": "piTKgcLEGmPE4e6mEKli",
"text": f"Added {clenedUpResponse} Kilo",
}
try:
if already_exists:
return
else:
response = requests.post(url, json=data, headers=headers)
response.raise_for_status() # If the request was successful, no Exception will be raised
with open("audio.mp3", "wb") as f:
f.write(response.content)
return response
except requests.exceptions.HTTPError as errh:
print("HTTP Error:", errh)
except requests.exceptions.ConnectionError as errc:
print("Error Connecting:", errc)
except requests.exceptions.Timeout as errt:
print("Timeout Error:", errt)
except requests.exceptions.RequestException as err:
print("Something went wrong", err)
@app.get("/audio")
async def main():
global SERVER_RESPONSE
# Generate the audio here
with open("audio.mp3", "rb") as f:
audio_data = f.read()
update_csv(SERVER_RESPONSE)
return StreamingResponse(iter([audio_data]), media_type="audio/mp3")
@app.get("/video")
async def video_endpoint(request: Request):
return templates.TemplateResponse("video.html", {"request": request})
def check_picture(img_path):
result = ocr.ocr(img_path, cls=False)
new_result = []
for idx in range(len(result)):
res = result[idx]
for line in res:
print(line[1][0])
if line[1][0].replace(".", "", 1).isdigit() or line[0][1] == ".":
new_result.append(line[1][0])
return new_result
def update_csv(result):
# Ensure result is not None and can be converted to float
if result is None:
print("No result to update CSV.")
return
today = datetime.datetime.now().strftime("%Y-%m-%d")
# Check if the file exists
file_name = f"Elektronik_{today}.csv"
file_exists = os.path.isfile(file_name)
# If the file doesn't exist, create a new one with the header row
if not file_exists:
with open(file_name, "w", newline="") as csvfile:
writer = csv.writer(csvfile, delimiter=",", quotechar='"')
writer.writerow(["Vikt", "Datum", "Total Vikt"])
csvfile.close()
# Read the existing CSV file
with open(file_name, "r") as csvfile:
reader = csv.reader(csvfile, delimiter=",", quotechar='"')
rows = list(reader)
# Check if the date already exists
# Add the weights for the current date
total_weight = 0
for row in rows:
if row[1] == today:
total_weight += float(row[0])
try:
while float(result) > 30.0:
result = float(result) / 10
except ValueError as ve:
print(f"Error converting result to float: {ve}")
# Handle the error or return from the function
# Round the result to 2 decimal places
result = round(float(result), 2)
total_weight += float(result)
rows.append([str(result), today, total_weight])
# Write the updated rows to the CSV file
with open(file_name, "w", newline="") as csvfile:
writer = csv.writer(csvfile, delimiter=",", quotechar='"')
writer.writerows(rows)
if name == "main":
uvicorn.run(app, host="localhost", port=3333)