Initial commit

This commit is contained in:
2026-05-14 14:07:04 -03:00
commit e0bc5d784b
34 changed files with 7496 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
FROM public.ecr.aws/lambda/python:3.13
# Copy requirements.txt
COPY requirements.txt ${LAMBDA_TASK_ROOT}
# Install the specified packages
RUN pip install -r requirements.txt
# Copy function code
COPY ./ ${LAMBDA_TASK_ROOT}
# Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)
CMD ["lambda_handler.lambda_handler"]

View File

@@ -0,0 +1,93 @@
# ChatBot
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.shared.cloud.dnxbrasil.com.br/dnx-br/clientes/ifsp/chatbot.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.shared.cloud.dnxbrasil.com.br/dnx-br/clientes/ifsp/chatbot/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,181 @@
import boto3
import os
import tempfile
import json
from urllib.parse import urlparse
from diagram_processor import DiagramProcessor
def parse_s3_path(s3_path):
"""
Parse S3 path into bucket and key
Args:
s3_path: S3 path like 's3://bucket-name/path/to/file.pdf'
Returns:
Tuple (bucket, key)
"""
if not s3_path.startswith('s3://'):
raise ValueError(f"Invalid S3 path: {s3_path}. Must start with 's3://'")
parsed = urlparse(s3_path)
bucket = parsed.netloc
key = parsed.path.lstrip('/')
return bucket, key
def download_from_s3(s3_path, local_path):
"""
Download file from S3
Args:
s3_path: S3 path (s3://bucket/key)
local_path: Local file path to save to
"""
bucket, key = parse_s3_path(s3_path)
s3_client = boto3.client('s3')
print(f"Downloading from S3: {s3_path}")
s3_client.download_file(bucket, key, local_path)
print(f"Downloaded to: {local_path}")
def execute(s3_path):
"""
Function A - Process diagram from S3 and return matches only
Args:
s3_path: S3 path to diagram (e.g., 's3://my-bucket/diagrams/diagram.pdf')
Returns:
Dictionary with matches of labels and blocks
"""
print(f"Function A - Diagram Processing")
print(f"Input S3 path: {s3_path}")
# Create temporary directory
with tempfile.TemporaryDirectory() as temp_dir:
# Download diagram from S3
bucket, key = parse_s3_path(s3_path)
input_file = os.path.join(temp_dir, os.path.basename(key))
download_from_s3(s3_path, input_file)
# Create output directory for processing
output_dir = os.path.join(temp_dir, 'output')
os.makedirs(output_dir, exist_ok=True)
# Initialize processor
print("\nInitializing DiagramProcessor...")
processor = DiagramProcessor(
region=os.environ.get('AWS_REGION', 'us-east-1'),
custom_labels_arn=os.environ.get('CUSTOM_LABELS_ARN', 'arn:aws:rekognition:us-east-1:173378533286:project/labels-valvula/version/labels-valvula.2025-11-24T15.44.16/1764009856090')
)
# Process diagram
print("\nProcessing diagram...")
try:
results = processor.process_single_diagram(
diagram_path=input_file,
output_base_dir=output_dir,
grid_size=(5, 5),
overlap_percent=10,
keep_regex_list=[r'\+', r'\+', r'.*[Xx].*', r'\*', r'\\'],
min_confidence=80,
custom_labels_confidence=60,
iou_threshold=0.3,
matching_max_distance=200
)
# Extract only the matches
matching_results = results['matching_results']
# Format matches for clean output
formatted_matches = []
for match in matching_results['matches']:
match_type = match.get('match_type', 'vm_label')
if match_type == 'two_labels':
formatted_match = {
'object_name': match['object_name'],
'object_confidence': round(match['object_confidence'], 2),
'match_type': match_type,
'text_top': match['text_top'],
'text_top_confidence': round(match['text_confidence_top'], 2),
'text_bottom': match['text_bottom'],
'text_bottom_confidence': round(match['text_confidence_bottom'], 2),
'object_bbox': match['object_bbox'],
'text_bbox_top': match['text_bbox_top'],
'text_bbox_bottom': match['text_bbox_bottom']
}
else:
formatted_match = {
'object_name': match['object_name'],
'object_confidence': round(match['object_confidence'], 2),
'match_type': match_type,
'text': match['text'],
'text_confidence': round(match['text_confidence'], 2),
'distance_pixels': round(match['distance_pixels'], 2),
'object_bbox': match['object_bbox'],
'text_bbox': match['text_bbox']
}
formatted_matches.append(formatted_match)
# Format unmatched objects
unmatched_objects = [
{
'name': obj['Name'],
'confidence': round(obj['Confidence'], 2),
'bbox': obj['global_bbox']
}
for obj in matching_results['unmatched_objects']
]
# Format unmatched texts
unmatched_texts = [
{
'text': text['text'],
'confidence': round(text['confidence'], 2),
'bbox': text['global_bbox']
}
for text in matching_results['unmatched_texts']
]
# Prepare response
response = {
'status': 'success',
'input_s3_path': s3_path,
'summary': {
'total_matches': len(formatted_matches),
'unmatched_objects': len(unmatched_objects),
'unmatched_texts': len(unmatched_texts),
'matching_rate': f"{matching_results['matching_rate']*100:.1f}%"
},
'matches': formatted_matches,
'unmatched_objects': unmatched_objects,
'unmatched_texts': unmatched_texts
}
print("\n" + "="*80)
print("PROCESSING COMPLETE")
print("="*80)
print(f"Total matches: {len(formatted_matches)}")
print(f"Matching rate: {matching_results['matching_rate']*100:.1f}%")
print(f"Unmatched objects: {len(unmatched_objects)}")
print(f"Unmatched texts: {len(unmatched_texts)}")
return response
except Exception as e:
error_message = f"Error processing diagram: {str(e)}"
print(error_message)
import traceback
traceback.print_exc()
return {
'status': 'error',
'error': error_message,
'input_s3_path': s3_path
}

View File

@@ -0,0 +1,6 @@
def execute(text):
"""
Function B - prints the received text parameter
"""
print(f"Function B received: {text}")
return f"Function B processed: {text}"

View File

@@ -0,0 +1,111 @@
import json
import function_a
import function_b
def lambda_handler(event, context):
"""
AWS Lambda handler that routes to function_a or function_b
Expected event structure:
{
"function_name": "function_a" or "function_b",
"text_parameter": "your string here"
}
"""
try:
# DEBUG: Log the entire event
print(f"Received event: {json.dumps(event)}")
# Handle different event sources
body = None
# Check if body exists and is a string (API Gateway)
if 'body' in event:
if event['body'] is None:
return {
'statusCode': 400,
'body': json.dumps({'error': 'Request body is empty'})
}
if isinstance(event['body'], str):
# Try to parse JSON
try:
body = json.loads(event['body'])
except json.JSONDecodeError as e:
return {
'statusCode': 400,
'body': json.dumps({
'error': 'Invalid JSON in request body',
'details': str(e),
'received': event['body'][:100] # First 100 chars
})
}
else:
body = event['body']
else:
# Direct invocation (no body wrapper)
body = event
print(f"Parsed body: {json.dumps(body)}")
# Get parameters
function_name = body.get('function_name')
text_parameter = body.get('text_parameter')
# Validate inputs
if not function_name:
return {
'statusCode': 400,
'body': json.dumps({'error': 'function_name is required'})
}
if not text_parameter:
return {
'statusCode': 400,
'body': json.dumps({'error': 'text_parameter is required'})
}
# Route to the appropriate function
if function_name == 'function_a':
result = function_a.execute(text_parameter)
elif function_name == 'function_b':
result = function_b.execute(text_parameter)
else:
return {
'statusCode': 400,
'body': json.dumps({'error': f'Unknown function: {function_name}. Use "function_a" or "function_b"'})
}
# Return success response
return {
'statusCode': 200,
'body': json.dumps({
'message': 'Success',
'result': result
})
}
except Exception as e:
print(f"Error: {str(e)}")
import traceback
print(traceback.format_exc())
return {
'statusCode': 500,
'body': json.dumps({
'error': str(e),
'type': type(e).__name__
})
}
# For local testing
if __name__ == "__main__":
# Test event
test_event = {
'function_name': 'function_a',
'text_parameter': 'Hello from Lambda!'
}
result = lambda_handler(test_event, None)
print(json.dumps(result, indent=2))

View File

@@ -0,0 +1,4 @@
Pillow
numpy
scipy
pdf2image