-
Notifications
You must be signed in to change notification settings - Fork 4
Integrate recommendation backend #504
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 7 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
d7c53f7
implement tag-recommendation data model
4e4b760
implement crud and dto
Doma1612 1c6dfc7
implement dummy classification
Doma1612 e99a79b
document tag recommendation
Doma1612 1a1dba1
update alembic version
Doma1612 4cce2bd
remove faulty alembic version
Doma1612 24c84e2
Address Tims findings
Doma1612 3e98611
update None value query
Doma1612 e83f6de
revert changes
Doma1612 c99cbb8
remove dto transformation
Doma1612 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
145 changes: 145 additions & 0 deletions
145
backend/src/alembic/versions/523e193d91a0_add_document_tag_recommendation.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| """vscode launcher | ||
|
|
||
| Revision ID: 523e193d91a0 | ||
| Revises: 241cfa625db2 | ||
| Create Date: 2025-02-19 15:02:00.342999 | ||
|
|
||
| """ | ||
|
|
||
| from typing import Sequence, Union | ||
|
|
||
| import sqlalchemy as sa | ||
|
|
||
| from alembic import op | ||
|
|
||
| # revision identifiers, used by Alembic. | ||
| revision: str = "523e193d91a0" | ||
| down_revision: Union[str, None] = "241cfa625db2" | ||
| branch_labels: Union[str, Sequence[str], None] = None | ||
| depends_on: Union[str, Sequence[str], None] = None | ||
|
|
||
|
|
||
| def upgrade() -> None: | ||
| # ### commands auto generated by Alembic - please adjust! ### | ||
| op.create_table( | ||
| "documenttagrecommendationjob", | ||
| sa.Column("task_id", sa.Integer(), nullable=False), | ||
| sa.Column("model_name", sa.String(), nullable=True), | ||
| sa.Column( | ||
| "created", sa.DateTime(), server_default=sa.text("now()"), nullable=False | ||
| ), | ||
| sa.Column("user_id", sa.Integer(), nullable=False), | ||
| sa.Column("project_id", sa.Integer(), nullable=False), | ||
| sa.ForeignKeyConstraint(["project_id"], ["project.id"], ondelete="CASCADE"), | ||
| sa.ForeignKeyConstraint(["user_id"], ["user.id"], ondelete="CASCADE"), | ||
| sa.PrimaryKeyConstraint("task_id"), | ||
| ) | ||
| op.create_index( | ||
| op.f("ix_documenttagrecommendationjob_created"), | ||
| "documenttagrecommendationjob", | ||
| ["created"], | ||
| unique=False, | ||
| ) | ||
| op.create_index( | ||
| op.f("ix_documenttagrecommendationjob_model_name"), | ||
| "documenttagrecommendationjob", | ||
| ["model_name"], | ||
| unique=False, | ||
| ) | ||
| op.create_index( | ||
| op.f("ix_documenttagrecommendationjob_project_id"), | ||
| "documenttagrecommendationjob", | ||
| ["project_id"], | ||
| unique=False, | ||
| ) | ||
| op.create_index( | ||
| op.f("ix_documenttagrecommendationjob_task_id"), | ||
| "documenttagrecommendationjob", | ||
| ["task_id"], | ||
| unique=False, | ||
| ) | ||
| op.create_index( | ||
| op.f("ix_documenttagrecommendationjob_user_id"), | ||
| "documenttagrecommendationjob", | ||
| ["user_id"], | ||
| unique=False, | ||
| ) | ||
| op.create_table( | ||
| "documenttagrecommendationlink", | ||
| sa.Column("id", sa.Integer(), nullable=False), | ||
| sa.Column("recommendation_task_id", sa.Integer(), nullable=False), | ||
| sa.Column("source_document_id", sa.Integer(), nullable=False), | ||
| sa.Column("predicted_tag_id", sa.Integer(), nullable=False), | ||
| sa.Column("prediction_score", sa.Float(), nullable=True), | ||
| sa.Column("is_accepted", sa.Boolean(), nullable=True), | ||
| sa.ForeignKeyConstraint( | ||
| ["predicted_tag_id"], ["documenttag.id"], ondelete="CASCADE" | ||
| ), | ||
| sa.ForeignKeyConstraint( | ||
| ["recommendation_task_id"], | ||
| ["documenttagrecommendationjob.task_id"], | ||
| ondelete="CASCADE", | ||
| ), | ||
| sa.ForeignKeyConstraint( | ||
| ["source_document_id"], ["sourcedocument.id"], ondelete="CASCADE" | ||
| ), | ||
| sa.PrimaryKeyConstraint("id"), | ||
| ) | ||
| op.create_index( | ||
| op.f("ix_documenttagrecommendationlink_id"), | ||
| "documenttagrecommendationlink", | ||
| ["id"], | ||
| unique=False, | ||
| ) | ||
| op.create_index( | ||
| op.f("ix_documenttagrecommendationlink_is_accepted"), | ||
| "documenttagrecommendationlink", | ||
| ["is_accepted"], | ||
| unique=False, | ||
| ) | ||
| op.create_index( | ||
| op.f("ix_documenttagrecommendationlink_prediction_score"), | ||
| "documenttagrecommendationlink", | ||
| ["prediction_score"], | ||
| unique=False, | ||
| ) | ||
| # ### end Alembic commands ### | ||
|
|
||
|
|
||
| def downgrade() -> None: | ||
| # ### commands auto generated by Alembic - please adjust! ### | ||
| op.drop_index( | ||
| op.f("ix_documenttagrecommendationlink_prediction_score"), | ||
| table_name="documenttagrecommendationlink", | ||
| ) | ||
| op.drop_index( | ||
| op.f("ix_documenttagrecommendationlink_is_accepted"), | ||
| table_name="documenttagrecommendationlink", | ||
| ) | ||
| op.drop_index( | ||
| op.f("ix_documenttagrecommendationlink_id"), | ||
| table_name="documenttagrecommendationlink", | ||
| ) | ||
| op.drop_table("documenttagrecommendationlink") | ||
| op.drop_index( | ||
| op.f("ix_documenttagrecommendationjob_user_id"), | ||
| table_name="documenttagrecommendationjob", | ||
| ) | ||
| op.drop_index( | ||
| op.f("ix_documenttagrecommendationjob_task_id"), | ||
| table_name="documenttagrecommendationjob", | ||
| ) | ||
| op.drop_index( | ||
| op.f("ix_documenttagrecommendationjob_project_id"), | ||
| table_name="documenttagrecommendationjob", | ||
| ) | ||
| op.drop_index( | ||
| op.f("ix_documenttagrecommendationjob_model_name"), | ||
| table_name="documenttagrecommendationjob", | ||
| ) | ||
| op.drop_index( | ||
| op.f("ix_documenttagrecommendationjob_created"), | ||
| table_name="documenttagrecommendationjob", | ||
| ) | ||
| op.drop_table("documenttagrecommendationjob") | ||
| # ### end Alembic commands ### | ||
114 changes: 114 additions & 0 deletions
114
backend/src/api/endpoints/document_tag_recommendation.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| from typing import List | ||
|
|
||
| from fastapi import APIRouter, Depends, HTTPException | ||
| from sqlalchemy.orm import Session | ||
|
|
||
| from api.dependencies import get_current_user, get_db_session | ||
| from app.celery.background_jobs import ( | ||
| prepare_and_start_document_classification_job_async, | ||
| ) | ||
| from app.core.authorization.authz_user import AuthzUser | ||
| from app.core.data.classification.document_classification_service import ( | ||
| DocumentClassificationService, | ||
| ) | ||
| from app.core.data.crud.document_tag_recommendation import ( | ||
| crud_document_tag_recommendation, | ||
| ) | ||
| from app.core.data.dto.document_tag_recommendation import ( | ||
| DocumentTagRecommendationJobCreate, | ||
| DocumentTagRecommendationJobCreateIntern, | ||
| DocumentTagRecommendationJobRead, | ||
| DocumentTagRecommendationSummary, | ||
| ) | ||
|
|
||
| dcs: DocumentClassificationService = DocumentClassificationService() | ||
|
|
||
| router = APIRouter( | ||
| prefix="/doctagrecommendationjob", | ||
| dependencies=[Depends(get_current_user)], | ||
| tags=["documentTagRecommendationJob"], | ||
| ) | ||
|
|
||
|
|
||
| @router.put( | ||
| "", | ||
| response_model=DocumentTagRecommendationJobRead, | ||
| summary="Creates a new Document Tag Recommendation Task and returns it.", | ||
| ) | ||
| def create_new_doc_tag_rec_task( | ||
| *, | ||
| db: Session = Depends(get_db_session), | ||
| doc_tag_rec: DocumentTagRecommendationJobCreate, | ||
| authz_user: AuthzUser = Depends(), | ||
| ) -> DocumentTagRecommendationJobRead: | ||
| authz_user.assert_in_project(doc_tag_rec.project_id) | ||
|
|
||
| db_obj = crud_document_tag_recommendation.create( | ||
| db=db, | ||
| create_dto=DocumentTagRecommendationJobCreateIntern( | ||
| project_id=doc_tag_rec.project_id, user_id=authz_user.user.id | ||
| ), | ||
| ) | ||
| response = DocumentTagRecommendationJobRead.model_validate(db_obj) | ||
| prepare_and_start_document_classification_job_async( | ||
| db_obj.task_id, | ||
| doc_tag_rec.project_id, | ||
| ) | ||
|
|
||
| return response | ||
bigabig marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| @router.get( | ||
| "/{task_id}", | ||
| response_model=List[DocumentTagRecommendationSummary], | ||
| summary="Retrieve all document tag recommendations for the given task ID.", | ||
| ) | ||
| def get_recommendations_from_task_endpoint( | ||
| task_id: int, | ||
| ) -> List[DocumentTagRecommendationSummary]: | ||
| """ | ||
| Retrieves document tag recommendations based on the specified task ID. | ||
|
|
||
| ### Response Format: | ||
| The endpoint returns a list of recommendations, where each recommendation | ||
| is represented as a DocumentTagRecommendationSummary DTO with the following structure: | ||
|
|
||
| ```python | ||
| { | ||
| "recommendation_id": int, # Unique identifier for the recommendation | ||
| "source_document": str, # Name of the source document | ||
| "predicted_tag_id": int, # ID of the predicted tag | ||
| "predicted_tag": str, # Name of the predicted tag | ||
| "prediction_score": float # Confidence score of the prediction | ||
| } | ||
| ``` | ||
|
|
||
| ### Error Handling: | ||
| - Returns HTTP 404 if no recommendations are found for the given task ID. | ||
| """ | ||
| recommendations = dcs.get_recommendations_from_task(task_id) | ||
| if not recommendations: | ||
| raise HTTPException(status_code=404, detail="No recommendations found.") | ||
| return recommendations | ||
|
|
||
|
|
||
| @router.patch( | ||
| "/update_recommendations", | ||
| response_model=int, | ||
| summary="The endpoint receives IDs of wrongly and correctly tagged document recommendations and sets `is_accepted` to `true` or `false`, while setting the corresponding document tags if `true`.", | ||
| ) | ||
| def update_recommendations( | ||
| *, | ||
| accepted_recommendation_ids: List[int], | ||
| declined_recommendation_ids: List[int], | ||
| ) -> int: | ||
| modifications = dcs.validate_recommendations( | ||
| accepted_recommendation_ids=accepted_recommendation_ids, | ||
| declined_recommendation_ids=declined_recommendation_ids, | ||
| ) | ||
| if modifications == -1: | ||
| raise HTTPException( | ||
| status_code=400, detail="An error occurred while updating recommendations." | ||
| ) | ||
|
|
||
| return modifications | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
14 changes: 14 additions & 0 deletions
14
backend/src/app/celery/background_jobs/document_classification.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| from loguru import logger | ||
|
|
||
| from app.core.data.classification.document_classification_service import ( | ||
| DocumentClassificationService, | ||
| ) | ||
|
|
||
| dcs: DocumentClassificationService = DocumentClassificationService() | ||
|
|
||
|
|
||
| def start_document_classification_job_(task_id: int, project_id): | ||
| logger.info((f"Starting classification job with task id {task_id}",)) | ||
| dcs.classify_untagged_documents(task_id=task_id, project_id=project_id) | ||
|
|
||
| logger.info(f"Classification job {task_id} has finished.") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.