index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
55,421
Swiss-Polar-Institute/project-application
refs/heads/master
/ProjectApplication/grant_management/views.py
import abc from datetime import datetime from dal import autocomplete from django.contrib import messages from django.contrib.messages.views import SuccessMessageMixin from django.http import JsonResponse, HttpResponse from django.shortcuts import redirect, render from django.urls import reverse from django.views import View from django.views.generic import TemplateView, DetailView, UpdateView, CreateView from comments.utils import comments_attachments_forms, process_comment_attachment from grant_management.forms.blog_posts import BlogPostsInlineFormSet from grant_management.forms.grant_agreement import GrantAgreementForm from grant_management.forms.installments import InstallmentsInlineFormSet from grant_management.forms.invoices import InvoicesInlineFormSet from grant_management.forms.underspending import UnderspendingsInlineFormSet from grant_management.forms.lay_summaries import LaySummariesInlineFormSet from grant_management.forms.project_basic_information import ProjectBasicInformationForm from grant_management.forms.reports import FinancialReportsInlineFormSet, ScientificReportsInlineFormSet from grant_management.models import GrantAgreement, MilestoneCategory, Medium, MediumDeleted from project_core.decorators import api_key_required from project_core.models import Project from project_core.views.common.formset_inline_view import InlineFormsetUpdateView from .forms.close_project import CloseProjectModelForm from .forms.datasets import DatasetInlineFormSet from .forms.fieldnotes import FieldNoteInlineFormSet from .forms.locations import LocationsInlineFormSet from .forms.co_investigators import PersonsInlineFormSet from .forms.media import MediaInlineFormSet from .forms.milestones import MilestoneInlineFormSet from .forms.project import ProjectForm from .forms.publications import PublicationsInlineFormSet from .forms.social_network import SocialNetworksInlineFormSet class ProjectList(TemplateView): template_name = 'grant_management/project-list.tmpl' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['projects_active'] = Project.objects.all().filter(status=Project.ONGOING) context['projects_inactive'] = Project.objects.all().exclude(status=Project.ONGOING) context.update({'active_section': 'grant_management', 'active_subsection': 'project-list', 'sidebar_template': 'grant_management/_sidebar-grant_management.tmpl' }) context['breadcrumb'] = [{'name': 'Grant management'}] context['active_tab'] = self.request.GET.get('tab', 'ongoing') return context class ProjectDetail(DetailView): template_name = 'grant_management/project-detail.tmpl' context_object_name = 'project' model = Project def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) project = context['project'] if hasattr(project, 'grantagreement'): context['grant_agreement_button_text'] = 'Edit' context['grant_agreement_button_url'] = reverse('logged-grant_management-grant_agreement-update', kwargs={'pk': project.grantagreement.id}) else: context['grant_agreement_button_text'] = 'Create' context['grant_agreement_button_url'] = reverse('logged-grant_management-grant_agreement-add', kwargs={'project': project.id}) context.update({'active_section': 'grant_management', 'active_subsection': 'project-list', 'sidebar_template': 'grant_management/_sidebar-grant_management.tmpl'}) context['breadcrumb'] = [{'name': 'Grant management', 'url': reverse('logged-grant_management-project-list')}, {'name': f'Details ({project.key_pi()})'}] context['lay_summaries_count'] = project.laysummary_set.exclude(text='').count() context['blog_posts_count'] = project.blogpost_set.exclude(text='').count() context.update(comments_attachments_forms('logged-grant_management-project-comment-add', project)) context['active_tab'] = self.request.GET.get('tab', 'finances') return context class ProjectDetailCommentAdd(ProjectDetail): def post(self, request, *args, **kwargs): self.object = Project.objects.get(pk=kwargs['pk']) context = super().get_context_data(**kwargs) result = process_comment_attachment(request, context, 'logged-grant_management-project-detail', 'logged-grant_management-project-comment-add', 'grant_management/project-detail.tmpl', context['project']) return result def update_project_update_create_context(context, action): context.update({'active_section': 'lists', 'active_subsection': 'project-create', 'sidebar_template': 'logged/_sidebar-lists.tmpl'}) if action == 'edit': human_action = f'{action} ({context["object"].key_pi()})' elif action == 'create': human_action = 'Create project' else: assert False context['breadcrumb'] = [{'name': 'Lists', 'url': reverse('logged-lists')}, {'name': 'Projects', 'url': reverse('logged-project-list')}, {'name': human_action} ] class ProjectUpdate(SuccessMessageMixin, UpdateView): template_name = 'grant_management/project-form.tmpl' form_class = ProjectForm model = Project success_message = 'Project updated' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) update_project_update_create_context(context, 'edit') return context def get_success_url(self): return reverse('logged-project-detail', kwargs={'pk': self.object.pk}) class ProjectCreate(SuccessMessageMixin, CreateView): template_name = 'grant_management/project-form.tmpl' form_class = ProjectForm model = Project success_message = 'Project created' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) update_project_update_create_context(context, 'create') return context def get_success_url(self): return reverse('logged-project-detail', kwargs={'pk': self.object.pk}) class ProjectBasicInformationUpdateView(SuccessMessageMixin, UpdateView): template_name = 'grant_management/project-basic_information-form.tmpl' form_class = ProjectBasicInformationForm model = Project success_message = 'Project information updated' pk_url_kwarg = 'project' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) project = Project.objects.get(id=self.kwargs['project']) context.update(basic_context_data_grant_agreement(project, 'Basic project information')) context['project'] = project return context def get_success_url(self): return reverse('logged-grant_management-project-detail', kwargs={'pk': self.object.pk}) def basic_context_data_grant_agreement(project, active_page): context = {'active_section': 'grant_management', 'active_subsection': 'project-list', 'sidebar_template': 'grant_management/_sidebar-grant_management.tmpl'} context['breadcrumb'] = [{'name': 'Grant management', 'url': reverse('logged-grant_management-project-list')}, {'name': f'Details ({project.key_pi()})', 'url': reverse('logged-grant_management-project-detail', kwargs={'pk': project.id})}, {'name': active_page}] return context class AbstractGrantAgreement(SuccessMessageMixin, CreateView): template_name = 'grant_management/grant_agreement-form.tmpl' form_class = GrantAgreementForm model = GrantAgreement def _get_project(self): kwargs = self.kwargs if 'pk' in kwargs: project = GrantAgreement.objects.get(id=self.kwargs['pk']).project elif 'project' in kwargs: project = Project.objects.get(id=self.kwargs['project']) else: assert False return project def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['project'] = self._get_project() context.update(basic_context_data_grant_agreement(context['project'], 'Grant agreement')) return context def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['project'] = self._get_project() if 'pk' in self.kwargs: kwargs['instance'] = GrantAgreement.objects.get(id=self.kwargs['pk']) return kwargs def get_success_url(self): return reverse('logged-grant_management-project-detail', kwargs={'pk': self.object.project.pk}) class GrantAgreementAddView(AbstractGrantAgreement): success_message = 'Grant agreement added' class GrantAgreementUpdateView(AbstractGrantAgreement): success_message = 'Grant agreement updated' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if hasattr(context['project'], 'grantagreement'): context.update(comments_attachments_forms('logged-grant_management-grant_agreement-comment-add', context['project'].grantagreement)) return context def grant_management_project_url(kwargs): return reverse('logged-grant_management-project-detail', kwargs={'pk': kwargs['project']}) class GrantManagementInlineFormset(InlineFormsetUpdateView): parent = Project url_id = 'project' tab = 'None' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) project = self.parent.objects.get(id=kwargs['project']) context.update(basic_context_data_grant_agreement(project, self.human_type_plural.capitalize())) context['project'] = project context['destination_url'] = reverse('logged-grant_management-project-detail', kwargs={'pk': project.id}) + f'?tab={self.tab}' inline_formset_kwargs = {'prefix': 'FORM_SET', 'instance': project} context['FORM_SET'] = self.inline_formset(**inline_formset_kwargs) return context class BlogPostsUpdateView(GrantManagementInlineFormset): inline_formset = BlogPostsInlineFormSet human_type = 'blog post' tab = 'deliverables' class LaySummariesUpdateView(GrantManagementInlineFormset): inline_formset = LaySummariesInlineFormSet human_type = 'lay summary' human_type_plural = 'lay summaries' tab = 'deliverables' class LocationsUpdateView(GrantManagementInlineFormset): inline_formset = LocationsInlineFormSet human_type = 'location' tab = 'other' class PersonsUpdateView(GrantManagementInlineFormset): inline_formset = PersonsInlineFormSet human_type = 'Co-Investigator' tab = 'other' class DatasetUpdateView(GrantManagementInlineFormset): inline_formset = DatasetInlineFormSet human_type = 'dataset' tab = 'deliverables' class FieldNoteUpdateView(GrantManagementInlineFormset): inline_formset = FieldNoteInlineFormSet human_type = 'fieldnote' tab = 'deliverables' class PublicationsUpdateView(GrantManagementInlineFormset): inline_formset = PublicationsInlineFormSet human_type = 'publication' tab = 'deliverables' class MediaUpdateView(GrantManagementInlineFormset): inline_formset = MediaInlineFormSet human_type = 'medium' human_type_plural = 'media' tab = 'deliverables' class InvoicesUpdateView(GrantManagementInlineFormset): inline_formset = InvoicesInlineFormSet human_type = 'invoice' tab = 'finances' class UnderspendingsUpdateView(GrantManagementInlineFormset): inline_formset = UnderspendingsInlineFormSet human_type = 'underspending' tab = 'finances' class FinancialReportsUpdateView(GrantManagementInlineFormset): inline_formset = FinancialReportsInlineFormSet human_type = 'financial report' tab = 'finances' class InstallmentsUpdateView(GrantManagementInlineFormset): inline_formset = InstallmentsInlineFormSet human_type = 'installment' tab = 'finances' class ScientificReportsUpdateView(GrantManagementInlineFormset): inline_formset = ScientificReportsInlineFormSet human_type = 'scientific report' tab = 'deliverables' class SocialMediaUpdateView(GrantManagementInlineFormset): inline_formset = SocialNetworksInlineFormSet human_type = 'outreach' human_type_plural = 'outreach' tab = 'deliverables' class MilestoneUpdateView(GrantManagementInlineFormset): inline_formset = MilestoneInlineFormSet human_type = 'milestone' tab = 'deliverables' class CloseProjectView(TemplateView): template_name = 'grant_management/close_project-form.tmpl' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['project'] = Project.objects.get(id=kwargs['project']) context.update(basic_context_data_grant_agreement(context['project'], 'Grant agreement')) context['close_project_form'] = CloseProjectModelForm(instance=context['project']) return context def post(self, request, *args, **kwargs): project = Project.objects.get(id=kwargs['project']) close_project_form = CloseProjectModelForm(request.POST, instance=project) if close_project_form.is_valid(): close_project_form.close(user=request.user) messages.success(request, 'The project has been closed') return redirect(reverse('logged-grant_management-project-list')) context = self.get_context_data(**kwargs) context['close_project_form'] = close_project_form return render(request, 'grant_management/close_project-form.tmpl', context) class LaySummariesRaw(TemplateView): template_name = 'grant_management/lay_summaries-raw.tmpl' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) call_id = kwargs['call'] projects = Project.objects.filter(call_id=call_id).order_by('key') context['projects'] = projects return context class MilestoneCategoriesAutocomplete(autocomplete.Select2QuerySetView): def create_object(self, text): d = {self.create_field: text, 'created_by': self.request.user} return self.get_queryset().get_or_create(**d)[0] def get_result_label(self, result): return result.name def has_add_permission(self, *args, **kwargs): # By default only authenticated users with permissions to add in the model # have the option to create keywords. We allow any user (if it's logged-in, for the URL) # to create milestones return True def get_queryset(self): qs = MilestoneCategory.objects.all() if self.q: qs = qs.filter(name__icontains=self.q) qs = qs.order_by('name') return qs class GrantAgreementCommentAdd(AbstractGrantAgreement): def post(self, request, *args, **kwargs): self.object = self._get_project() context = super().get_context_data(**kwargs) result = process_comment_attachment(request, context, 'logged-grant_management-grant_agreement-update', 'logged-grant_management-grant_agreement-comment-add', 'grant_management/grant_agreement-form.tmpl', context['project'].grantagreement) return result class ApiList(abc.ABC, View): @api_key_required def get(self, request, *args, **kwargs): modified_since_str = request.GET['modified_since'] modified_since_str = modified_since_str.replace('Z', '+00:00') try: modified_since = datetime.fromisoformat(modified_since_str) except ValueError: return HttpResponse(status=400, content='Invalid date format, please use %Y-%m-%dT%H:%M:%S%z E.g.: 2017-01-28T21:00:00+00:00') return self.generate_json(modified_since) @abc.abstractmethod def generate_json(self, modified_since): """ Subclass should implement and return a JsonResponse """ class ApiListMediaView(ApiList): def generate_json(self, modified_since): media = Medium.objects.filter(modified_on__gt=modified_since).order_by('modified_on') data = [] for medium in media: medium_info = {} medium_info['id'] = medium.id medium_info['received_date'] = medium.received_date if medium.license: medium_info['license'] = medium.license.spdx_identifier else: medium_info['license'] = None medium_info['copyright'] = medium.copyright medium_info['file_url'] = medium.file.url medium_info['file_md5'] = medium.file_md5 medium_info['original_file_path'] = medium.file.name medium_info['modified_on'] = medium.modified_on medium_info['descriptive_text'] = medium.descriptive_text project_info = {} project_info['key'] = medium.project.key project_info['title'] = medium.project.title project_info['funding_instrument'] = medium.project.call.funding_instrument.long_name project_info['finance_year'] = medium.project.call.finance_year project_info['pi'] = medium.project.principal_investigator.person.full_name() medium_info['project'] = project_info photographer_info = {} photographer_info['first_name'] = medium.photographer.first_name photographer_info['last_name'] = medium.photographer.surname medium_info['photographer'] = photographer_info data.append(medium_info) # safe=False... but it's safe in this case. See: # https://docs.djangoproject.com/en/3.1/ref/request-response/#serializing-non-dictionary-objects # Besides it's safe in modern browsers: this call is only used internally (it's protected) and the # consumer is another Django application, not a browser return JsonResponse(data=data, status=200, json_dumps_params={'indent': 2}, safe=False) class ApiListMediaDeletedView(ApiList): def generate_json(self, modified_since): media_deleted = MediumDeleted.objects.filter(modified_on__gt=modified_since).order_by('created_on') data = [] for medium_deleted in media_deleted: medium_deleted_info = {} medium_deleted_info['id'] = medium_deleted.original_id medium_deleted_info['deleted_on'] = medium_deleted.created_on data.append(medium_deleted_info) # safe=False... but it's safe in this case. See: # https://docs.djangoproject.com/en/3.1/ref/request-response/#serializing-non-dictionary-objects # Besides it's safe in modern browsers: this call is only used internally (it's protected) and the # consumer is another Django application, not a browser return JsonResponse(data=data, status=200, json_dumps_params={'indent': 2}, safe=False)
{"/ProjectApplication/project_core/forms/call.py": ["/ProjectApplication/project_core/fields.py", "/ProjectApplication/project_core/models.py", "/ProjectApplication/project_core/widgets.py"], "/ProjectApplication/project_core/forms/call_part_file.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/models.py"], "/ProjectApplication/grant_management/tests/test_models.py": ["/ProjectApplication/grant_management/models.py"], "/ProjectApplication/variable_templates/tests/database_population.py": ["/ProjectApplication/variable_templates/models.py"], "/ProjectApplication/project_core/forms/financial_key.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/models.py"], "/ProjectApplication/project_core/tests/views/logged/test_proposal.py": ["/ProjectApplication/project_core/models.py", "/ProjectApplication/project_core/views/logged/__init__.py"], "/ProjectApplication/project_core/tests/templatetags/test_short_filename_from_path.py": ["/ProjectApplication/project_core/templatetags/filename_from_path.py"], "/ProjectApplication/project_core/forms/proposal.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/fields.py", "/ProjectApplication/project_core/models.py", "/ProjectApplication/project_core/templatetags/thousands_separator.py", "/ProjectApplication/project_core/widgets.py"], "/ProjectApplication/comments/tests/forms/test_comment.py": ["/ProjectApplication/comments/forms/comment.py", "/ProjectApplication/comments/models.py"], "/ProjectApplication/variable_templates/tests/test_utils.py": ["/ProjectApplication/variable_templates/models.py"], "/ProjectApplication/project_core/models.py": ["/ProjectApplication/project_core/utils/SpiS3Boto3Storage.py", "/ProjectApplication/project_core/utils/orcid.py", "/ProjectApplication/project_core/utils/utils.py"], "/ProjectApplication/evaluation/admin.py": ["/ProjectApplication/evaluation/models.py"], "/ProjectApplication/project_core/utils/utils.py": ["/ProjectApplication/project_core/models.py"], "/ProjectApplication/project_core/forms/contacts.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/models.py", "/ProjectApplication/project_core/utils/orcid.py"], "/ProjectApplication/project_core/management/commands/deleteunusedexternalkeywords.py": ["/ProjectApplication/project_core/models.py"], "/ProjectApplication/project_core/views/logged/call.py": ["/ProjectApplication/project_core/views/logged/funding_instrument.py", "/ProjectApplication/project_core/views/common/proposal.py", "/ProjectApplication/project_core/widgets.py"], "/ProjectApplication/project_core/forms/postal_address.py": ["/ProjectApplication/project_core/models.py"], "/ProjectApplication/colours/admin.py": ["/ProjectApplication/colours/forms.py", "/ProjectApplication/colours/models.py"], "/ProjectApplication/project_core/forms/utils.py": ["/ProjectApplication/project_core/models.py"], "/ProjectApplication/project_core/management/commands/importorganisations.py": ["/ProjectApplication/project_core/management/commands/createorganisationnames.py"], "/ProjectApplication/comments/tests/forms/test_attachment.py": ["/ProjectApplication/comments/forms/attachment.py", "/ProjectApplication/comments/models.py"], "/ProjectApplication/comments/tests/test_utils.py": ["/ProjectApplication/comments/forms/attachment.py", "/ProjectApplication/comments/forms/comment.py", "/ProjectApplication/comments/models.py"], "/ProjectApplication/grant_management/admin.py": ["/ProjectApplication/grant_management/models.py"], "/ProjectApplication/evaluation/forms/proposal_evaluation.py": ["/ProjectApplication/evaluation/models.py", "/ProjectApplication/evaluation/utils.py"], "/ProjectApplication/project_core/forms/call_part.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/models.py"], "/ProjectApplication/project_core/tests/templatetags/test_ordinal.py": ["/ProjectApplication/project_core/templatetags/ordinal.py"], "/ProjectApplication/variable_templates/forms/template_variables.py": ["/ProjectApplication/variable_templates/models.py"], "/ProjectApplication/project_core/forms/funding_instrument.py": ["/ProjectApplication/project_core/models.py"], "/ProjectApplication/project_core/forms/partners.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/utils/orcid.py", "/ProjectApplication/project_core/utils/utils.py"], "/ProjectApplication/project_core/forms/person.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/utils/utils.py", "/ProjectApplication/project_core/widgets.py"], "/ProjectApplication/colours/forms.py": ["/ProjectApplication/colours/models.py"], "/ProjectApplication/grant_management/views.py": ["/ProjectApplication/grant_management/forms/close_project.py", "/ProjectApplication/grant_management/forms/datasets.py", "/ProjectApplication/grant_management/forms/locations.py", "/ProjectApplication/grant_management/forms/co_investigators.py", "/ProjectApplication/grant_management/forms/media.py", "/ProjectApplication/grant_management/forms/project.py"]}
55,422
Swiss-Polar-Institute/project-application
refs/heads/master
/ProjectApplication/comments/migrations/0014_adds_txt_to_attachment.py
# Generated by Django 2.2.6 on 2020-02-12 12:05 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('comments', '0013_adds_call_comment_category'), ] operations = [ migrations.AddField( model_name='callattachment', name='text', field=models.TextField(blank=True, help_text='Comment of the attachment', null=True), ), migrations.AddField( model_name='proposalattachment', name='text', field=models.TextField(blank=True, help_text='Comment of the attachment', null=True), ), migrations.AlterUniqueTogether( name='callattachment', unique_together={('created_on', 'created_by')}, ), migrations.AlterUniqueTogether( name='proposalattachment', unique_together={('created_on', 'created_by')}, ), ]
{"/ProjectApplication/project_core/forms/call.py": ["/ProjectApplication/project_core/fields.py", "/ProjectApplication/project_core/models.py", "/ProjectApplication/project_core/widgets.py"], "/ProjectApplication/project_core/forms/call_part_file.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/models.py"], "/ProjectApplication/grant_management/tests/test_models.py": ["/ProjectApplication/grant_management/models.py"], "/ProjectApplication/variable_templates/tests/database_population.py": ["/ProjectApplication/variable_templates/models.py"], "/ProjectApplication/project_core/forms/financial_key.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/models.py"], "/ProjectApplication/project_core/tests/views/logged/test_proposal.py": ["/ProjectApplication/project_core/models.py", "/ProjectApplication/project_core/views/logged/__init__.py"], "/ProjectApplication/project_core/tests/templatetags/test_short_filename_from_path.py": ["/ProjectApplication/project_core/templatetags/filename_from_path.py"], "/ProjectApplication/project_core/forms/proposal.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/fields.py", "/ProjectApplication/project_core/models.py", "/ProjectApplication/project_core/templatetags/thousands_separator.py", "/ProjectApplication/project_core/widgets.py"], "/ProjectApplication/comments/tests/forms/test_comment.py": ["/ProjectApplication/comments/forms/comment.py", "/ProjectApplication/comments/models.py"], "/ProjectApplication/variable_templates/tests/test_utils.py": ["/ProjectApplication/variable_templates/models.py"], "/ProjectApplication/project_core/models.py": ["/ProjectApplication/project_core/utils/SpiS3Boto3Storage.py", "/ProjectApplication/project_core/utils/orcid.py", "/ProjectApplication/project_core/utils/utils.py"], "/ProjectApplication/evaluation/admin.py": ["/ProjectApplication/evaluation/models.py"], "/ProjectApplication/project_core/utils/utils.py": ["/ProjectApplication/project_core/models.py"], "/ProjectApplication/project_core/forms/contacts.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/models.py", "/ProjectApplication/project_core/utils/orcid.py"], "/ProjectApplication/project_core/management/commands/deleteunusedexternalkeywords.py": ["/ProjectApplication/project_core/models.py"], "/ProjectApplication/project_core/views/logged/call.py": ["/ProjectApplication/project_core/views/logged/funding_instrument.py", "/ProjectApplication/project_core/views/common/proposal.py", "/ProjectApplication/project_core/widgets.py"], "/ProjectApplication/project_core/forms/postal_address.py": ["/ProjectApplication/project_core/models.py"], "/ProjectApplication/colours/admin.py": ["/ProjectApplication/colours/forms.py", "/ProjectApplication/colours/models.py"], "/ProjectApplication/project_core/forms/utils.py": ["/ProjectApplication/project_core/models.py"], "/ProjectApplication/project_core/management/commands/importorganisations.py": ["/ProjectApplication/project_core/management/commands/createorganisationnames.py"], "/ProjectApplication/comments/tests/forms/test_attachment.py": ["/ProjectApplication/comments/forms/attachment.py", "/ProjectApplication/comments/models.py"], "/ProjectApplication/comments/tests/test_utils.py": ["/ProjectApplication/comments/forms/attachment.py", "/ProjectApplication/comments/forms/comment.py", "/ProjectApplication/comments/models.py"], "/ProjectApplication/grant_management/admin.py": ["/ProjectApplication/grant_management/models.py"], "/ProjectApplication/evaluation/forms/proposal_evaluation.py": ["/ProjectApplication/evaluation/models.py", "/ProjectApplication/evaluation/utils.py"], "/ProjectApplication/project_core/forms/call_part.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/models.py"], "/ProjectApplication/project_core/tests/templatetags/test_ordinal.py": ["/ProjectApplication/project_core/templatetags/ordinal.py"], "/ProjectApplication/variable_templates/forms/template_variables.py": ["/ProjectApplication/variable_templates/models.py"], "/ProjectApplication/project_core/forms/funding_instrument.py": ["/ProjectApplication/project_core/models.py"], "/ProjectApplication/project_core/forms/partners.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/utils/orcid.py", "/ProjectApplication/project_core/utils/utils.py"], "/ProjectApplication/project_core/forms/person.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/utils/utils.py", "/ProjectApplication/project_core/widgets.py"], "/ProjectApplication/colours/forms.py": ["/ProjectApplication/colours/models.py"], "/ProjectApplication/grant_management/views.py": ["/ProjectApplication/grant_management/forms/close_project.py", "/ProjectApplication/grant_management/forms/datasets.py", "/ProjectApplication/grant_management/forms/locations.py", "/ProjectApplication/grant_management/forms/co_investigators.py", "/ProjectApplication/grant_management/forms/media.py", "/ProjectApplication/grant_management/forms/project.py"]}
55,423
Swiss-Polar-Institute/project-application
refs/heads/master
/ProjectApplication/grant_management/migrations/0002_auto_20200406_1008.py
# Generated by Django 3.0.3 on 2020-04-06 08:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('grant_management', '0001_initial'), ] operations = [ migrations.RenameField( model_name='laysummary', old_name='webversion', new_name='web_version', ), migrations.RemoveField( model_name='invoice', name='urls', ), migrations.RemoveField( model_name='publication', name='date_published', ), migrations.AddField( model_name='publication', name='date_time_published', field=models.DateTimeField(blank=True, help_text='Date of the publication', null=True), ), migrations.AlterField( model_name='dataset', name='url', field=models.URLField(blank=True, help_text='Web address for entry', null=True), ), migrations.AlterField( model_name='financereport', name='due_date', field=models.DateField(blank=True, help_text='Date that the document is expected to be received', null=True), ), migrations.AlterField( model_name='invoice', name='amount', field=models.DecimalField(blank=True, decimal_places=2, help_text='Total of the invoice (CHF)', max_digits=20, null=True), ), migrations.AlterField( model_name='invoice', name='due_date', field=models.DateField(blank=True, help_text='Date that the document is expected to be received', null=True), ), migrations.AlterField( model_name='laysummary', name='due_date', field=models.DateField(blank=True, help_text='Date that the document is expected to be received', null=True), ), migrations.AlterField( model_name='media', name='due_date', field=models.DateField(blank=True, help_text='Date that the document is expected to be received', null=True), ), migrations.AlterField( model_name='projectsocialmedia', name='url', field=models.URLField(blank=True, help_text='Web address of social media entry', null=True), ), ]
{"/ProjectApplication/project_core/forms/call.py": ["/ProjectApplication/project_core/fields.py", "/ProjectApplication/project_core/models.py", "/ProjectApplication/project_core/widgets.py"], "/ProjectApplication/project_core/forms/call_part_file.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/models.py"], "/ProjectApplication/grant_management/tests/test_models.py": ["/ProjectApplication/grant_management/models.py"], "/ProjectApplication/variable_templates/tests/database_population.py": ["/ProjectApplication/variable_templates/models.py"], "/ProjectApplication/project_core/forms/financial_key.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/models.py"], "/ProjectApplication/project_core/tests/views/logged/test_proposal.py": ["/ProjectApplication/project_core/models.py", "/ProjectApplication/project_core/views/logged/__init__.py"], "/ProjectApplication/project_core/tests/templatetags/test_short_filename_from_path.py": ["/ProjectApplication/project_core/templatetags/filename_from_path.py"], "/ProjectApplication/project_core/forms/proposal.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/fields.py", "/ProjectApplication/project_core/models.py", "/ProjectApplication/project_core/templatetags/thousands_separator.py", "/ProjectApplication/project_core/widgets.py"], "/ProjectApplication/comments/tests/forms/test_comment.py": ["/ProjectApplication/comments/forms/comment.py", "/ProjectApplication/comments/models.py"], "/ProjectApplication/variable_templates/tests/test_utils.py": ["/ProjectApplication/variable_templates/models.py"], "/ProjectApplication/project_core/models.py": ["/ProjectApplication/project_core/utils/SpiS3Boto3Storage.py", "/ProjectApplication/project_core/utils/orcid.py", "/ProjectApplication/project_core/utils/utils.py"], "/ProjectApplication/evaluation/admin.py": ["/ProjectApplication/evaluation/models.py"], "/ProjectApplication/project_core/utils/utils.py": ["/ProjectApplication/project_core/models.py"], "/ProjectApplication/project_core/forms/contacts.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/models.py", "/ProjectApplication/project_core/utils/orcid.py"], "/ProjectApplication/project_core/management/commands/deleteunusedexternalkeywords.py": ["/ProjectApplication/project_core/models.py"], "/ProjectApplication/project_core/views/logged/call.py": ["/ProjectApplication/project_core/views/logged/funding_instrument.py", "/ProjectApplication/project_core/views/common/proposal.py", "/ProjectApplication/project_core/widgets.py"], "/ProjectApplication/project_core/forms/postal_address.py": ["/ProjectApplication/project_core/models.py"], "/ProjectApplication/colours/admin.py": ["/ProjectApplication/colours/forms.py", "/ProjectApplication/colours/models.py"], "/ProjectApplication/project_core/forms/utils.py": ["/ProjectApplication/project_core/models.py"], "/ProjectApplication/project_core/management/commands/importorganisations.py": ["/ProjectApplication/project_core/management/commands/createorganisationnames.py"], "/ProjectApplication/comments/tests/forms/test_attachment.py": ["/ProjectApplication/comments/forms/attachment.py", "/ProjectApplication/comments/models.py"], "/ProjectApplication/comments/tests/test_utils.py": ["/ProjectApplication/comments/forms/attachment.py", "/ProjectApplication/comments/forms/comment.py", "/ProjectApplication/comments/models.py"], "/ProjectApplication/grant_management/admin.py": ["/ProjectApplication/grant_management/models.py"], "/ProjectApplication/evaluation/forms/proposal_evaluation.py": ["/ProjectApplication/evaluation/models.py", "/ProjectApplication/evaluation/utils.py"], "/ProjectApplication/project_core/forms/call_part.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/models.py"], "/ProjectApplication/project_core/tests/templatetags/test_ordinal.py": ["/ProjectApplication/project_core/templatetags/ordinal.py"], "/ProjectApplication/variable_templates/forms/template_variables.py": ["/ProjectApplication/variable_templates/models.py"], "/ProjectApplication/project_core/forms/funding_instrument.py": ["/ProjectApplication/project_core/models.py"], "/ProjectApplication/project_core/forms/partners.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/utils/orcid.py", "/ProjectApplication/project_core/utils/utils.py"], "/ProjectApplication/project_core/forms/person.py": ["/ProjectApplication/project_core/forms/utils.py", "/ProjectApplication/project_core/utils/utils.py", "/ProjectApplication/project_core/widgets.py"], "/ProjectApplication/colours/forms.py": ["/ProjectApplication/colours/models.py"], "/ProjectApplication/grant_management/views.py": ["/ProjectApplication/grant_management/forms/close_project.py", "/ProjectApplication/grant_management/forms/datasets.py", "/ProjectApplication/grant_management/forms/locations.py", "/ProjectApplication/grant_management/forms/co_investigators.py", "/ProjectApplication/grant_management/forms/media.py", "/ProjectApplication/grant_management/forms/project.py"]}
55,424
amitesh080295/redis-lock
refs/heads/main
/src/controllers/management.py
from fastapi import APIRouter management_router = APIRouter( prefix='/management' ) @management_router.get('/health') def health_check(): return dict(status='UP')
{"/src/controllers/api.py": ["/src/configs/containers.py", "/src/services/redis_service.py"], "/src/services/redis_service.py": ["/src/configs/redis_datasource.py"], "/src/configs/config_client.py": ["/src/security/authenticator.py"], "/src/configs/containers.py": ["/src/services/redis_service.py", "/src/security/authenticator.py", "/src/configs/config_client.py", "/src/configs/redis_datasource.py"], "/src/app.py": ["/src/configs/containers.py"]}
55,425
amitesh080295/redis-lock
refs/heads/main
/src/controllers/api.py
from fastapi import APIRouter, Depends from dependency_injector.wiring import inject, Provide from ..configs.containers import Container from ..services.redis_service import RedisService import logging logger = logging.getLogger(__name__) api_router = APIRouter( prefix='/api/v1' ) @api_router.get('/lock') @inject def lock( key: str, key_expiry: int, redis_service: RedisService = Depends(Provide[Container.redis_service]) ): return redis_service.get_lock(key, key_expiry) @api_router.get('/unlock') @inject def unlock( key: str, redis_service: RedisService = Depends(Provide[Container.redis_service]) ): return redis_service.remove_lock(key)
{"/src/controllers/api.py": ["/src/configs/containers.py", "/src/services/redis_service.py"], "/src/services/redis_service.py": ["/src/configs/redis_datasource.py"], "/src/configs/config_client.py": ["/src/security/authenticator.py"], "/src/configs/containers.py": ["/src/services/redis_service.py", "/src/security/authenticator.py", "/src/configs/config_client.py", "/src/configs/redis_datasource.py"], "/src/app.py": ["/src/configs/containers.py"]}
55,426
amitesh080295/redis-lock
refs/heads/main
/src/services/redis_service.py
import logging from ..configs.redis_datasource import RedisDatasource logger = logging.getLogger(__name__) class RedisService: def __init__(self, redis_datasource: RedisDatasource): self.redis_datasource = redis_datasource def get_lock(self, key: str, key_expiry: int): redis_response = self.redis_datasource.set_key(key, key_expiry) if redis_response: logger.info(f'{key} is set in Redis') return dict(status=201, message=f'{key} is unique') logger.info(f'{key} is duplicate') return dict(status=406, message=f'{key} is duplicate') def remove_lock(self, key: str): redis_response = self.redis_datasource.delete_key(key) if redis_response: logger.info(f'{key} is removed') return dict(status=202, message=f'{key} is removed') logger.info(f'{key} didn\'t exist') return dict(status=404, message=f'{key} didn\'t exist')
{"/src/controllers/api.py": ["/src/configs/containers.py", "/src/services/redis_service.py"], "/src/services/redis_service.py": ["/src/configs/redis_datasource.py"], "/src/configs/config_client.py": ["/src/security/authenticator.py"], "/src/configs/containers.py": ["/src/services/redis_service.py", "/src/security/authenticator.py", "/src/configs/config_client.py", "/src/configs/redis_datasource.py"], "/src/app.py": ["/src/configs/containers.py"]}
55,427
amitesh080295/redis-lock
refs/heads/main
/src/configs/config_client.py
import json import requests import re import logging from ..security.authenticator import AuthenticationHandler from environs import Env logger = logging.getLogger(__name__) def parse_config(property_sources): config_server_properties = {} property_sources.reverse() for property_source in property_sources: config_server_properties.update(property_source['source']) return config_server_properties class PythonConfigClient: def __init__(self, auth_handler: AuthenticationHandler, env: Env): self.address = env.str('config-address') self.branch = env.str('branch') self.profile = env.str('profile') self.app_name = env.str('app-name') self.profile = self.profile.replace(',', '%2C') config_url = self.address + '/' + self.app_name + '/' + self.profile + '/' + self.branch headers = {'X-Config-Token': auth_handler.get_auth_token()} try: logger.info('Getting the properties from the config server') response = requests.get(config_url, headers=headers) decoded_response = response.content.decode('utf-8') property_sources = json.loads(decoded_response)['propertySources'] self.CONFIG_SERVER_PROPERTIES = parse_config(property_sources) logger.info('Config properties have been successfully fetched') except Exception as exception: logger.error('Failed to fetch configs from config server' + str(exception)) def serve_value(self, key): value = str(self.CONFIG_SERVER_PROPERTIES.get(key)) match = re.search('(?<=\${)[a-zA-Z0-9.-]*(?=})', value) if match: sub_key = match.group(0) return value.replace('${' + sub_key + '}', str(self.CONFIG_SERVER_PROPERTIES.get(sub_key))) else: return value
{"/src/controllers/api.py": ["/src/configs/containers.py", "/src/services/redis_service.py"], "/src/services/redis_service.py": ["/src/configs/redis_datasource.py"], "/src/configs/config_client.py": ["/src/security/authenticator.py"], "/src/configs/containers.py": ["/src/services/redis_service.py", "/src/security/authenticator.py", "/src/configs/config_client.py", "/src/configs/redis_datasource.py"], "/src/app.py": ["/src/configs/containers.py"]}
55,428
amitesh080295/redis-lock
refs/heads/main
/src/security/oauth_filter.py
import requests import logging from fastapi import Header, HTTPException, Depends from http import HTTPStatus from environs import Env env = Env() logger = logging.getLogger(__name__) class OAuthFilter: def __init__(self): auth_token_url = env.url('auth.token.url') self.token_validation_url = auth_token_url.replace('/token', '/user') def validate_token(self, token: str): headers = dict(Authorization=token) try: response = requests.get(self.token_validation_url, headers=headers) if response.status_code == HTTPStatus.OK: return True except Exception as exception: logger.error(f'Unable to validate the token {str(exception)}') return False def resolve_token(authorization): if type(authorization) == str and authorization.startswith('Bearer '): return authorization return None def secure(authorization: str = Header(None), oauth_filter: OAuthFilter = Depends(OAuthFilter)): token = resolve_token(authorization) if not oauth_filter.validate_token(token): raise HTTPException(status_code=403, detail='Access Forbidden')
{"/src/controllers/api.py": ["/src/configs/containers.py", "/src/services/redis_service.py"], "/src/services/redis_service.py": ["/src/configs/redis_datasource.py"], "/src/configs/config_client.py": ["/src/security/authenticator.py"], "/src/configs/containers.py": ["/src/services/redis_service.py", "/src/security/authenticator.py", "/src/configs/config_client.py", "/src/configs/redis_datasource.py"], "/src/app.py": ["/src/configs/containers.py"]}
55,429
amitesh080295/redis-lock
refs/heads/main
/src/configs/redis_datasource.py
import redis import logging logger = logging.getLogger(__name__) class RedisDatasource: def __init__(self): logger.info('Connecting to Redis...') try: self.redis_connection = redis.Redis( host='localhost', port=6379, db=0 ) logger.info('Successfully connected to Redis') except Exception as exception: logger.error(f'Unable to connect to Redis ${str(exception)}') raise def set_key(self, key: str, key_expiry: int): return self.redis_connection.set(key, 'DUMMY', ex=key_expiry, nx=True) def delete_key(self, key: str): return self.redis_connection.delete(key)
{"/src/controllers/api.py": ["/src/configs/containers.py", "/src/services/redis_service.py"], "/src/services/redis_service.py": ["/src/configs/redis_datasource.py"], "/src/configs/config_client.py": ["/src/security/authenticator.py"], "/src/configs/containers.py": ["/src/services/redis_service.py", "/src/security/authenticator.py", "/src/configs/config_client.py", "/src/configs/redis_datasource.py"], "/src/app.py": ["/src/configs/containers.py"]}
55,430
amitesh080295/redis-lock
refs/heads/main
/src/configs/containers.py
from dependency_injector import containers, providers from environs import Env from ..services.redis_service import RedisService from ..security.authenticator import AuthenticationHandler from ..configs.config_client import PythonConfigClient from ..configs.redis_datasource import RedisDatasource class Container(containers.DeclarativeContainer): configs = providers.Configuration() env = providers.Singleton( Env ) auth_handler = providers.Singleton( AuthenticationHandler, env=env ) python_config_client = providers.Singleton( PythonConfigClient, auth_handler=auth_handler, env=env ) redis_datasource = providers.Singleton( RedisDatasource ) redis_service = providers.Singleton( RedisService, redis_datasource=redis_datasource )
{"/src/controllers/api.py": ["/src/configs/containers.py", "/src/services/redis_service.py"], "/src/services/redis_service.py": ["/src/configs/redis_datasource.py"], "/src/configs/config_client.py": ["/src/security/authenticator.py"], "/src/configs/containers.py": ["/src/services/redis_service.py", "/src/security/authenticator.py", "/src/configs/config_client.py", "/src/configs/redis_datasource.py"], "/src/app.py": ["/src/configs/containers.py"]}
55,431
amitesh080295/redis-lock
refs/heads/main
/src/app.py
from fastapi import FastAPI from .configs.containers import Container from .controllers import api, management import logging logging.basicConfig(format='%(asctime)s %(module)s %(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO) def create_app() -> FastAPI: container = Container() container.wire(modules=[api]) application = FastAPI() application.container = container application.include_router(api.api_router) application.include_router(management.management_router) return application app = create_app()
{"/src/controllers/api.py": ["/src/configs/containers.py", "/src/services/redis_service.py"], "/src/services/redis_service.py": ["/src/configs/redis_datasource.py"], "/src/configs/config_client.py": ["/src/security/authenticator.py"], "/src/configs/containers.py": ["/src/services/redis_service.py", "/src/security/authenticator.py", "/src/configs/config_client.py", "/src/configs/redis_datasource.py"], "/src/app.py": ["/src/configs/containers.py"]}
55,432
amitesh080295/redis-lock
refs/heads/main
/src/security/authenticator.py
import json import base64 import requests import datetime import logging from environs import Env logger = logging.getLogger(__name__) class AuthenticationHandler: def __init__(self, env: Env): auth_username = env.str('oauth.username') auth_password = env.str('oauth.password') auth_credentials = auth_username + ':' + auth_password encoded_auth_credentials = (base64.b64encode(bytes(auth_credentials, 'utf-8'))).decode('utf-8') self.auth_token_url = env.url('auth.token.url') self.headers = dict(Authorization='Basic ' + encoded_auth_credentials) self.token = str() self.token_expiry_time = datetime.datetime.now() + datetime.timedelta(minutes=25) def get_auth_token(self): if datetime.datetime.now() > self.token_expiry_time or self.token == '': try: response = requests.get(self.auth_token_url, headers=self.headers) decoded_response = response.content.decode('UTF-8') if decoded_response is not None: jwt_token = json.loads(decoded_response).get('token') self.token = 'Bearer ' + jwt_token self.token_expiry_time = datetime.datetime.now() + datetime.timedelta(minutes=25) else: logger.error('No JWT token fetched') except Exception as exception: logger.error(f'Error in getting auth token {str(exception)}') raise return self.token
{"/src/controllers/api.py": ["/src/configs/containers.py", "/src/services/redis_service.py"], "/src/services/redis_service.py": ["/src/configs/redis_datasource.py"], "/src/configs/config_client.py": ["/src/security/authenticator.py"], "/src/configs/containers.py": ["/src/services/redis_service.py", "/src/security/authenticator.py", "/src/configs/config_client.py", "/src/configs/redis_datasource.py"], "/src/app.py": ["/src/configs/containers.py"]}
55,444
EddyEdzwan/sharingiscaring
refs/heads/master
/tests/test_tryme.py
from sharingiscaring.lib import try_me def test_tryme(): assert type(try_me()) == str
{"/tests/test_tryme.py": ["/sharingiscaring/lib.py"]}
55,445
EddyEdzwan/sharingiscaring
refs/heads/master
/sharingiscaring/lib.py
import os def try_me(): current_path = os.getcwd() print(current_path) return current_path
{"/tests/test_tryme.py": ["/sharingiscaring/lib.py"]}
55,457
Gnorbi951/Advent_of_code_2020_Day_1
refs/heads/main
/main.py
from file_reader import read_file_to_list def solve_dojo(): input_list = read_file_to_list("input.txt") for i in range(len(input_list)): for j in range(len(input_list)): if i == j: continue outer_number = input_list[i] inner_number = input_list[j] if outer_number + inner_number == 2020: print(f"The solution is {outer_number}+{inner_number}={outer_number * inner_number}") return (outer_number * inner_number) if __name__ == "__main__": solve_dojo()
{"/main.py": ["/file_reader.py"]}
55,458
Gnorbi951/Advent_of_code_2020_Day_1
refs/heads/main
/file_reader.py
def read_file_to_list(filename): input_file = open(filename, "r") input_list = [int(line.split('\n')[0]) for line in input_file] input_file.close() return input_list
{"/main.py": ["/file_reader.py"]}
55,466
tupini07/StyleTransfer
refs/heads/master
/stransfer/clis/gatys_st.py
import os import click from stransfer import c_logging, constants, img_utils, network LOGGER = c_logging.get_logger() @click.command() @click.argument('content-image-path') @click.argument('style-image-path') @click.option('-n', '--out-name', default='gatys_converted.png', help='The name of the result file (transformed image)') @click.option('-s', '--steps', default=300, help="How many iterations should the optimization go through.") @click.option('-cw', '--content-weight', default=1, help="The weight we will assign to the content loss during the optimization") @click.option('-sw', '--style-weight', default=100_000, help="The weight we will assign to the style loss during the optimization") def gatys_st(content_image_path, style_image_path, out_name, steps, content_weight, style_weight): """ Run the original Gatys style transfer (slow). Both `style-image` and `content-image` should be the paths to the image we want to take the content from and the one we want to take the style from (respectively). """ style_image_path = os.path.join(constants.PROJECT_ROOT_PATH, style_image_path) content_image_path = os.path.join(constants.PROJECT_ROOT_PATH, content_image_path) style_image = img_utils.image_loader(style_image_path) content_image = img_utils.image_loader(content_image_path) net = network.StyleNetwork(style_image, content_image) converted_image = net.train_gatys(style_image=style_image, content_image=content_image, style_weight=style_weight, content_weight=content_weight, steps=steps) out_dir = os.path.join(constants.PROJECT_ROOT_PATH, 'results') # ensure that the result directory exist os.makedirs(out_dir, exist_ok=True) out_file = os.path.join(out_dir, out_name) img_utils.imshow(converted_image, path=out_file) LOGGER.info('Done! Transformed image has been saved to: %s', out_file)
{"/stransfer/clis/gatys_st.py": ["/stransfer/__init__.py"], "/stransfer/__main__.py": ["/stransfer/clis/__init__.py"], "/stransfer/network.py": ["/stransfer/__init__.py"], "/stransfer/dataset.py": ["/stransfer/__init__.py"], "/stransfer/c_logging.py": ["/stransfer/__init__.py"], "/stransfer/clis/video_st.py": ["/stransfer/__init__.py"], "/stransfer/clis/fast_st.py": ["/stransfer/__init__.py"], "/stransfer/img_utils.py": ["/stransfer/__init__.py"]}
55,467
tupini07/StyleTransfer
refs/heads/master
/stransfer/clis/__init__.py
import click from stransfer.clis import video_st, fast_st, gatys_st @click.group(commands={ 'video_st': video_st.video_st, 'fast_st': fast_st.fast_st, 'gatys_st': gatys_st.gatys_st, }) def cli(): """ Style Transfer """ pass
{"/stransfer/clis/gatys_st.py": ["/stransfer/__init__.py"], "/stransfer/__main__.py": ["/stransfer/clis/__init__.py"], "/stransfer/network.py": ["/stransfer/__init__.py"], "/stransfer/dataset.py": ["/stransfer/__init__.py"], "/stransfer/c_logging.py": ["/stransfer/__init__.py"], "/stransfer/clis/video_st.py": ["/stransfer/__init__.py"], "/stransfer/clis/fast_st.py": ["/stransfer/__init__.py"], "/stransfer/img_utils.py": ["/stransfer/__init__.py"]}
55,468
tupini07/StyleTransfer
refs/heads/master
/stransfer/__main__.py
import colored_traceback from stransfer.clis import cli if __name__ == "__main__": colored_traceback.add_hook() cli(**{}, prog_name='stransfer') # suppress warning
{"/stransfer/clis/gatys_st.py": ["/stransfer/__init__.py"], "/stransfer/__main__.py": ["/stransfer/clis/__init__.py"], "/stransfer/network.py": ["/stransfer/__init__.py"], "/stransfer/dataset.py": ["/stransfer/__init__.py"], "/stransfer/c_logging.py": ["/stransfer/__init__.py"], "/stransfer/clis/video_st.py": ["/stransfer/__init__.py"], "/stransfer/clis/fast_st.py": ["/stransfer/__init__.py"], "/stransfer/img_utils.py": ["/stransfer/__init__.py"]}
55,469
tupini07/StyleTransfer
refs/heads/master
/stransfer/network.py
""" This module holds the implementation of all the networks, their losses, and their components """ import os import shutil import imageio import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision from PIL import Image from tensorboardX import SummaryWriter from tqdm import tqdm from stransfer import c_logging, constants, dataset, img_utils LOGGER = c_logging.get_logger() def get_tensorboard_writer(path: str) -> SummaryWriter: """ Creates a TensorBoard writer at the folder with `path`. If `path` exists then it is deleted and recreated. :param path: the path where our SummaryWriter will write :return: an initialized SummaryWriter """ shutil.rmtree(path, ignore_errors=True) return SummaryWriter(path) def adaptive_torch_load(weights_path: str): """ When loading saved weights, we check if need to map them to either `cuda` or `cpu`. :param weights_path: paths of the weights to load :return: the loaded weights """ if constants.DEVICE.type == "cuda": return torch.load(weights_path, map_location='cuda') else: return torch.load(weights_path, map_location='cpu') def _load_latest_model_weigths(model_name: str, style_name: str, models_path='data/models/'): """ :param models_path: path where the pretrained models are saved :return: the weights file for the latest epoch corresponding to the model and style specified. """ models_path = os.path.join(constants.PROJECT_ROOT_PATH, models_path) try: latest_weight_name = sorted([x for x in os.listdir(models_path) if x.startswith(model_name) and style_name in x])[-1] except IndexError: LOGGER.critical('There are no weights for the specified model name (%s) ' 'and style (%s). In the specified path: %s', model_name, style_name, models_path) raise AssertionError('There are no weights for the specified ' 'model name and style.') return adaptive_torch_load(models_path + latest_weight_name) class StyleLoss(nn.Module): """ Implementation of the style loss :param target: the tensor representing the style image we want to take as reference during training """ def __init__(self, target: torch.Tensor): super().__init__() self.set_target(target) def gram_matrix(self, input: torch.Tensor) -> torch.Tensor: """ Calculate the gram matrix for the `input` tensor """ # The size would be [batch_size, depth, height, width] bs, depth, height, width = input.size() features = input.view(bs, depth, height * width) features_t = features.transpose(1, 2) # compute the gram product G = torch.bmm(features, features_t) # we 'normalize' the values of the gram matrix # by dividing by the number of element in each feature maps. return G.div(depth * height * width) def forward(self, input: torch.Tensor) -> torch.Tensor: """ Compare the gram matrix of the `input` with that of the `target`. By doing this we calculate the style loss, which is saved to a local `loss` attribute. """ G = self.gram_matrix(input) self.loss = F.mse_loss(G, # correct the fact that we only have one # style image for the whole batch self.target.expand_as(G)) return input def set_target(self, target: torch.Tensor): """ This method allows us to change the style target of the loss """ # Here the target is the conv layer which we're taking as reference # as the style source self.target = self.gram_matrix(target).detach() class ContentLoss(nn.Module): """ Implementation of the content loss :param target: the target image we want to use to calculate the content loss """ def __init__(self, target: torch.Tensor): super().__init__() # Here the target is the conv layer which we're taking as reference # as the content source self.set_target(target) def set_target(self, target: torch.Tensor): """ This method allows us to set the target image of this content loss instance """ self.target = target.detach() def forward(self, input: torch.Tensor) -> torch.Tensor: """ Calculate the distance between the `input` image and the `target`. This is saved to a local `loss` attribute. """ # Content loss is just the per pixel distance between an input and # the target self.loss = F.mse_loss(input, self.target) return input class FeatureReconstructionLoss(nn.Module): """ Implementation of the feature reconstruction loss. ..note:: this loss is currently not used since it doesn't seem to provide much improvement over the normal :class:`.ContentLoss` """ def __init__(self, target: torch.Tensor): super().__init__() # Here the target is the conv layer which we're taking as reference # as the content source self.set_target(target) def set_target(self, target: torch.Tensor): self.target = target.detach() def forward(self, input: torch.Tensor) -> torch.Tensor: """ Get the feature loss of `input` with respect to the `target` """ # Content loss is just the per pixel distance between an input and # the target l2_norm = F.mse_loss(input, self.target) l2_squared = l2_norm.pow(2) # The size would be [batch_size, depth, height, width] bs, depth, height, width = input.size() self.loss = l2_squared.div(bs * depth * height * width) return input class StyleNetwork(nn.Module): """ Implementation of the StyleNetwork as defined in `A Neural Algorithm of Artistic Style - Gatys (2015) <https://arxiv.org/abs/1508.06576>`_ :param style_image: tensor of the image we want to use as a source for the style :param content_image: tensor of the image we want to use as the source for the content """ content_layers = [ # layers from where image content will be taken # 'Conv2d_1', # 'Conv2d_2', # 'Conv2d_3', 'Conv2d_4', # 'Conv2d_5', ] style_layers = [ # layers were the image style will be taken from 'Conv2d_1', 'Conv2d_2', 'Conv2d_3', 'Conv2d_4', 'Conv2d_5', ] feature_loss_layers = [ # layer for the feature loss 'ReLU_4', ] def __init__(self, style_image: torch.Tensor, content_image: torch.Tensor = None): super().__init__() self.content_losses = [] self.style_losses = [] self.feature_losses = [] if content_image is None: # set a dummy content image content_image = torch.zeros([1, 3, 256, 256]) # we use the vgg19 net to get the losses during training vgg = (torchvision.models.vgg19(pretrained=True) # we only want the `features` part of VGG19 (see print(vgg) for structure) .features .to(constants.DEVICE) .eval()) # by default we set the network to evaluation mode # separate the network in pieces. These are limited by the layers # specified in the `content_layers`, `style_layers`, and `feature_loss_layers` # Each piece is basically a sequential network self.net_pieces = [ nn.Sequential() ] loss_added = False current_piece = 0 i = 0 for layer in vgg: # for each layer in VGG, simply add it to the sequential net corresponding # to the layer we're currently working on (and give it an appropriate name) if isinstance(layer, nn.Conv2d): i += 1 if isinstance(layer, nn.ReLU): layer.inplace = False # one of {'Conv2d', 'MaxPool2d', 'ReLU'} layer_name = type(layer).__name__ + f"_{i}" self.net_pieces[current_piece].add_module(layer_name, layer) # if the layer is used to calculate the content, style, or feature losses then: # Save in the appropriate list the 'pointer' to the loss and the piece where # it belongs if layer_name in self.content_layers: # output of passing the `content_image` through all layers we've # processed until now layer_output = self.run_through_pieces(content_image) # calculate content loss content_loss = ContentLoss(layer_output) # save pointer to content loss in `self.content_losses` together # with the INDEX of the piece to which it corresponds self.content_losses.append([content_loss, current_piece]) # finally, say that a loss has been added so that the next iteration we # start with a new network piece loss_added = True # same is to be done for the style and feature losses if layer_name in self.style_layers: layer_output = self.run_through_pieces(style_image) style_loss = StyleLoss(layer_output) self.style_losses.append([style_loss, current_piece]) loss_added = True if layer_name in self.feature_loss_layers: layer_output = self.run_through_pieces(content_image) feature_loss = FeatureReconstructionLoss(layer_output) self.feature_losses.append([feature_loss, current_piece]) loss_added = True # If a loss has been added for the current layer then we say # that we're now working on a different piece if loss_added: self.net_pieces.append(nn.Sequential()) current_piece += 1 loss_added = False def run_through_pieces(self, input_g: torch.Tensor, until=-1) -> torch.Tensor: """ Runs ths input `input_g` through all the pieces of the network, or until the specified layer if `until` is not `-1` :param input_g: the input to run through the network :param until: by default `-1`. If changed then it specified until which layer we want to run the input through :return: the output of running the input through all the specified layers """ x = input_g # if no array of pieces is provided then we just run the input # through all pieces in the network if until == -1: pieces = self.net_pieces else: pieces = self.net_pieces[:until + 1] # finally run the input image through the pieces for piece in pieces: x = piece(x) return x def get_total_current_content_loss(self, weight=1) -> torch.Tensor: """ Returns the sum of all the `loss` present in all *content* nodes """ return weight * torch.stack([x[0].loss for x in self.content_losses]).sum() def get_total_current_feature_loss(self, weight=1) -> torch.Tensor: """ Returns the sum of all the `loss` present in all *content* nodes """ return weight * torch.stack([x[0].loss for x in self.feature_losses]).sum() def get_total_current_style_loss(self, weight=1) -> torch.Tensor: """ Returns the sum of all the `loss` present in all *style* nodes """ return weight * torch.stack([x[0].loss for x in self.style_losses]).sum() def forward(self, input_image: torch.Tensor, content_image=None, style_image=None) -> None: """ Given an input image pass it through all layers in the network :param input_image: the image to pass through the network :param content_image: if specified then this will change the curret target for the content loss :param style_image: if specified then this will change the current target for the style loss """ # first set content, feature, and style targets for (loss, piece_idx) in self.content_losses + self.feature_losses: if content_image is not None: loss.set_target( self.run_through_pieces(content_image, piece_idx) ) loss( self.run_through_pieces(input_image, piece_idx) ) # if we provide a style image to override the one # provided in the __init__ for (loss, piece_idx) in self.style_losses: if style_image is not None: loss.set_target( self.run_through_pieces(content_image, piece_idx) ) loss( self.run_through_pieces(input_image, piece_idx) ) # we don't need the network output, so there is no need to run # the input through the whole network def get_content_optimizer(self, input_img, optt=optim.Adam): # we want to apply the gradient to the content image, so we # need to mark it as such optimizer = optt([input_img.requires_grad_()]) return optimizer def train_gatys(self, style_image: torch.Tensor, content_image: torch.Tensor, steps=550, style_weight=100_000, content_weight=1) -> torch.Tensor: """ Creates a new image with the style of `style_image` and the content of `content_image` :return: the converted image """ assert isinstance( style_image, torch.Tensor), 'Images need to be already loaded' assert isinstance( content_image, torch.Tensor), 'Images need to be already loaded' # start from content image input_image = content_image.clone() # or start from random image # input_image = torch.randn( # content_image.data.size(), device=constants.DEVICE) optimizer = self.get_content_optimizer(input_image, optt=optim.LBFGS) for step in tqdm(range(steps)): def closure(): optimizer.zero_grad() # pass content image through net self(input_image, content_image) # get losses style_loss = self.get_total_current_style_loss( weight=style_weight) content_loss = self.get_total_current_content_loss( weight=content_weight) total_loss = style_loss + content_loss total_loss.backward() LOGGER.info('Loss: %s', total_loss) return total_loss optimizer.step(closure) return input_image class ResidualBlock(nn.Module): # based on the residual block implementation from: # https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/02-intermediate/deep_residual_network/main.py def __init__(self, in_channels, out_channels, kernel_size=3, stride=1): super().__init__() self.conv1 = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=kernel_size // 2, padding_mode='reflection') self.insn1 = nn.InstanceNorm2d(out_channels, affine=True) self.relu = nn.ReLU() self.conv2 = nn.Conv2d(in_channels=out_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=kernel_size // 2, padding_mode='reflection') self.insn2 = nn.InstanceNorm2d(out_channels, affine=True) def forward(self, x: torch.Tensor) -> torch.Tensor: """ Given a tensor input, pass it through the residual block, and return the output. """ # architecure of the residual block was taken from # Gross and Wilber (Training and investigating residual nets) # http://torch.ch/blog/2016/02/04/resnets.html residual = x out = self.conv1(x) out = self.insn1(out) out = self.relu(out) out = self.conv2(out) out += residual out = self.insn2(out) return out class ImageTransformNet(nn.Sequential): """ This the implementation of the fast style transform, image transform network, as defined in: `Perceptual Losses for Real-Time Style Transfer and Super-Resolution <https://arxiv.org/abs/1603.08155>`_ :param style_image: The image we want to use as as the style reference :param batch_size: the size of the batch """ def __init__(self, style_image: torch.Tensor, batch_size=4): super().__init__( # Initial convolutional layers # First Conv nn.Conv2d(in_channels=3, out_channels=32, kernel_size=9, stride=1, padding=9 // 2, padding_mode='reflection'), nn.InstanceNorm2d(num_features=32, affine=True), nn.ReLU(), # Second Conv nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=3 // 2, padding_mode='reflection'), nn.InstanceNorm2d(num_features=64, affine=True), nn.ReLU(), # Third Conv nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=2, padding=3 // 2, padding_mode='reflection'), nn.InstanceNorm2d(num_features=128, affine=True), nn.ReLU(), # * Residual blocks ResidualBlock(in_channels=128, out_channels=128, kernel_size=3), ResidualBlock(in_channels=128, out_channels=128, kernel_size=3), ResidualBlock(in_channels=128, out_channels=128, kernel_size=3), ResidualBlock(in_channels=128, out_channels=128, kernel_size=3), ResidualBlock(in_channels=128, out_channels=128, kernel_size=3), # Deconvolution layers # According to https://distill.pub/2016/deconv-checkerboard/ # an upsampling layer followed by a convolution layer # yields better results # First 'deconvolution' layer nn.Upsample(mode='nearest', scale_factor=2), nn.Conv2d(in_channels=128, out_channels=64, kernel_size=3, stride=1, padding=3 // 2, padding_mode='reflection'), nn.InstanceNorm2d(num_features=64, affine=True), nn.ReLU(), # Second 'deconvolution' layer nn.Upsample(mode='nearest', scale_factor=2), nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=3 // 2, padding_mode='reflection'), nn.InstanceNorm2d(num_features=32, affine=True), nn.ReLU(), # * Final convolutional layer nn.Conv2d(in_channels=32, out_channels=3, kernel_size=9, stride=1, padding=9 // 2, padding_mode='reflection'), ) # finally, set the style image which # transform network represents assert isinstance( style_image, torch.Tensor), 'Style image need to be already loaded' self.style_image = style_image self.batch_size = batch_size def get_total_variation_regularization_loss(self, transformed_image: torch.Tensor, regularization_factor=1e-6) -> torch.Tensor: """ Calculate a regularization loss, which will tell us how 'noisy' is the current image. Penalize if it is very noisy. See: https://en.wikipedia.org/wiki/Total_variation_denoising#2D_signal_images :param transformed_image: image for which we will get the loss :param regularization_factor: 'weight' to scale the loss :return: the regularization loss """ return regularization_factor * ( torch.sum(torch.abs( transformed_image[:, :, :, :-1] - transformed_image[:, :, :, 1:]) ) + torch.sum( torch.abs( transformed_image[:, :, :-1, :] - transformed_image[:, :, 1:, :]) )) def get_optimizer(self, optimizer=optim.Adam): """ Get an initialized optimizer """ params = self.parameters() return optimizer(params) def static_train(self, style_name='nsp', epochs=50, style_weight=100_000, content_weight=1): """ Trains a fast style transfer network for style transfer on still images. """ tb_writer = get_tensorboard_writer( f'runs/fast-image-style-transfer-still-image_{style_name}') # TODO: try adding the following so that grads are not computed # with torch.no_grad(): loss_network = StyleNetwork(self.style_image, torch.rand([1, 3, 256, 256]).to( constants.DEVICE)) optimizer = self.get_optimizer(optimizer=optim.Adam) LOGGER.info('Training network with "%s" optimizer', type(optimizer)) iteration = 0 test_loader, train_loader = dataset.get_coco_loader(test_split=0.10, test_limit=20, batch_size=self.batch_size) for epoch in range(epochs): LOGGER.info('Starting epoch %d', epoch) epoch_checkpoint_name = f'data/models/fast_st_{style_name}_epoch{epoch}.pth' # if the checkpoint file for this epoch exists then we # just load it and go over to the next epoch if os.path.isfile(epoch_checkpoint_name): self.load_state_dict( adaptive_torch_load(epoch_checkpoint_name) ) continue for batch in tqdm(train_loader): batch = batch.squeeze(1) def closure(): optimizer.zero_grad() transformed_image = self(batch) # evaluate how good the transformation is loss_network(transformed_image, content_image=batch) # Get losses style_loss = loss_network.get_total_current_style_loss( weight=style_weight ) # Feature loss doesn't seem to be much better than the normal # content loss # feature_weight = 1 # feature_loss = loss_network.get_total_current_feature_loss( # weight=feature_weight # ) content_loss = loss_network.get_total_current_content_loss( weight=content_weight ) regularization_loss = self.get_total_variation_regularization_loss( transformed_image ) # calculate loss total_loss = style_loss + content_loss + regularization_loss total_loss.backward() LOGGER.debug('Max of each channel: %s', [ x.max().item() for x in transformed_image[0].squeeze()]) LOGGER.debug('Min of each channel: %s', [ x.min().item() for x in transformed_image[0].squeeze()]) LOGGER.debug('Sum of each channel: %s', [ x.sum().item() for x in transformed_image[0].squeeze()]) LOGGER.debug('Closure loss: %.8f', total_loss) return total_loss if iteration % 20 == 0: total_loss = closure() tb_writer.add_scalar( 'data/fst_train_loss', total_loss, iteration) LOGGER.info('Batch Loss: %.8f', total_loss) if iteration % 150 == 0: average_test_loss = self.static_test( test_loader, loss_network) tb_writer.add_scalar( 'data/fst_test_loss', average_test_loss, iteration) if iteration % 50 == 0: transformed_image = torch.clamp( self(batch), # transform the image min=0, max=255 )[0] tb_writer.add_image('data/fst_images', img_utils.concat_images( transformed_image.squeeze(), batch[0].squeeze()), iteration) iteration += 1 # after processing the batch, run the gradient update optimizer.step(closure) torch.save( self.state_dict(), epoch_checkpoint_name ) def static_test(self, test_loader, loss_network, style_weight=100_000, feature_weight=1): """ Tests the performance of a fast style transfer network on still images """ total_test_loss = [] for test_batch in test_loader: transformed_image = torch.clamp( self(test_batch.squeeze(1)), # transfor the image min=0, max=255 ) loss_network(transformed_image, content_image=test_batch.squeeze(1)) style_loss = style_weight * loss_network.get_total_current_style_loss() feature_loss = feature_weight * loss_network.get_total_current_feature_loss() total_test_loss.append((style_loss + feature_loss).item()) average_test_loss = torch.mean(torch.Tensor(total_test_loss)) LOGGER.info('Average test loss: %.8f', average_test_loss) return average_test_loss def process_image(self, image_path: str, style_name='nsp', out_dir='results/') -> None: """ Processes a given input image at `image_path` with a network pretrained on the style `style_name`. Saves the processed image to `out_dir` :param image_path: path to the image we want to stylize :param style_name: name of the style we want to apply to the image. Note that a pretrained model with said style must exist in `data/models/` :param out_dir: directory were the stylized image will be saved """ # set weights to latest checkpoint self.load_state_dict( _load_latest_model_weigths( model_name='fast_st', style_name=style_name ) ) input_image = img_utils.image_loader( os.path.join(constants.PROJECT_ROOT_PATH, image_path)) # transform the image transformed_image = self(input_image) # save the image out_dir = os.path.join(constants.PROJECT_ROOT_PATH, out_dir) # ensure that the result directory exist os.makedirs(out_dir, exist_ok=True) out_file = os.path.join(out_dir, f'converted_fast_st_{style_name}.png') img_utils.imshow(transformed_image, path=out_file) class VideoTransformNet(ImageTransformNet): """ Implementation of the video transform net. :param style_image: image we'll use as style reference :param batch_size: size of the batch :param fast_transfer_dict: state dict from a pretrained 'fast style network'. It allows us to start training the video model from this, which allows to bootstrap training. It is recommended to do this since the current video set is not very big. """ def __init__(self, style_image: torch.Tensor, batch_size=4, fast_transfer_dict=None): super().__init__(style_image, batch_size) self[0] = nn.Conv2d(in_channels=6, out_channels=32, kernel_size=9, stride=1, padding=9 // 2, padding_mode='reflection') # since this video net is exactly the same as the ImageTransformNet # 'fast transfer' then we can reuse it's backup weights, already trained # on imagenet, for this task. if fast_transfer_dict is not None: # if 'fast_transfer_dict' is a string then we take it to be the path # to a dump of the weights. So we load it. if isinstance(fast_transfer_dict, str): fast_transfer_dict = adaptive_torch_load(fast_transfer_dict) # but first we have to remove the 'weight' and 'bias' for the first layer, # since this is the one we will be replacing in this 'VideoTransformNet' del fast_transfer_dict['0.weight'] del fast_transfer_dict['0.bias'] # update video net state dict so that we ensure we have # the correct weight/biases for the first layer m_sd = self.state_dict().copy() m_sd.update(fast_transfer_dict) # finally load weights into network self.load_state_dict(m_sd) # flag to use when training, to know if we've loaded # external weights or not self.has_external_weights = True else: self.has_external_weights = False def get_temporal_loss(self, old_content, old_stylized, current_content, current_stylized, temporal_weight=1) -> torch.Tensor: """ Calculates the temporal loss See https://github.com/tupini07/StyleTransfer/issues/5 :param old_content: tensor representing the content of the previous frame :param old_stylized: tensor representing the stylized previous frame :param current_content: tensor representing the content of the current frame :param current_stylized: tensor representing the stylized current frame :param temporal_weight: weight for the temporal loss :return: the temporal loss """ change_in_style = (current_stylized - old_stylized).norm() change_in_content = (current_content - old_content).norm() return (change_in_style / (change_in_content + 1)) * temporal_weight def video_train(self, style_name='nsp', epochs=50, temporal_weight=0.8, style_weight=100_000, feature_weight=1, content_weight=1) -> None: """ Trains the video network :param style_name: the name of the style (used for saving and loading checkpoints) :param epochs: how many epochs should the training go through :param temporal_weight: the weight for the temporal loss :param style_weight: the weight for the style loss :param feature_weight: the weight for the feature loss :param content_weight: the weight for the content loss :return: """ tb_writer = get_tensorboard_writer( f'runs/video-style-transfer_{style_name}') VIDEO_FOLDER = f'video_samples_{style_name}/' shutil.rmtree(VIDEO_FOLDER, ignore_errors=True) os.makedirs(VIDEO_FOLDER, exist_ok=True) # TODO: try adding the following so that grads are not computed # with torch.no_grad(): style_loss_network = StyleNetwork(self.style_image, torch.rand([1, 3, 256, 256]).to( constants.DEVICE)) optimizer = self.get_optimizer(optimizer=optim.Adam) LOGGER.info('Training video network with "%s" optimizer', type(optimizer)) iteration = 0 video_loader = dataset.VideoDataset(batch_size=self.batch_size) for epoch in range(epochs): # we freeze the 'external_weights' during the first epoch # if these are present if epoch == 0 and self.has_external_weights: LOGGER.info( 'Freezing weights imported from fast transfer network for the first epoch') for name, param in self.named_parameters(): # all layers which are not the first one if not name.startswith('0.'): param.requires_grad = False # next epoch we just 'unfreeze' all if epoch == 1 and self.has_external_weights: LOGGER.info('Unfreezing all weights') for param in self.parameters(): param.requires_grad = True epoch_checkpoint_name = f'data/models/video_st_{style_name}_epoch{epoch}.pth' # if the checkpoint file for this epoch exists then we # just load it and go over to the next epoch if os.path.isfile(epoch_checkpoint_name): self.load_state_dict( adaptive_torch_load(epoch_checkpoint_name) ) continue LOGGER.info('Starting epoch %d', epoch) for video_batch in video_loader: # of shape [content, stylized] old_images = None for batch in dataset.iterate_on_video_batches(video_batch): # if we're in new epoch then previous frame is None if old_images is None: old_images = [batch, batch] # ? make images available as simple vars old_content_images = old_images[0] old_styled_images = old_images[1] batch_with_old_content = torch.cat( [batch, old_styled_images], dim=1) def closure(): optimizer.zero_grad() transformed_image = self(batch_with_old_content) style_loss_network(transformed_image, content_image=batch) style_loss = style_loss_network.get_total_current_style_loss( weight=style_weight ) # feature weights don't seem to improve much the final results # feature_loss = style_loss_network.get_total_current_feature_loss( # weight=feature_weight # ) content_loss = style_loss_network.get_total_current_content_loss( weight=content_weight ) regularization_loss = self.get_total_variation_regularization_loss( transformed_image ) temporal_loss = self.get_temporal_loss( old_content_images, old_styled_images, batch, transformed_image, temporal_weight=temporal_weight ) # * agregate losses total_loss = style_loss + content_loss + regularization_loss + temporal_loss # * set old content and stylized versions old_images[0] = batch.detach() old_images[1] = transformed_image.detach() total_loss.backward() # * debug messages LOGGER.debug('Max of each channel: %s', [ x.max().item() for x in transformed_image[0].squeeze()]) LOGGER.debug('Min of each channel: %s', [ x.min().item() for x in transformed_image[0].squeeze()]) LOGGER.debug('Sum of each channel: %s', [ x.sum().item() for x in transformed_image[0].squeeze()]) LOGGER.debug('Closure loss: %.8f', total_loss) return total_loss if iteration % 20 == 0: total_loss = closure() tb_writer.add_scalar( 'data/fst_train_loss', total_loss, iteration) LOGGER.info('Epoch: %d\tBatch Loss: %.4f', epoch, total_loss) if iteration % 50 == 0: transformed_image = torch.clamp( self(batch_with_old_content), # transform the image min=0, max=255 )[2] tb_writer.add_image('data/fst_images', img_utils.concat_images( transformed_image.squeeze(), batch[2].squeeze()), iteration) iteration += 1 # after processing the batch, run the gradient update optimizer.step(closure) torch.save( self.state_dict(), epoch_checkpoint_name ) def process_video(self, video_path: str, style_name='nsp', working_dir='workdir/', out_dir='results/', fps=24.0): """ Applies style to a single video, using pretrained weights. Note that the weights must exist, if not an exception will be raised. :param video_path: the path of the video to stylize :param style_name: the name of the style to apply to the video. The weights for a video transform model using said style must exist in `data/models/` :param working_dir: directory where the transformed frames will be saved :param out_dir: directory where the final transformed video will be saved :param fps: the frames per second to use in the final video """ video_path = os.path.join(constants.PROJECT_ROOT_PATH, video_path) working_dir = os.path.join(constants.PROJECT_ROOT_PATH, working_dir) out_dir = os.path.join(constants.PROJECT_ROOT_PATH, out_dir) # set weights to latest checkpoint self.load_state_dict( _load_latest_model_weigths( model_name='video_st', style_name=style_name ) ) # we can treat this as a video batch of 1 video_reader = [imageio.get_reader(video_path)] # first we process each video frame, then we join those frames into # a final video # ensure that working_dir is empty shutil.rmtree(working_dir, ignore_errors=True) # ensure that the working and result directories exist os.makedirs(working_dir, exist_ok=True) os.makedirs(out_dir, exist_ok=True) # of shape [content, stylized] old_image = None LOGGER.info('Starting to process video into stylized frames') # Stylize all frames separately for i, video_frame in enumerate(dataset.iterate_on_video_batches(video_reader)): # if we're in new epoch then previous frame is None if old_image is None: old_image = video_frame batch_with_old_content = torch.cat( [video_frame, old_image], dim=1) # Get the transformed video image transformed_image = self(batch_with_old_content) # set old image variable old_image = transformed_image.detach() img_utils.imshow(transformed_image[0], path=f'{working_dir}{i}.png') if i % 50 == 0: LOGGER.info('.. processing, currently frame %d', i) # convert stylized frames into video LOGGER.info('All frames have been stylized.') final_path = os.path.join(out_dir, f'video_st_{style_name}.mp4') LOGGER.info('Joining stylized frames into a video') video_writer = imageio.get_writer(final_path, fps=fps) frame_files = sorted( os.listdir(working_dir), # cast frame index to int when sorting so that we actually get # the correct order key=lambda x: int(x.split('.')[0]) ) for frame_name in tqdm(frame_files): video_writer.append_data(np.array(Image.open(working_dir + frame_name))) LOGGER.info('Done! Final stylized video can be found in: %s', final_path)
{"/stransfer/clis/gatys_st.py": ["/stransfer/__init__.py"], "/stransfer/__main__.py": ["/stransfer/clis/__init__.py"], "/stransfer/network.py": ["/stransfer/__init__.py"], "/stransfer/dataset.py": ["/stransfer/__init__.py"], "/stransfer/c_logging.py": ["/stransfer/__init__.py"], "/stransfer/clis/video_st.py": ["/stransfer/__init__.py"], "/stransfer/clis/fast_st.py": ["/stransfer/__init__.py"], "/stransfer/img_utils.py": ["/stransfer/__init__.py"]}
55,470
tupini07/StyleTransfer
refs/heads/master
/stransfer/dataset.py
""" This module holds functionality related to dataset management. Both for downloading and iterating on the dataset. In the project we use 2 datasets: - COCO (for training the fast image transform net) - Some public videos (for training the Video style transfer net) """ import json import os import random from typing import Tuple, List, Any, Generator import imageio import requests import torch from PIL import Image from torch.utils.data import DataLoader, Dataset from tqdm import tqdm from stransfer import c_logging, img_utils LOGGER = c_logging.get_logger() # Where we'll place our coco dataset BASE_COCO_PATH = 'data/coco_dataset/' IMAGE_FOLDER_PATH = os.path.join(BASE_COCO_PATH, 'images') # Where we'll place our video dataset VIDEO_DATA_PATH = 'data/video/' def download_from_url(url: str, dst: str) -> int: """ :param url: to download file :param dst: place to put the file :return: the size of the downloaded file """ file_size = int(requests.head(url).headers["Content-Length"]) if os.path.exists(dst): first_byte = os.path.getsize(dst) else: first_byte = 0 if first_byte >= file_size: return file_size header = {"Range": "bytes=%s-%s" % (first_byte, file_size)} pbar = tqdm( total=file_size, initial=first_byte, unit='B', unit_scale=True, desc=url.split('/')[-1]) req = requests.get(url, headers=header, stream=True) with(open(dst, 'ab')) as f: for chunk in req.iter_content(chunk_size=1024): if chunk: f.write(chunk) pbar.update(1024) pbar.close() return file_size def download_list_of_urls(urls: List[str], destination_folder=VIDEO_DATA_PATH) -> None: """ Download a list of `urls` into `destination_folder` :param urls: list of urls to download :param destination_folder: the destination folder to which they will be downloaded :return: None """ name_counter = 0 for url in urls: try: filename = url.split('/')[-1] if len(filename) > 20: raise Exception except Exception: filename = f'{name_counter}.mp4' name_counter += 1 filepath = os.path.join(destination_folder, filename) download_from_url(url, filepath) def download_videos_dataset() -> None: """ Ensures that the videos in the video dataset have been downloaded :return: None """ videos_to_download = [ "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4", "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4", "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/Sintel.mp4", "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/TearsOfSteel.mp4" ] os.makedirs(VIDEO_DATA_PATH, exist_ok=True) # if we haven't downloaded all videos then just continue downloading if len(videos_to_download) != len(os.listdir(VIDEO_DATA_PATH)): download_list_of_urls(videos_to_download) def download_coco_images() -> None: """ Ensures that the coco dataset is downloaded :return: None """ json_file_path = os.path.join(BASE_COCO_PATH, 'image_info_test2017.json') images_urls = [x['coco_url'] for x in json.load(open(json_file_path, 'r'))['images']] os.makedirs(IMAGE_FOLDER_PATH, exist_ok=True) # if we haven't downloaded all images then just continue downloading if len(images_urls) != len(os.listdir(IMAGE_FOLDER_PATH)): download_list_of_urls(images_urls) def make_batches(l: List[Any], n: int) -> List[List[Any]]: """ Yield successive n-sized chunks from l. :param l: list of elements we want to convert into batches :param n: size of the batches :return: list of batches of elements """ batches = [] for i in range(0, len(l), n): batches.append(l[i:i + n]) return batches class CocoDataset(Dataset): """ An implementation of the :class:`torch.utils.data.Dataset` class, specific for the COCO dataset """ def __init__(self, images=None, image_limit=None): """ :param images: list of paths of images. If not specified then the images in `IMAGE_FOLDER_PATH` will be used. :param image_limit: the maximum amount of images we want to use """ if images is None: self.images = os.listdir(IMAGE_FOLDER_PATH) else: self.images = images if image_limit: try: self.images = self.images[:image_limit] except IndexError: LOGGER.warning('The provided image limit is larger than ' 'the actual image set. So will use the whole set') def __len__(self): return len(self.images) def __getitem__(self, idx): try: img_path = os.path.join(IMAGE_FOLDER_PATH, self.images[idx]) image = img_utils.image_loader(img_path) # if the image with the specified index doesn't have 3 channels # then we discard it # In the coco dataset there are some greyscale images (only one channel) if image.shape[1] != 3: LOGGER.warning('Discarding image with %d color channels', image.shape[1]) self.images.pop(idx) return self.__getitem__(idx) else: return image # catch if file is not image or if idx is out of bounds # TODO: might want to change this to catch proper exceptions (instead of generic Exception) except Exception: # not very pretty, but if above we're at the end of the # list then idx will be out of bounds. In that case just # return a random image from those that do exist return self.__getitem__(random.randint( 0, len(self.images) )) class VideoDataset: """ Dataset wrapper for the video dataset """ def __init__(self, videos=None, data_limit=None, batch_size=3): """ :param videos: list of paths of videos. If not specified then the videos in `VIDEO_DATA_PATH` will be used. :param data_limit: maximum amount of videos to use as part of the dataset :param batch_size: the batch size we will split our videos in """ # Ensure video have been downloaded download_videos_dataset() if videos is None: self.videos = os.listdir(VIDEO_DATA_PATH) else: self.videos = videos if data_limit: try: self.videos = self.videos[:data_limit] except IndexError: LOGGER.warning('The provided video limit is larger than ' 'the actual amount of videos in the video set. So will use the whole set') # set proper value for batch size if batch_size > len(self.videos): LOGGER.warning('The batch size is larger than the amount of videos in the ' f'video set. Will use complete set as a batch of size {len(self.videos)}') self.batch_size = len(self.videos) else: self.batch_size = batch_size # create video loaders for each video self.video_paths = [] for vid_name in self.videos: vid_path = os.path.join(VIDEO_DATA_PATH, vid_name) self.video_paths.append( vid_path ) # separate video loaders into batches self.video_paths = make_batches(self.video_paths, self.batch_size) # Throw away last batch if it is not the perfect batchsize length if len(self.video_paths[-1]) != self.batch_size: self.video_paths = self.video_paths[:-1] # vars for iterator management self.current_i = 0 def __len__(self): # number of batches return len(self.video_paths) def __iter__(self): return self def __next__(self): try: # we're iterating over batches of videos # so each iteration we get the batch corresponding to # `current_i` video_paths = self.video_paths[self.current_i] except IndexError: # once we reach the end of the list we stop # iteration self.current_i = 0 raise StopIteration self.current_i += 1 # for each video in the batch we return a video reader for said video return [imageio.get_reader(vp) for vp in video_paths] def iterate_on_video_batches(batch: List[imageio.core.format.Format.Reader], max_frames=90 * 24) -> Generator[torch.Tensor, None, None]: """ Generator that, given a list of video readers, will yield at each iteration a list composed of one frame from each video. :param batch: batch of video readers we want to iterate on :param max_frames: the maximum number of frames we want to yield. By default we limit to 90 seconds which is the same as 90*24 if the videos are 24 FPS """ try: for _ in range(max_frames): next_data = [] for video_reader in batch: frame = video_reader.get_next_data() # convert image to tensor image = Image.fromarray(frame) tensor = img_utils.image_loader_transform(image) # add to data we'll yield for the current batch next_data.append(tensor) # concatenate frames across their batch dimension and yield yield torch.cat(next_data, dim=0) # when one of the videos finishes imageio will # throw an IndexError when getting `get_next_data` except IndexError: pass def get_coco_loader(batch_size=4, test_split=0.10, test_limit=None, train_limit=None) -> Tuple[DataLoader, DataLoader]: """ Sets up and returns the dataloaders for the coco dataset :param batch_size: the amount of elements we want per batch :param test_split: the percentage of items from the whole set that we want to be part of the test set :param test_limit: the maximum amount of items we want in our test set :param train_limit: the maximum amount of items we want in the training set :return: the test set dataloader, and the train set dataloader """ # ensure that we have coco images download_coco_images() all_images = os.listdir(IMAGE_FOLDER_PATH) split_idx = int(len(all_images) * test_split) test_images = all_images[:split_idx] train_images = all_images[split_idx:] LOGGER.info('Loading train and test set') LOGGER.info('Train set has %d entries', len(train_images)) LOGGER.info('Test set has %d entries', len(test_images)) test_dataset = CocoDataset(images=test_images, image_limit=test_limit) train_dataset = CocoDataset(images=train_images, image_limit=train_limit) test_loader = DataLoader( test_dataset, batch_size=batch_size, num_workers=0, drop_last=True, shuffle=True ) train_loader = DataLoader( train_dataset, batch_size=batch_size, num_workers=0, drop_last=True, shuffle=True ) return test_loader, train_loader
{"/stransfer/clis/gatys_st.py": ["/stransfer/__init__.py"], "/stransfer/__main__.py": ["/stransfer/clis/__init__.py"], "/stransfer/network.py": ["/stransfer/__init__.py"], "/stransfer/dataset.py": ["/stransfer/__init__.py"], "/stransfer/c_logging.py": ["/stransfer/__init__.py"], "/stransfer/clis/video_st.py": ["/stransfer/__init__.py"], "/stransfer/clis/fast_st.py": ["/stransfer/__init__.py"], "/stransfer/img_utils.py": ["/stransfer/__init__.py"]}
55,471
tupini07/StyleTransfer
refs/heads/master
/stransfer/c_logging.py
""" This module contains functionality for logging. It mainly configures the log level and a handler so that logging can coexist with the `tqdm` progress bar. """ import logging import os import tqdm from stransfer import constants # Setup default logger for the application _LOGGER = logging.getLogger('StyleTransfer') # Set logging level _LOGGER.setLevel(logging.INFO) # clear handlers _LOGGER.handlers = [] LOGGER_FORMATTER = logging.Formatter( '%(asctime)s [%(levelname)s] %(module)s.%(funcName)s #%(lineno)d - %(message)s' ) class TqdmLoggingHandler(logging.StreamHandler): """ Custom logging handler. This ensures that TQDM progress bars always stay at the bottom of the terminal instead of being printed as normal messages """ def __init__(self, stream=None): super().__init__(stream) # we only overwrite `Logging.StreamHandler` # emit method def emit(self, record): try: msg = self.format(record) tqdm.tqdm.write(msg) self.flush() except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) tqdm_handler = TqdmLoggingHandler() tqdm_handler.setFormatter(LOGGER_FORMATTER) # we need to ensure that the runs_path exists since there is # where we'll save a log file of the execution os.makedirs(constants.RUNS_PATH, exist_ok=True) file_handler = logging.FileHandler(constants.LOG_PATH, mode='w+') file_handler.setFormatter(LOGGER_FORMATTER) _LOGGER.addHandler(tqdm_handler) _LOGGER.addHandler(file_handler) def get_logger() -> logging.Logger: """ :return: the global loader for the application """ return _LOGGER
{"/stransfer/clis/gatys_st.py": ["/stransfer/__init__.py"], "/stransfer/__main__.py": ["/stransfer/clis/__init__.py"], "/stransfer/network.py": ["/stransfer/__init__.py"], "/stransfer/dataset.py": ["/stransfer/__init__.py"], "/stransfer/c_logging.py": ["/stransfer/__init__.py"], "/stransfer/clis/video_st.py": ["/stransfer/__init__.py"], "/stransfer/clis/fast_st.py": ["/stransfer/__init__.py"], "/stransfer/img_utils.py": ["/stransfer/__init__.py"]}
55,472
tupini07/StyleTransfer
refs/heads/master
/stransfer/clis/video_st.py
import os import click import torch from stransfer import c_logging, constants, img_utils, network LOGGER = c_logging.get_logger() @click.group() def video_st(): """Video Style Transfer""" pass @video_st.command() @click.argument('style-image-path') @click.option('-e', '--epochs', default=50, help="How many epochs the training will take") @click.option('-b', '--batch-size', default=4, help="Batch size for training") @click.option('-cw', '--content-weight', default=1, help="The weight we will assign to the content loss during the optimization") @click.option('-sw', '--style-weight', default=100_000, help="The weight we will assign to the style loss during the optimization") @click.option('-tw', '--temporal-weight', default=0.8, help="The weight we will assign to the temporal loss during the optimization") @click.option('--use-pretrained-fast-st', is_flag=True, help='States whether we want to start training the video model from pretrained fast ' 'style transfer weights (which was trained on the same style name)') def train(style_image_path, epochs, batch_size, content_weight, style_weight, temporal_weight, use_pretrained_fast_st): """ Perform the training for the video style transfer network. A checkpoint will be created at the end of each epoch in the `data/models/` directory. We have the possibility of starting the training process for video style transfer from pretrained weights for a fast style transfer trained with the same `style name`. The weights that will be used are those of the highest epoch which correspond to that `style_name`. """ style_name = style_image_path.split("/")[-1] LOGGER.info('Training video style transfer network with style name: %s', style_name) ft_pretrained_w = None if use_pretrained_fast_st: LOGGER.info('Trying to load pretrained fast ST weights') try: ft_pretrained_w = network._load_latest_model_weigths('fast_st', style_name) except AssertionError: LOGGER.warning("Couldn't load pretrained weights") style_image_path = os.path.join(constants.PROJECT_ROOT_PATH, style_image_path) style_image = img_utils.image_loader(style_image_path) net = network.VideoTransformNet(style_image, batch_size, fast_transfer_dict=ft_pretrained_w) net.video_train(style_name=style_name, epochs=epochs, style_weight=style_weight, content_weight=content_weight, temporal_weight=temporal_weight) @video_st.command() @click.argument('video-path') @click.argument('style-name') @click.option('-o', '--out-dir', default='results/', help='The results directory where the converted style will be saved') @click.option('--fps', default=24.0, help='The FPS that will be used when saving the transformed video') def convert_video(video_path, style_name, out_dir, fps): """ Converts the video at `video-path` using the network pretrained with `style-name` and saves the resulting transformed video in `out-dir`. A pretrained model should exist in `data/models/` for the specified `style-name`. The files in `data/models/` contain the style names in their file names. For example, `video_st_starry_night_epoch3.pth` was trained with the style `starry_night` """ sty = network.VideoTransformNet(torch.rand([3, 255, 255])) sty.process_video(video_path=video_path, style_name=style_name, out_dir=out_dir, fps=fps)
{"/stransfer/clis/gatys_st.py": ["/stransfer/__init__.py"], "/stransfer/__main__.py": ["/stransfer/clis/__init__.py"], "/stransfer/network.py": ["/stransfer/__init__.py"], "/stransfer/dataset.py": ["/stransfer/__init__.py"], "/stransfer/c_logging.py": ["/stransfer/__init__.py"], "/stransfer/clis/video_st.py": ["/stransfer/__init__.py"], "/stransfer/clis/fast_st.py": ["/stransfer/__init__.py"], "/stransfer/img_utils.py": ["/stransfer/__init__.py"]}
55,473
tupini07/StyleTransfer
refs/heads/master
/stransfer/clis/fast_st.py
import os import click import torch from stransfer import c_logging, constants, img_utils, network LOGGER = c_logging.get_logger() @click.group() def fast_st(): """Fast Style Transfer""" pass @fast_st.command() @click.argument('style-image-path') @click.option('-e', '--epochs', default=50, help="How many epochs the training will take") @click.option('-b', '--batch-size', default=4, help="Batch size for training") @click.option('-cw', '--content-weight', default=1, help="The weight we will assign to the content loss during the optimization") @click.option('-sw', '--style-weight', default=100_000, help="The weight we will assign to the style loss during the optimization") def train(style_image_path, epochs, batch_size, content_weight, style_weight): """ Perform the training for the fast style transfer network. A checkpoint will be created at the end of each epoch in the `data/models/` directory. """ style_name = style_image_path.split("/")[-1] LOGGER.info('Training fast style transfer network with style name: %s', style_name) style_image_path = os.path.join(constants.PROJECT_ROOT_PATH, style_image_path) style_image = img_utils.image_loader(style_image_path) net = network.ImageTransformNet(style_image, batch_size) net.static_train(style_name=style_name, epochs=epochs, style_weight=style_weight, content_weight=content_weight) @fast_st.command() @click.argument('image-path') @click.argument('style-name') @click.option('-o', '--out-dir', default='results/', help='The results directory where the converted image will be saved') def convert_image(image_path, style_name, out_dir): """ Converts the image at `image-path` using the network pretrained with `style-name` and saves the resulting transformed image in `out-dir`. A pretrained model should exist in `data/models/` for the specified `style-name`. The files in `data/models/` contain the style names in their file names. For example, `fast_st_the_great_wave_epoch1.pth` was trained with the style `the_great_wave` """ sty = network.ImageTransformNet(torch.rand([3, 255, 255])) sty.process_image(image_path=image_path, style_name=style_name, out_dir=out_dir)
{"/stransfer/clis/gatys_st.py": ["/stransfer/__init__.py"], "/stransfer/__main__.py": ["/stransfer/clis/__init__.py"], "/stransfer/network.py": ["/stransfer/__init__.py"], "/stransfer/dataset.py": ["/stransfer/__init__.py"], "/stransfer/c_logging.py": ["/stransfer/__init__.py"], "/stransfer/clis/video_st.py": ["/stransfer/__init__.py"], "/stransfer/clis/fast_st.py": ["/stransfer/__init__.py"], "/stransfer/img_utils.py": ["/stransfer/__init__.py"]}
55,474
tupini07/StyleTransfer
refs/heads/master
/stransfer/img_utils.py
""" This module holds functionality related to loading and saving images. """ import torch from PIL import Image import matplotlib.pyplot as plt import torchvision.transforms as transforms from stransfer import constants def image_loader_transform(image: Image) -> torch.Tensor: """ Transform a PIL.Image instance into a torch.Tensor one. :param image: image to transform :return: torch.Tensor representing the image """ min_dimension = min(transforms.ToTensor()(image).shape[1:]) load_transforms = transforms.Compose([ # crop imported image to be sqaured (min between height and width) transforms.CenterCrop(min_dimension), transforms.Resize(constants.IMSIZE), # scale imported image transforms.ToTensor(), # transform it into a torch tensor ]) # fake batch dimension required to fit network's input dimensions image = load_transforms(image).unsqueeze(0) # normalize image with IMAGENET mean and std. img_mean = (torch.tensor(constants.IMAGENET_MEAN) .view(-1, 1, 1) .to(constants.DEVICE)) img_std = (torch.tensor(constants.IMAGENET_STD) .view(-1, 1, 1) .to(constants.DEVICE)) image = image.to(constants.DEVICE, torch.float) image = (image - img_mean) / img_std return image def concat_images(im1, im2, dim=2) -> torch.Tensor: """ Simple wrapper function that concatenates two images along a given dimension. :param im1: :param im2: :param dim: the dimension we want to concatenate across. By default it is the third dimension (width if images only have 3 dims) :return: tensor representing concatenated image """ return torch.cat([ im1, im2], dim=dim) def image_loader(image_path: str) -> torch.Tensor: """ Loads an image from `image_path`, and transforms it into a torch.Tensor :param image_path: path to the image that will be loaded :return: tensor representing the image """ image = Image.open(image_path) return image_loader_transform(image) def imshow(image_tensor: torch.Tensor, ground_truth_image: torch.Tensor = None, denormalize=True, path="out.bmp") -> None: """ Utility function to save an input image tensor to disk. :param image_tensor: the tensor representing the image to be saved :param ground_truth_image: another tensor, representing another image. If provided, it will be concatenated to the `image_tensor` across the width dimension and this result will be saved to disk :param denormalize: whether or not to denormalize (using IMAGENET mean and std) the tensor before saving it to disk. :param path: the path where the image will be saved """ # concat with ground truth if specified if ground_truth_image is not None: image_tensor = concat_images(image_tensor, ground_truth_image) if denormalize: # denormalize image img_mean = (torch.tensor(constants.IMAGENET_MEAN) .view(-1, 1, 1)) img_std = (torch.tensor(constants.IMAGENET_STD) .view(-1, 1, 1)) image_tensor = (image_tensor * img_std) + img_mean # clamp image to legal RGB values before showing image = torch.clamp( image_tensor.cpu().clone(), # we clone the tensor to not do changes on it min=0, max=255 ) image = image.squeeze(0) # remove the fake batch dimension, if any # concat with ground truth if any tpil = transforms.ToPILImage() image = tpil(image) image.save(path)
{"/stransfer/clis/gatys_st.py": ["/stransfer/__init__.py"], "/stransfer/__main__.py": ["/stransfer/clis/__init__.py"], "/stransfer/network.py": ["/stransfer/__init__.py"], "/stransfer/dataset.py": ["/stransfer/__init__.py"], "/stransfer/c_logging.py": ["/stransfer/__init__.py"], "/stransfer/clis/video_st.py": ["/stransfer/__init__.py"], "/stransfer/clis/fast_st.py": ["/stransfer/__init__.py"], "/stransfer/img_utils.py": ["/stransfer/__init__.py"]}
55,475
tupini07/StyleTransfer
refs/heads/master
/stransfer/__init__.py
from stransfer import c_logging, constants, dataset, img_utils, network __all__ = [ 'c_logging', 'constants', 'dataset', 'img_utils', 'network' ]
{"/stransfer/clis/gatys_st.py": ["/stransfer/__init__.py"], "/stransfer/__main__.py": ["/stransfer/clis/__init__.py"], "/stransfer/network.py": ["/stransfer/__init__.py"], "/stransfer/dataset.py": ["/stransfer/__init__.py"], "/stransfer/c_logging.py": ["/stransfer/__init__.py"], "/stransfer/clis/video_st.py": ["/stransfer/__init__.py"], "/stransfer/clis/fast_st.py": ["/stransfer/__init__.py"], "/stransfer/img_utils.py": ["/stransfer/__init__.py"]}
55,476
tupini07/StyleTransfer
refs/heads/master
/stransfer/constants.py
""" This module holds constant values used throughout the application """ import os import torch # where information of the runs will be saved. # both for the log of the run and for tensorboard results RUNS_PATH = 'runs/' LOG_PATH = os.path.join(RUNS_PATH, 'runtime.log') # used for normalizing and denormalizing input and output # images respectively IMAGENET_MEAN = [0.485, 0.456, 0.406] IMAGENET_STD = [0.229, 0.224, 0.225] # Always use cuda if available, but fallback to CPU if not. DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") if DEVICE.type == "cuda": torch.set_default_tensor_type(torch.cuda.FloatTensor) else: torch.set_default_tensor_type(torch.FloatTensor) # size of input images and output images # if input images are not IMSIZExIMSIZE then a square of size # IMSIZE will be cropped from the center of the image. IMSIZE = 256 PROJECT_ROOT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
{"/stransfer/clis/gatys_st.py": ["/stransfer/__init__.py"], "/stransfer/__main__.py": ["/stransfer/clis/__init__.py"], "/stransfer/network.py": ["/stransfer/__init__.py"], "/stransfer/dataset.py": ["/stransfer/__init__.py"], "/stransfer/c_logging.py": ["/stransfer/__init__.py"], "/stransfer/clis/video_st.py": ["/stransfer/__init__.py"], "/stransfer/clis/fast_st.py": ["/stransfer/__init__.py"], "/stransfer/img_utils.py": ["/stransfer/__init__.py"]}
55,480
Detry322/deeprole-proavalon
refs/heads/master
/keyvalue.py
import redis import ujson as json import os import functools @functools.lru_cache(maxsize=100) def get_key(key): return STORE._get(key) class RedisKV: def __init__(self): print("Using redis KV store") self.conn = redis.Redis.from_url(os.environ['REDIS_URL']) def exists(self, key): assert isinstance(key, str), "keys must be str" return self.conn.exists(key) == 1 def _get(self, key): assert isinstance(key, str), "keys must be str" value = self.conn.get(key) if value is None: raise ValueError("couldn't find {} in store".format(key)) return json.loads(value, precise_float=True) def get(self, key): return get_key(key) def set(self, key, value): assert isinstance(key, str), "keys must be str" value_json = json.dumps(value, double_precision=16) self.conn.set(key, value_json) def delete(self, key): assert isinstance(key, str), "keys must be str" self.conn.delete(key) def refcount_incr(self, key): assert isinstance(key, str), "keys must be str" key = "counter:" + key return self.conn.incr(key) def refcount_decr(self, key): assert isinstance(key, str), "keys must be str" key = "counter:" + key result = self.conn.decr(key) if result == 0: self.conn.delete(key) return result class LocalKV: def __init__(self): print("Using in-memory KV store") self.backing_store = {} def exists(self, key): assert isinstance(key, str), "keys must be str" return key in self.backing_store def _get(self, key): assert isinstance(key, str), "keys must be str" if key not in self.backing_store: raise ValueError("couldn't find {} in store".format(key)) return json.loads(self.backing_store[key], precise_float=True) def get(self, key): return get_key(key) def set(self, key, value): assert isinstance(key, str), "keys must be str" value_json = json.dumps(value, double_precision=16) self.backing_store[key] = value_json def delete(self, key): assert isinstance(key, str), "keys must be str" del self.backing_store[key] def refcount_incr(self, key): assert isinstance(key, str), "keys must be str" key = "counter:" + key self.backing_store[key] = self.backing_store.get(key, 0) + 1 return self.backing_store[key] def refcount_decr(self, key): assert isinstance(key, str), "keys must be str" key = "counter:" + key if key not in self.backing_store: raise ValueError("couldn't find {} in store".format(key)) result = self.backing_store[key] - 1 self.backing_store[key] = result if result == 0: del self.backing_store[key] return result if os.environ.get('PRODUCTION') is not None: STORE = RedisKV() else: STORE = LocalKV()
{"/game.py": ["/keyvalue.py", "/util.py", "/run.py"], "/deeprole.py": ["/util.py", "/keyvalue.py", "/game.py"], "/server.py": ["/debug.py", "/deeprole.py"], "/debug.py": ["/util.py"]}
55,481
Detry322/deeprole-proavalon
refs/heads/master
/game.py
import numpy as np import json import os from keyvalue import STORE from util import quickhash from run import run_deeprole def proposal_to_bitstring(proposal): result = 0 for p in proposal: result |= (1 << p) assert result < 32 return result def bitstring_to_proposal(bitstring): result = () i = 0 for i in range(5): if ((1 << i) & bitstring) != 0: result = result + (i, ) assert len(result) in [2, 3] return result def get_start_node(session_info): return { "type": "TERMINAL_PROPOSE_NN", "succeeds": 0, "fails": 0, "propose_count": 0, "proposer": session_info['starting_proposer'], "new_belief": list(np.ones(60)/60.0) } def terminal_propose_to_node_key(terminal_propose_node): assert terminal_propose_node['type'] == 'TERMINAL_PROPOSE_NN' return "node:" + quickhash({ 'succeeds': terminal_propose_node['succeeds'], 'fails': terminal_propose_node['fails'], 'propose_count': terminal_propose_node['propose_count'], 'proposer': terminal_propose_node['proposer'], 'belief': terminal_propose_node['new_belief'] }) def node_is_caught_up(node, game_info): phase = game_info['phase'] if node['type'] == 'TERMINAL_PROPOSE_NN': return False if node['type'].startswith('TERMINAL_'): return True if node['succeeds'] + node['fails'] + 1 < game_info['missionNum']: return False if node['type'] == 'PROPOSE': if phase != 'pickingTeam': return False return node['proposer'] == game_info['teamLeaderReversed'] elif node['type'] == 'VOTE': if phase != 'votingTeam': return False return node['proposer'] == game_info['teamLeaderReversed'] elif node['type'] == 'MISSION': return phase == 'votingMission' def replay_game_and_run_deeprole(session_info, game_info): current_node = get_start_node(session_info) updated_session = False while not node_is_caught_up(current_node, game_info): round_ = current_node['succeeds'] + current_node['fails'] if current_node['type'] == 'TERMINAL_PROPOSE_NN': next_node_key = terminal_propose_to_node_key(current_node) if not STORE.exists(next_node_key): current_node = run_deeprole(current_node) STORE.set(next_node_key, current_node) else: current_node = STORE.get(next_node_key) if next_node_key not in session_info['nodes_in_use']: session_info['nodes_in_use'].append(next_node_key) STORE.refcount_incr(next_node_key) updated_session = True elif current_node['type'] == 'PROPOSE': propose_count = current_node['propose_count'] leader = None proposal = [] for index, name in enumerate(session_info['players']): info = game_info['voteHistory'][name][round_][propose_count] if 'VHpicked' in info: proposal.append(index) if 'VHleader' in info: assert leader is None leader = index assert leader == current_node['proposer'] child_index = current_node['propose_options'].index(proposal_to_bitstring(proposal)) current_node = current_node['children'][child_index] elif current_node['type'] == 'VOTE': propose_count = current_node['propose_count'] proposal = bitstring_to_proposal(current_node['proposal']) for player in proposal: name = session_info['players'][player] assert 'VHpicked' in game_info['voteHistory'][name][round_][propose_count] leader_name = session_info['players'][current_node['proposer']] assert 'VHleader' in game_info['voteHistory'][leader_name][round_][propose_count] up_voters = [] for index, name in enumerate(session_info['players']): info = game_info['voteHistory'][name][round_][propose_count] if 'VHapprove' in info: up_voters.append(index) child_index = proposal_to_bitstring(up_voters) assert 0 <= child_index < 32 current_node = current_node['children'][child_index] elif current_node['type'] == 'MISSION': fails = game_info['numFailsHistory'][round_] current_node = current_node['children'][fails] if updated_session: STORE.set(session_info['session_id'], session_info) return current_node print(json.dumps(game_info, indent=2, sort_keys=2)) def get_move(phase, session_info, node): player = session_info['player'] perspective = session_info['perspective'] if phase == 'pickingTeam': assert node['type'] == 'PROPOSE' propose_strategy = node['propose_strat'][perspective] propose_options = node['propose_options'] index = np.random.choice(len(propose_strategy), p=propose_strategy) players = bitstring_to_proposal(propose_options[index]) return { 'buttonPressed': 'yes', 'selectedPlayers': [session_info['players'][p] for p in players] } elif phase == 'votingTeam': assert node['type'] == 'VOTE' vote_strategy = node['vote_strat'][player][perspective] vote_up = bool(np.random.choice(len(vote_strategy), p=vote_strategy)) return { 'buttonPressed': 'yes' if vote_up else 'no' } elif phase == 'votingMission': assert node['type'] == 'MISSION' if perspective < 7: return { 'buttonPressed': 'yes' } mission_strategy = node['mission_strat'][player][perspective] fail_mission = bool(np.random.choice(len(mission_strategy), p=mission_strategy)) return { 'buttonPressed': 'no' if fail_mission else 'yes' } elif phase == 'assassination': assert node['type'] == 'TERMINAL_MERLIN' merlin_strat = node['merlin_strat'][player][perspective] p = np.random.choice(len(merlin_strat), p=merlin_strat) return { 'buttonPressed': 'yes', 'selectedPlayers': [ session_info['players'][p] ] } else: assert False, "Can't handle this case"
{"/game.py": ["/keyvalue.py", "/util.py", "/run.py"], "/deeprole.py": ["/util.py", "/keyvalue.py", "/game.py"], "/server.py": ["/debug.py", "/deeprole.py"], "/debug.py": ["/util.py"]}
55,482
Detry322/deeprole-proavalon
refs/heads/master
/util.py
import os import functools import hashlib import json from flask import request from flask import current_app as app from flask_api import exceptions AUTH_KEY = os.environ.get('SECRET_AUTH_KEY') def require_auth_decorator(f): @functools.wraps(f) def decorated_func(*args, **kwargs): if not app.debug and request.headers.get('Authorization') != AUTH_KEY: raise exceptions.AuthenticationFailed(detail="API Key Incorrect") return f(*args, **kwargs) return decorated_func CAPABILITIES = [ { "numPlayers": [5], "cards": [], "roles": ['Resistance', 'Spy', 'Assassin', 'Merlin'] } ] def matches_capabilities(session_create): for capability in CAPABILITIES: if session_create["numPlayers"] not in capability["numPlayers"]: continue if not set(session_create["roles"]).issubset(set(capability["roles"])): continue # # Hacky code since deeprole needs both merlin and assassin # if 'Assassin' not in session_create['roles'] or 'Merlin' not in session_create['roles']: # continue if not set(session_create["cards"]).issubset(set(capability["cards"])): continue return True return False def get_missing_fields(obj, fields): return [field for field in fields if field not in obj.keys()] def quickhash(data): h = hashlib.md5(json.dumps(data, sort_keys=True).encode('utf-8')) return h.digest().hex()
{"/game.py": ["/keyvalue.py", "/util.py", "/run.py"], "/deeprole.py": ["/util.py", "/keyvalue.py", "/game.py"], "/server.py": ["/debug.py", "/deeprole.py"], "/debug.py": ["/util.py"]}
55,483
Detry322/deeprole-proavalon
refs/heads/master
/deeprole.py
import os from flask import Blueprint, request from util import require_auth_decorator, CAPABILITIES, get_missing_fields, matches_capabilities, quickhash from keyvalue import STORE from lookup_tables import get_deeprole_perspective from game import replay_game_and_run_deeprole, get_move from flask_api import exceptions import requests import json deeprole_app = Blueprint('deeprole', __name__) @deeprole_app.route('/v0/info', methods=['GET']) def get_info(): return { "name": "DeepRole", "chat": False, "capabilities": CAPABILITIES } @deeprole_app.route('/v0/session', methods=['POST']) @require_auth_decorator def create_session(): if not isinstance(request.data, dict): raise exceptions.ParseError('Data is not a json dict') missing_fields = get_missing_fields( request.data, ['numPlayers', 'roles', 'cards', 'teamLeader', 'players', 'name', 'role'] ) if len(missing_fields) != 0: raise exceptions.ParseError('Data is missing fields: {}'.format(missing_fields)) if not matches_capabilities(request.data): raise exceptions.ParseError("Bot can't handle these capabilities") num_players = request.data['numPlayers'] players = request.data['players'] name = request.data['name'] player = players.index(name) role = request.data['role'] spies = request.data.get('see', {}).get('spies', []) spies = [ players.index(spy) for spy in spies ] team_leader = request.data['teamLeader'] perspective = get_deeprole_perspective(player, role, spies) session_id = "session:" + os.urandom(10).hex() session_info = { 'session_id': session_id, 'num_players': num_players, 'name': name, 'player': player, 'players': players, 'starting_proposer': team_leader, 'perspective': perspective, 'nodes_in_use': [], } STORE.set(session_id, session_info) return { 'sessionID': session_id } @deeprole_app.route('/v0/session/act', methods=['POST']) @require_auth_decorator def get_action(): if not isinstance(request.data, dict): raise exceptions.ParseError('Data is not a json dict') missing_fields = get_missing_fields(request.data, ['sessionID', 'gameInfo']) if len(missing_fields) != 0: raise exceptions.ParseError('Data is missing fields: {}'.format(missing_fields)) game_info = request.data['gameInfo'] missing_fields = get_missing_fields(game_info, ['voteHistory', 'phase', 'teamLeader', 'pickNum']) if len(missing_fields) != 0: raise exceptions.ParseError('gameInfo is missing fields: {}'.format(missing_fields)) session_id = request.data['sessionID'] try: session_info = STORE.get(session_id) except ValueError: raise exceptions.NotFound('Could not find session ID: {}'.format(session_id)) current_node = replay_game_and_run_deeprole(session_info, game_info) return get_move(game_info['phase'], session_info, current_node) @deeprole_app.route('/v0/session/gameover', methods=['POST']) @require_auth_decorator def gameover(): if not isinstance(request.data, dict): raise exceptions.ParseError('Data is not a json dict') missing_fields = get_missing_fields(request.data, ['sessionID', 'gameInfo']) if len(missing_fields) != 0: raise exceptions.ParseError('Data is missing fields: {}'.format(missing_fields)) session_id = request.data['sessionID'] try: session_info = STORE.get(session_id) except ValueError: raise exceptions.NotFound('Could not find session ID: {}'.format(session_id)) for node_id in session_info['nodes_in_use']: new_count = STORE.refcount_decr(node_id) if new_count == 0: STORE.delete(node_id) STORE.delete(session_id) url = 'https://jserrino.scripts.mit.edu/datasink/index.py?auth_key={}'.format(os.environ.get('SECRET_AUTH_KEY')) r = requests.post(url, headers={ 'Content-Type': 'application/json' }, data=json.dumps({ 'session_info': session_info, 'game_info': request.data['gameInfo'] })) return r.json()
{"/game.py": ["/keyvalue.py", "/util.py", "/run.py"], "/deeprole.py": ["/util.py", "/keyvalue.py", "/game.py"], "/server.py": ["/debug.py", "/deeprole.py"], "/debug.py": ["/util.py"]}
55,484
Detry322/deeprole-proavalon
refs/heads/master
/server.py
from flask_api import FlaskAPI from debug import debug_app from deeprole import deeprole_app import os import markdown DIR = os.path.abspath(os.path.dirname(__file__)) app = FlaskAPI(__name__) app.config['DEFAULT_RENDERERS'] = [ 'flask_api.renderers.JSONRenderer', ] app.register_blueprint(debug_app, url_prefix='/debug') app.register_blueprint(deeprole_app, url_prefix='/deeprole') @app.route('/') def index(): with open(os.path.join(DIR, 'README.md'), 'r') as f: html = markdown.markdown(f.read()) return "<!doctype HTML><html><body>{}</body></html>".format(html) if __name__ == "__main__": import os os.environ['FLASK_ENV'] = 'development' app.run(debug=True)
{"/game.py": ["/keyvalue.py", "/util.py", "/run.py"], "/deeprole.py": ["/util.py", "/keyvalue.py", "/game.py"], "/server.py": ["/debug.py", "/deeprole.py"], "/debug.py": ["/util.py"]}
55,485
Detry322/deeprole-proavalon
refs/heads/master
/run.py
import subprocess import os import platform import json THINK_ITERATIONS = int(os.environ.get('THINK_ITERATIONS', 100)) WAIT_ITERATIONS = int(os.environ.get('WAIT_ITERATIONS', 50)) DIR = os.path.abspath(os.path.dirname(__file__)) BINARY = 'deeprole_darwin_avx' if platform.system() == 'Darwin' else 'deeprole_linux_avx' BINARY_PATH = os.path.join(DIR, 'bin', BINARY) MODEL_DIR = os.path.join(DIR, 'models') def run_deeprole(node): print("Running deeprole!") command = [ BINARY_PATH, '--play', '--proposer={}'.format(node['proposer']), '--succeeds={}'.format(node['succeeds']), '--fails={}'.format(node['fails']), '--propose_count={}'.format(node['propose_count']), '--depth=1', '--iterations={}'.format(THINK_ITERATIONS), '--witers={}'.format(WAIT_ITERATIONS), '--modeldir={}'.format(MODEL_DIR) ] process = subprocess.run( command, input=str(node['new_belief']) + "\n", text=True, capture_output=True ) result = json.loads(process.stdout) return result
{"/game.py": ["/keyvalue.py", "/util.py", "/run.py"], "/deeprole.py": ["/util.py", "/keyvalue.py", "/game.py"], "/server.py": ["/debug.py", "/deeprole.py"], "/debug.py": ["/util.py"]}
55,486
Detry322/deeprole-proavalon
refs/heads/master
/debug.py
from flask import Blueprint, request from flask import current_app as app from flask_api import exceptions import os import random from util import require_auth_decorator, CAPABILITIES, get_missing_fields, matches_capabilities debug_app = Blueprint('debug', __name__) SESSION_DATA = {} @debug_app.route('/v0/info', methods=['GET']) def get_info(): return { "name": "DebugRole", "chat": False, "capabilities": CAPABILITIES } @debug_app.route('/v0/session', methods=['POST']) @require_auth_decorator def create_session(): if not isinstance(request.data, dict): raise exceptions.ParseError('Data is not a json dict') missing_fields = get_missing_fields( request.data, ['numPlayers', 'roles', 'cards', 'teamLeader', 'players', 'name', 'role'] ) if len(missing_fields) != 0: raise exceptions.ParseError('Data is missing fields: {}'.format(missing_fields)) if not matches_capabilities(request.data): raise exceptions.ParseError("Bot can't handle these capabilities") sessionID = os.urandom(10).hex() SESSION_DATA[sessionID] = { 'sessionID': sessionID, 'creation_data': request.data, } return { 'sessionID': sessionID } @debug_app.route('/v0/session/act', methods=['POST']) @require_auth_decorator def bot_action(): if not isinstance(request.data, dict): raise exceptions.ParseError('Data is not a json dict') missing_fields = get_missing_fields(request.data, ['sessionID', 'gameInfo']) if len(missing_fields) != 0: raise exceptions.ParseError('Data is missing fields: {}'.format(missing_fields)) session_id = request.data['sessionID'] if session_id not in SESSION_DATA: raise exceptions.NotFound('Could not find session ID: {}'.format(session_id)) creation_data = SESSION_DATA[session_id]['creation_data'] game_data = request.data['gameInfo'] if game_data['phase'] == 'pickingTeam': num_players = int(game_data['numPlayersOnMission'][game_data['missionNum'] - 1]) return { 'buttonPressed': "yes", 'selectedPlayers': random.sample(creation_data['players'], num_players) } elif game_data['phase'] == 'votingTeam': return { 'buttonPressed': "yes" if random.random() < 0.5 else "no" } elif game_data['phase'] == 'votingMission': return { 'buttonPressed': "yes" if random.random() < 0.5 or game_data['alliance'] == "Resistance" else "no" } elif game_data['phase'] == 'assassination': return { 'buttonPressed': "yes", 'selectedPlayers': [ random.choice(creation_data['players']) ] } else: raise exceptions.ParseError("Invalid phase. Must be one of: pickingTeam, votingTeam, votingMission, assassination") @debug_app.route('/v0/session/gameover', methods=['POST']) @require_auth_decorator def gameover(): if not isinstance(request.data, dict): raise exceptions.ParseError('Data is not a json dict') missing_fields = get_missing_fields(request.data, ['sessionID', 'gameInfo']) if len(missing_fields) != 0: raise exceptions.ParseError('Data is missing fields: {}'.format(missing_fields)) session_id = request.data['sessionID'] if session_id not in SESSION_DATA: raise exceptions.NotFound('Could not find session ID: {}'.format(session_id)) del SESSION_DATA[session_id] return {}
{"/game.py": ["/keyvalue.py", "/util.py", "/run.py"], "/deeprole.py": ["/util.py", "/keyvalue.py", "/game.py"], "/server.py": ["/debug.py", "/deeprole.py"], "/debug.py": ["/util.py"]}
55,490
PLAZMAMA/IdeaCollector
refs/heads/main
/idea/__init__.py
default_app_config = 'idea.apps.IdeaConfig'
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,491
PLAZMAMA/IdeaCollector
refs/heads/main
/idea/admin.py
from django.contrib import admin from idea.models import IdeaModel class IdeaAdmin(admin.ModelAdmin): pass admin.site.register(IdeaModel, IdeaAdmin)
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,492
PLAZMAMA/IdeaCollector
refs/heads/main
/idea_collector/routing.py
from django.urls import path from idea.consumers import GetMostRecentIdea, GetRandomIdea, GetRandomIdeaChannels, GetMostRecentIdeasChannels ws_urlpatterns = [ path('ws/most_recent_ideas/', GetMostRecentIdea.as_asgi()), path('ws/get_random_idea/', GetRandomIdea.as_asgi()), path('ws/channels/most_recent_ideas/', GetRandomIdeaChannels.as_asgi()), path('ws/channels/get_random_idea/', GetMostRecentIdeasChannels.as_asgi()), ]
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,493
PLAZMAMA/IdeaCollector
refs/heads/main
/idea/tasks.py
from celery import shared_task from idea.models import IdeaModel from idea.serializers import IdeaSerializer from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from time import sleep from random import randint channel_layer = get_channel_layer() @shared_task(bind=True, autoretry_for=(Exception,), retry_kwargs={'max_retries': 3, 'countdown': 5}) def publish_most_recent_ideas(self, num_of_ideas=5): """gets the most recent "num_of_ideas" ideas""" queryset = IdeaModel.objects.all().order_by('-date_time')[:num_of_ideas] most_recent_ideas = IdeaSerializer(queryset, many=True) try: async_to_sync(channel_layer.group_send)('most_recent', {'type': 'send_most_recent', 'text': most_recent_ideas}) except Exception as e: raise Exception(f'no one is connected to the websocket connection but just in case, the function will run again(retry) in 5 seconds: {e}') @shared_task def get_random_idea(): """get a random idea""" queryset = IdeaModel.objects.all() random_idea = IdeaSerializer(queryset[randint(0, len(queryset)-1)]) async_to_sync(channel_layer.group_send)('random_idea', {'type': 'send_random_idea', 'text': random_idea})
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,494
PLAZMAMA/IdeaCollector
refs/heads/main
/idea/tests/test_views.py
from rest_framework.test import APITestCase, APIClient from idea.models import IdeaModel from idea_collector.settings import MEDIA_ROOT import json class TestIdea(APITestCase): def setUp(self): self.client = APIClient() def tearDown(self): IdeaModel.objects.all().delete() #get/list/retrieve def test_get(self): ideas = [IdeaModel.objects.create(title='test0', description='description0'), IdeaModel.objects.create(title='test1', description='description1')] #single byte_string = self.client.get(f'/ideas/{ideas[0].id}/').content response = json.loads(byte_string.decode()) self.assertEqual(ideas[0].title, response['title']) self.assertEqual(ideas[0].description, response['description']) #all byte_string = self.client.get('/ideas/').content response = json.loads(byte_string.decode()) for i in range(len(ideas)): self.assertEqual(ideas[i].title, response[i]['title']) self.assertEqual(ideas[i].description, response[i]['description']) #post/create def test_post(self): with open(f'{MEDIA_ROOT}/images/test_picture.jpeg', 'rb') as pic: byte_string = self.client.post('/ideas/', {"title": "test1", "description": "description1", "picture": pic}).content byte_string = byte_string.decode() uploaded_idea = IdeaModel.objects.get(id=json.loads(byte_string)['id']) self.assertEquals([uploaded_idea.title, uploaded_idea.description], ['test1', 'description1']) #put/update def test_put(self): idea = IdeaModel.objects.create(title='test1', description='description1', picture=None) with open(f'{MEDIA_ROOT}/images/test_picture.jpeg', 'rb') as pic: self.client.put(f'/ideas/{idea.id}/', {"title": "test2", "description": "description2", "picture": pic})#, content_type='multipart/form-data') changed_idea = IdeaModel.objects.get(id=idea.id) self.assertEqual(changed_idea.title, 'test2') self.assertEqual(changed_idea.description, 'description2') #delete/destroy def test_delete(self): idea = IdeaModel.objects.create(title='test1', description='description1') self.client.delete(f'/ideas/{idea.id}')
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,495
PLAZMAMA/IdeaCollector
refs/heads/main
/idea/migrations/0005_auto_20201116_0234.py
# Generated by Django 3.1.3 on 2020-11-16 02:34 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('idea', '0004_auto_20201104_0733'), ] operations = [ migrations.RenameModel( old_name='Idea', new_name='IdeaModel', ), ]
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,496
PLAZMAMA/IdeaCollector
refs/heads/main
/idea/migrations/0003_auto_20201015_2116.py
# Generated by Django 3.0.8 on 2020-10-15 21:16 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('idea', '0002_auto_20201012_1647'), ] operations = [ migrations.RenameField( model_name='idea', old_name='body', new_name='description', ), ]
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,497
PLAZMAMA/IdeaCollector
refs/heads/main
/idea_collector/asgi.py
""" ASGI config for idea_collector project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application #calling the asgi app so the following imports work django_asgi_app = get_asgi_application() from idea_collector.routing import ws_urlpatterns from channels.routing import ProtocolTypeRouter, ChannelNameRouter from channels.auth import AuthMiddlewareStack from channels.routing import URLRouter from idea.consumers import TaskConsumer os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'idea_collector.settings') application = ProtocolTypeRouter({ 'http': django_asgi_app, 'websocket': AuthMiddlewareStack(URLRouter(ws_urlpatterns)), 'channel': ChannelNameRouter({ 'task-consumer': TaskConsumer.as_asgi(), }) })
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,498
PLAZMAMA/IdeaCollector
refs/heads/main
/idea/apps.py
from django.apps import AppConfig class IdeaConfig(AppConfig): name = 'idea'
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,499
PLAZMAMA/IdeaCollector
refs/heads/main
/operator/idea_collector_operator.py
import kopf import pykube import yaml import inspect @kopf.on.create('idea-collectors') def idea_collector(body, **kwargs): deployment_configs = [ { 'name': 'web', 'replicas': body['spec']['web_app_replicas'], 'command': '["pipenv run python manage.py makemigrations && pipenv run python manage.py migrate && pipenv run daphne -p 8080 -b 0.0.0.0 idea_collector.asgi:application"]' }, { 'name': 'celery', 'replicas': body['spec']['celery_worker_replicas'], 'command': '["pipenv run celery -A idea_collector worker --loglevel=INFO"]' }, ] api = pykube.HTTPClient(pykube.KubeConfig.from_file()) for deployment_config in deployment_configs: deployment_data = yaml.full_load(f""" apiVersion: apps/v1 kind: Deployment metadata: name: idea-collector-{deployment_config['name']} labels: app: idea-collector-{deployment_config['name']} spec: replicas: {deployment_config['replicas']} selector: matchLabels: app: idea-collector-{deployment_config['name']} template: metadata: labels: app: idea-collector-{deployment_config['name']} spec: containers: - name: idea-collector-{deployment_config['name']} image: maorc112/idea_collector_web:latest command: args: {deployment_config['command']} ports: - containerPort: 8080 env: - name: POSTGRESQLUSERNAME valueFrom: secretKeyRef: name: postgres-redis-credentials key: username - name: POSTGRESQLPASSWORD valueFrom: secretKeyRef: name: postgres-redis-credentials key: password - name: POSTGRESQLHOST valueFrom: secretKeyRef: name: postgres-redis-credentials key: host - name: REDIS_URL valueFrom: secretKeyRef: name: postgres-redis-credentials key: redis_url """) deployment = pykube.Deployment(api, deployment_data) deployment.create() @kopf.on.update('idea-collectors') def update_idea_colletor(body, **kwargs): pass
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,500
PLAZMAMA/IdeaCollector
refs/heads/main
/idea/views.py
from rest_framework.viewsets import ModelViewSet from idea.models import IdeaModel from idea.serializers import IdeaSerializer from idea.tasks import publish_most_recent_ideas from idea_collector.celery import app from idea_collector.settings import DEBUG class IdeaViewSet(ModelViewSet): queryset = IdeaModel.objects.all() serializer_class = IdeaSerializer def create(self, request, *args, **kwargs): if not(DEBUG): publish_most_recent_ideas.delay() return super().create(request, args, kwargs) def update(self, request, *args, **kwargs): if not(DEBUG): publish_most_recent_ideas().delay() return super().update(request, args, kwargs) def delete(self, request, *args, **kwargs): if not(DEBUG): publish_most_recent_ideas().delay() return super().delete(request, args, kwargs)
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,501
PLAZMAMA/IdeaCollector
refs/heads/main
/idea/migrations/0004_auto_20201104_0733.py
# Generated by Django 3.1.2 on 2020-11-04 07:33 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('idea', '0003_auto_20201015_2116'), ] operations = [ migrations.AlterField( model_name='idea', name='picture', field=models.ImageField(null=True, upload_to='images'), ), ]
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,502
PLAZMAMA/IdeaCollector
refs/heads/main
/idea/management/commands/list_ids.py
from django.core.management.base import BaseCommand from idea.models import Idea class Command(BaseCommand): def handle(self, *args, **options): for idea in Idea.objects.all(): print(idea)
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,503
PLAZMAMA/IdeaCollector
refs/heads/main
/idea/migrations/0006_auto_20201212_0245.py
# Generated by Django 3.1.3 on 2020-12-12 02:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('idea', '0005_auto_20201116_0234'), ] operations = [ migrations.AlterField( model_name='ideamodel', name='description', field=models.TextField(max_length=512, null=True), ), migrations.AlterField( model_name='ideamodel', name='title', field=models.CharField(max_length=128, null=True), ), ]
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,504
PLAZMAMA/IdeaCollector
refs/heads/main
/idea/consumers.py
from channels.generic.websocket import AsyncJsonWebsocketConsumer from channels.consumer import AsyncConsumer from idea.tasks import publish_most_recent_ideas from idea.serializers import IdeaSerializer from idea.models import IdeaModel from idea_collector.celery import app from asgiref.sync import async_to_sync from random import randint from asyncio import sleep #uses the celery for its workers class GetMostRecentIdea(AsyncJsonWebsocketConsumer): async def connect(self): await self.channel_layer.group_add('most_recent', self.channel_name) await self.accept() publish_most_recent_ideas.delay() async def disconnect(self): await self.channel_layer.group_discard('most_recent', self.channel_name) async def send_most_recent_idea(self, event): most_recent_ideas = [[idea.title, idea.description] for idea in event['text']] await self.send_json({'data': most_recent_ideas}) #uses the celery for its workers class GetRandomIdea(AsyncJsonWebsocketConsumer): async def connect(self): await self.channel_layer.group_add('random_idea', self.channel_name) await self.accept() async def disconnect(self): await self.channel_layer.group_discard('random_idea', self.channel_name) async def send_random_idea(self, event): random_idea = [event['text'].title, event['text'].description] await self.send_json({'data': random_idea}) #uses the built in channels worker for its workers class GetMostRecentIdeasChannels(AsyncJsonWebsocketConsumer): async def connect(self): await self.channel_layer.group_add('most_recent_channels', self.channel_name) await self.accept() await self.channel_layer.send('task-consumer', {'type': 'publish_most_recent_ideas'}) async def disconnect(self): await self.channel_layer.group_discard('most_recent_channels', self.channel_name) async def send_most_recent(self, event): most_recent_ideas = [[idea.title, idea.description] for idea in event['text']] await self.send_json({'data': most_recent_ideas}) #uses the built in channels worker for its workers class GetRandomIdeaChannels(AsyncJsonWebsocketConsumer): async def connect(self): await self.channel_layer.group_add('random_idea_channels', self.channel_name) await self.accept() await self.get_random_idea() async def disconnect(self): await self.channel_layer.group_discard('random_idea_channels', self.channel_name) async def send_random_idea(self, event): random_idea = [event['text'].title, event['text'].description] await self.send_json({'data': random_idea}) async def get_random_idea(self, sleep_time=5): while(True): await sleep(sleep_time) await self.channel_layer.send('task-consumer', {'type': 'publish_random_idea'}) #used in the worker instance class TaskConsumer(AsyncConsumer): async def publish_most_recent_ideas(self, num_of_ideas=5): queryset = IdeaModel.objects.all().order_by('-date_time')[:num_of_ideas] most_recent_ideas = IdeaSerializer(queryset, many=True) try: await self.channel_layer.group_send('most_recent_channels', {'type': 'send_most_recent', 'text': most_recent_ideas}) except Exception as e: await sleep(5) await self.channel_layer.send('task-consumer', {'type': 'publish_random_idea'}) raise Exception(f'no one is connected to the websocket connection but just in case, the function is runing again(retry): {e}') async def publish_random_idea(self): queryset = IdeaModel.objects.all() random_idea = IdeaSerializer(queryset[randint(0, len(queryset)-1)]) await self.channel_layer.group_send('random_idea_channels', {'type': 'send_random_idea', 'text': random_idea})
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,505
PLAZMAMA/IdeaCollector
refs/heads/main
/idea/urls.py
from django.urls import path, register_converter, re_path from idea.views import IdeaViewSet from rest_framework import routers router = routers.SimpleRouter() router.register('', IdeaViewSet) urlpatterns = router.urls
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,506
PLAZMAMA/IdeaCollector
refs/heads/main
/idea_collector/celery.py
import os from celery import Celery #set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'idea_collector.settings') #build celery app and get the created tasks app = Celery('idea_collector') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.beat_schedule = { 'get_random_idea': { 'task': 'tasks.get_random_idea', 'schedule': 5.0 } } @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}')
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,507
PLAZMAMA/IdeaCollector
refs/heads/main
/idea/models.py
from django.db import models from datetime import datetime class IdeaModel(models.Model): title = models.CharField(max_length=128, null=True) description = models.TextField(max_length=512, null=True) picture = models.ImageField(upload_to=f'images', null=True) date_time = models.DateTimeField(auto_now_add=True, null=True, blank=True) def __str__(self): return f'{self.pk}, {self.title}, {self.description}, {self.picture}'
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,508
PLAZMAMA/IdeaCollector
refs/heads/main
/idea/management/commands/create_idea.py
from django.core.management.base import BaseCommand from idea.models import Idea class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('-t', '--title', type=str, help='title of the idea', required=True) parser.add_argument('-b', '--body', type=str, help='body of the idea', required=True) def handle(self, *args, **options): idea = Idea.objects.create(title=options['title'], body=options['body']) #idea = Idea() #idea.title = options['title'] #idea.body = options['body'] #idea.save()
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,509
PLAZMAMA/IdeaCollector
refs/heads/main
/idea/forms.py
from django import forms from idea.models import IdeaModel #class IdeaForm(forms.Form): # title = forms.CharField(max_length=150) # description = forms.CharField(max_length=10000) # picture = forms.ImageField(required=False, allow_empty_file=True) class IdeaForm(forms.ModelForm): class Meta: model = IdeaModel fields = ['title', 'description', 'picture']
{"/idea/admin.py": ["/idea/models.py"], "/idea_collector/routing.py": ["/idea/consumers.py"], "/idea/tasks.py": ["/idea/models.py"], "/idea/tests/test_views.py": ["/idea/models.py"], "/idea_collector/asgi.py": ["/idea_collector/routing.py", "/idea/consumers.py"], "/idea/views.py": ["/idea/models.py", "/idea/tasks.py", "/idea_collector/celery.py"], "/idea/management/commands/list_ids.py": ["/idea/models.py"], "/idea/consumers.py": ["/idea/tasks.py", "/idea/models.py", "/idea_collector/celery.py"], "/idea/urls.py": ["/idea/views.py"], "/idea/management/commands/create_idea.py": ["/idea/models.py"], "/idea/forms.py": ["/idea/models.py"]}
55,541
itgsodbojo/helloflask
refs/heads/master
/helloflask/views.py
from flask import render_template from helloflask import app from version import version @app.route('/') def hello_flask(): return render_template("index.html",version=version)
{"/helloflask/views.py": ["/helloflask/__init__.py"]}
55,542
itgsodbojo/helloflask
refs/heads/master
/setup.py
#!/usr/bin/env python import os from setuptools import setup ROOT_DIR = os.path.dirname(__file__) SOURCE_DIR = os.path.join(ROOT_DIR) exec(open('helloflask/version.py').read()) with open('./requirements.txt') as reqs_txt: requirements = [line for line in reqs_txt] setup( name="helloflask", version=version, description="helloflask testing deployment", packages=['helloflask'], include_package_data=True, install_requires=requirements, zip_safe=False, test_suite='tests', classifiers=[ 'Development Status :: Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Topic :: Education :: Testing', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', ], )
{"/helloflask/views.py": ["/helloflask/__init__.py"]}
55,543
itgsodbojo/helloflask
refs/heads/master
/helloflask/__init__.py
from flask import Flask app = Flask(__name__) from helloflask import views
{"/helloflask/views.py": ["/helloflask/__init__.py"]}
55,545
blacksadhorse/metric_client
refs/heads/master
/metric_client/__init__.py
from __future__ import absolute_import from .client import MetricClient VERSION = (0, 0, 1) __version__ = '.'.join(map(str, VERSION)) __all__ = ['MetricClient']
{"/metric_client/__init__.py": ["/metric_client/client.py"]}
55,546
blacksadhorse/metric_client
refs/heads/master
/metric_client/client.py
from __future__ import with_statement import sys import zerorpc import threading from zerorpc.exceptions import LostRemote, TimeoutExpired class MetricSingleton(type): _instance = {} """ Metric Client Singelton Class Implementation """ def __call__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(MetricSingleton, cls).__call__( *args) return cls._instance class MetricClient(object): def __init__(self, host="127.0.0.1", port="13375"): if host != "" and port != "": self.sock = zerorpc.Client() self.sock.connect("tcp://{0}:{1}".format(host, port)) else: raise SyntaxError def push(self, obj, value=False): """Set a set value.""" try: self.sock.commit(obj, value) except (LostRemote, TimeoutExpired): e = sys.exc_info() print(e)
{"/metric_client/__init__.py": ["/metric_client/client.py"]}
55,547
blacksadhorse/metric_client
refs/heads/master
/setup.py
import os, sys, glob from setuptools import setup from glob import glob def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="metric_client", version="0.0.1", author="Mike Nilson", author_email="mike@blacksadhorse.com", description="UDP metric client pusher", license="BSD", keywords="metrica", url="http://blacksadhorse.com", packages=['metric_client'], install_requires=[ 'zerorpc' ], include_package_data=True, long_description=read('README'), classifiers=[ "Development Status :: 0 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: BSD License", ], )
{"/metric_client/__init__.py": ["/metric_client/client.py"]}
55,551
Gauravdarkslayer/school_project_demo
refs/heads/main
/test_gen_webapp/authentication/views.py
from django.shortcuts import render from .models import user from django.http import HttpResponseRedirect # Create your views here. # def login_page(request): # return render(request,'signin.html') def login(request): if request.method.lower() == "post": email = request.POST["email"] password= request.POST["password"] print(request.POST["email"],request.POST["password"]) if user.objects.filter(email_id=email).exists(): print(user.objects.filter(email_id=email).values('password')[0]['password']) if user.objects.filter(email_id=email).values('password')[0]['password'] == password: print("ot hgere") return HttpResponseRedirect('/test_gen/') else: return render(request,"signin.html",{"message":"invalid credentials"}) else: return render(request,"signin.html",{"message":"doesnt exists"}) else: return render(request,'signin.html') def signup_page(request): return render(request,"signup.html") def signup(request): full_name = request.POST["full_name"] email = request.POST["emailid"] password= request.POST["password"] print("I am inside down") if user.objects.filter(email_id=email).exists(): print("alreay exists") return render(request,"signup.html",{"message":"already exists"}) user.objects.create(full_name=full_name, email_id=email,password=password) return render(request,"signin.html") def choose(request): return render(request,"choose.html") def homepage(request): return render(request, 'index.html')
{"/test_gen_webapp/authentication/views.py": ["/test_gen_webapp/authentication/models.py"], "/test_gen_webapp/authentication/urls.py": ["/test_gen_webapp/authentication/views.py"], "/test_gen_webapp/test_gen/views.py": ["/test_gen_webapp/test_gen/models.py"], "/test_gen_webapp/test_gen/urls.py": ["/test_gen_webapp/test_gen/views.py"]}
55,552
Gauravdarkslayer/school_project_demo
refs/heads/main
/test_gen_webapp/authentication/models.py
from django.db import models # Create your models here. roles = (("stu","student"),("org","organization"),("schl","school")) class user(models.Model): user_id = models.AutoField(primary_key=True) full_name= models.CharField(max_length=100) email_id = models.EmailField(unique=True) password = models.CharField(max_length=500) role = models.CharField(choices=roles,max_length=50,blank=True)
{"/test_gen_webapp/authentication/views.py": ["/test_gen_webapp/authentication/models.py"], "/test_gen_webapp/authentication/urls.py": ["/test_gen_webapp/authentication/views.py"], "/test_gen_webapp/test_gen/views.py": ["/test_gen_webapp/test_gen/models.py"], "/test_gen_webapp/test_gen/urls.py": ["/test_gen_webapp/test_gen/views.py"]}
55,553
Gauravdarkslayer/school_project_demo
refs/heads/main
/test_gen_webapp/test_gen/apps.py
from django.apps import AppConfig class TestGenConfig(AppConfig): name = 'test_gen'
{"/test_gen_webapp/authentication/views.py": ["/test_gen_webapp/authentication/models.py"], "/test_gen_webapp/authentication/urls.py": ["/test_gen_webapp/authentication/views.py"], "/test_gen_webapp/test_gen/views.py": ["/test_gen_webapp/test_gen/models.py"], "/test_gen_webapp/test_gen/urls.py": ["/test_gen_webapp/test_gen/views.py"]}
55,554
Gauravdarkslayer/school_project_demo
refs/heads/main
/test_gen_webapp/authentication/urls.py
from django.conf.urls import include from django.urls import path from .views import * urlpatterns = [ path('choose/',choose), path('signup/',signup), path('login/',login), path('signup_page/',signup_page), path('',homepage), ]
{"/test_gen_webapp/authentication/views.py": ["/test_gen_webapp/authentication/models.py"], "/test_gen_webapp/authentication/urls.py": ["/test_gen_webapp/authentication/views.py"], "/test_gen_webapp/test_gen/views.py": ["/test_gen_webapp/test_gen/models.py"], "/test_gen_webapp/test_gen/urls.py": ["/test_gen_webapp/test_gen/views.py"]}
55,555
Gauravdarkslayer/school_project_demo
refs/heads/main
/test_gen_webapp/test_gen/views.py
from django.shortcuts import render from django.http import HttpResponse from .models import organization_test_create from django.contrib import messages from django.conf import settings # Create your views here. def show_doc_upload_page(request): return render(request,'doc_upload_1.html') def register_new_org(request): return render(request, 'register_org.html') def doc_processing(request): file = request.FILES["mydocument"] print(request.FILES) print("this is file object",file) # current_user_email = request.session["email"] import docx try: doc = docx.Document('file.docx') print("success") except Exception as e: print(e) doc = docx.Document(file) print("this works") questionnaire={} explanation={} diagram={} fill_blanks = {} i=1 number_of_iterations = 0 for content in doc.paragraphs: if ("Q"+str(i) or "QUESTION"+str(i)) in content.text.upper(): print(content.text) # questionnaire["question"+str(i)] = content.text questionnaire[content.text] =[] i=i+1 j=1 for option in doc.paragraphs: # print("this is option",option.text.upper()) if "OPTION"+" "+str(j) in option.text.upper(): print("check") questionnaire[content.text].append(option.text) j= j+1 if "ANSWER" in option.text.upper(): print("get answer") questionnaire[content.text].append(option.text) break elif ('fill in the blanks') in content.text.lower(): print("I am inside Fill in the Blanks") fill_blanks[content.text] = [] next_index = number_of_iterations+1 for i in range(next_index, len(doc.paragraphs)): if "_" in doc.paragraphs[i].text: fill_blanks[content.text].append(doc.paragraphs[i].text) elif " " == doc.paragraphs[i].text: continue else: break elif("explain") in content.text.lower(): explanation[content.text]=[] next_index = number_of_iterations+1 for i in range(next_index, len(doc.paragraphs)): if "Write" in doc.paragraphs[i].text: explanation[content.text].append(doc.paragraphs[i].text) elif " " == doc.paragraphs[i].text: continue else: break elif("draw") in content.text.lower(): diagram[content.text]=[] next_index = number_of_iterations+1 for i in range(next_index, len(doc.paragraphs)): if "diagram" in doc.paragraphs[i].text: diagram[content.text].append(doc.paragraphs[i].text) elif " " == doc.paragraphs[i].text: continue else: break print("Explanation",explanation) print("Diagram",diagram) print("Data of Fill in the blanks is ", fill_blanks) number_of_iterations += 1 print(questionnaire) return render(request,"mcq.html",{'context':questionnaire, 'fill_blanks':fill_blanks,"explain":explanation,"diagram":diagram}) def preview(request): print(request.POST) if request.method == "POST": try: name = request.POST["organization_name"] description = request.POST["description"] logo = request.FILES["logo"] test_name = request.POST["test_name"] college_name = request.POST["college_name"] cam_micro = request.POST["cam_micro"] test_duration = request.POST["test_duration"] organization_test_create.objects.create( name = name, description=description, logo = logo, test_name = test_name, college_name = college_name, cam_micro = cam_micro, test_duration = test_duration ) file = request.FILES["mydocument"] # print("this is file object",file) # current_user_email = request.session["email"] import docx try: doc = docx.Document('file.docx') print("success") except Exception as e: print(e) doc = docx.Document(file) print("this works") questionnaire={} explanation={} diagram={} fill_blanks = {} i=1 number_of_iterations = 0 for content in doc.paragraphs: if ("Q"+str(i) or "QUESTION"+str(i)) in content.text.upper(): print(content.text) # questionnaire["question"+str(i)] = content.text questionnaire[content.text] =[] i=i+1 j=1 for option in doc.paragraphs: # print("this is option",option.text.upper()) if "OPTION"+" "+str(j) in option.text.upper(): print("check") questionnaire[content.text].append(option.text) j= j+1 if "ANSWER" in option.text.upper(): print("get answer") questionnaire[content.text].append(option.text) break elif ('fill in the blanks') in content.text.lower(): print("I am inside Fill in the Blanks") fill_blanks[content.text] = [] next_index = number_of_iterations+1 for i in range(next_index, len(doc.paragraphs)): if "_" in doc.paragraphs[i].text: fill_blanks[content.text].append(doc.paragraphs[i].text) elif " " == doc.paragraphs[i].text: continue else: break elif("explain") in content.text.lower(): explanation[content.text]=[] next_index = number_of_iterations+1 for i in range(next_index, len(doc.paragraphs)): if "Write" in doc.paragraphs[i].text: explanation[content.text].append(doc.paragraphs[i].text) elif " " == doc.paragraphs[i].text: continue else: break elif("draw") in content.text.lower(): diagram[content.text]=[] next_index = number_of_iterations+1 for i in range(next_index, len(doc.paragraphs)): if "diagram" in doc.paragraphs[i].text: diagram[content.text].append(doc.paragraphs[i].text) elif " " == doc.paragraphs[i].text: continue else: break print("Explanation",explanation) print("Diagram",diagram) print("Data of Fill in the blanks is ", fill_blanks) number_of_iterations += 1 print(questionnaire) preview_data = { "name":name, "description":description, "logo": logo, "test_name":test_name, "college_name":college_name, "cam_micro":cam_micro, "test_duration":test_duration } messages.success(request,"Test created successfully") print(">>>>>>>>sucess") return render(request,"mcq.html",{'preview_data':preview_data,'context':questionnaire, 'fill_blanks':fill_blanks,"explain":explanation,"diagram":diagram}) except Exception as e: messages.error(request,e) return render(request,"register_org.html") else: return render(request,"register_org.html")
{"/test_gen_webapp/authentication/views.py": ["/test_gen_webapp/authentication/models.py"], "/test_gen_webapp/authentication/urls.py": ["/test_gen_webapp/authentication/views.py"], "/test_gen_webapp/test_gen/views.py": ["/test_gen_webapp/test_gen/models.py"], "/test_gen_webapp/test_gen/urls.py": ["/test_gen_webapp/test_gen/views.py"]}
55,556
Gauravdarkslayer/school_project_demo
refs/heads/main
/test_gen_webapp/test_gen/urls.py
from django.conf.urls import include from django.urls import path from .views import * from django.contrib.staticfiles.urls import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns app_name = 'test_gen' urlpatterns = [ path('',show_doc_upload_page,name='upload_question'), path('register_org/',register_new_org,name='register_new_org'), path('preview_test/',preview), path('generate/',doc_processing), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
{"/test_gen_webapp/authentication/views.py": ["/test_gen_webapp/authentication/models.py"], "/test_gen_webapp/authentication/urls.py": ["/test_gen_webapp/authentication/views.py"], "/test_gen_webapp/test_gen/views.py": ["/test_gen_webapp/test_gen/models.py"], "/test_gen_webapp/test_gen/urls.py": ["/test_gen_webapp/test_gen/views.py"]}
55,557
Gauravdarkslayer/school_project_demo
refs/heads/main
/test_gen_webapp/test_gen/migrations/0002_auto_20201113_2150.py
# Generated by Django 3.1.2 on 2020-11-13 16:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('test_gen', '0001_initial'), ] operations = [ migrations.CreateModel( name='organization_test_create', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('description', models.CharField(max_length=500)), ('logo', models.ImageField(upload_to='media/')), ('test_name', models.CharField(max_length=100)), ('college_name', models.CharField(blank=True, max_length=100, null=True)), ('cam_micro', models.CharField(choices=[('yes', 'yes'), ('no', 'no')], max_length=3)), ('test_duration', models.CharField(max_length=100)), ], ), migrations.RemoveField( model_name='user_questionnaire', name='user_id', ), migrations.DeleteModel( name='question_options', ), migrations.DeleteModel( name='user_questionnaire', ), ]
{"/test_gen_webapp/authentication/views.py": ["/test_gen_webapp/authentication/models.py"], "/test_gen_webapp/authentication/urls.py": ["/test_gen_webapp/authentication/views.py"], "/test_gen_webapp/test_gen/views.py": ["/test_gen_webapp/test_gen/models.py"], "/test_gen_webapp/test_gen/urls.py": ["/test_gen_webapp/test_gen/views.py"]}
55,558
Gauravdarkslayer/school_project_demo
refs/heads/main
/test_gen_webapp/test_gen/models.py
from django.db import models from authentication.models import user # Create your models here. # class user_questionnaire(models.Model): # user_id= models.ForeignKey(user,on_delete=models.CASCADE) # question_id = models.AutoField(primary_key=True) # question_text = models.TextField() # class question_options(models.Model): # question_id = models.ForeignKey(user_questionnaire,on_delete=models.CASCADE) # option_id = models.AutoField(primary_key=True) # question_option = models.TextField() class organization_test_create(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=500) logo = models.ImageField(upload_to="media/") test_name = models.CharField(max_length=100) college_name = models.CharField(max_length=100, null=True,blank=True) cam_micro = models.CharField(max_length=3, choices=(("yes","yes"),("no","no"))) test_duration = models.CharField(max_length=100)
{"/test_gen_webapp/authentication/views.py": ["/test_gen_webapp/authentication/models.py"], "/test_gen_webapp/authentication/urls.py": ["/test_gen_webapp/authentication/views.py"], "/test_gen_webapp/test_gen/views.py": ["/test_gen_webapp/test_gen/models.py"], "/test_gen_webapp/test_gen/urls.py": ["/test_gen_webapp/test_gen/views.py"]}
55,559
Gauravdarkslayer/school_project_demo
refs/heads/main
/test_gen_webapp/test_gen/migrations/0001_initial.py
# Generated by Django 3.0.5 on 2020-10-11 21:15 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('authentication', '0001_initial'), ] operations = [ migrations.CreateModel( name='user_questionnaire', fields=[ ('question_id', models.AutoField(primary_key=True, serialize=False)), ('question_text', models.TextField()), ('user_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='authentication.user')), ], ), migrations.CreateModel( name='question_options', fields=[ ('option_id', models.AutoField(primary_key=True, serialize=False)), ('question_option', models.TextField()), ('question_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='test_gen.user_questionnaire')), ], ), ]
{"/test_gen_webapp/authentication/views.py": ["/test_gen_webapp/authentication/models.py"], "/test_gen_webapp/authentication/urls.py": ["/test_gen_webapp/authentication/views.py"], "/test_gen_webapp/test_gen/views.py": ["/test_gen_webapp/test_gen/models.py"], "/test_gen_webapp/test_gen/urls.py": ["/test_gen_webapp/test_gen/views.py"]}
55,560
Gauravdarkslayer/school_project_demo
refs/heads/main
/doc_processing.py
import docx def getText(doc): # doc = docx.Document(filename) fullText = [] for para in doc.paragraphs: fullText.append(para.text) return '\n'.join(fullText) doc = docx.Document('test_doc.docx') # print(len(doc.paragraphs)) # print(doc.paragraphs[0].text) # print(getText(doc)) # actual_content = getText(doc) questionnaire={} i=1 # print(getText(doc)) # working code for content in doc.paragraphs: if "Q"+str(i) in content.text.upper(): # questionnaire["question"+str(i)] = content.text questionnaire[content.text] =[] i=i+1 j=1 for option in doc.paragraphs: # print("this is option",option.text.upper()) if "OPTION"+" "+str(j) in option.text.upper(): print("check") questionnaire[content.text].append(option.text) j= j+1 if "ANSWER" in option.text.upper(): print("get answer") questionnaire[content.text].append(option.text) break print(questionnaire) # for content in doc.paragraphs: # if "Q"+str(i) in content.text.upper(): # # questionnaire["question"+str(i)] = content.text # questionnaire[content.text] =[] # i=i+1 # j=1 # question # elif "OPTION"+" "+str(j) in content.text.upper(): # questionnaire[content.text].append(option.text) # j= j+1 # for option in doc.paragraphs: # # print("this is option",option.text.upper()) # if "OPTION"+" "+str(j) in option.text.upper(): # print("check") # questionnaire[content.text].append(option.text) # j= j+1 """ { "question1":[option1,option2,option3,option4,answer], "question2":[option1,option2,option3,option4,answer], } """
{"/test_gen_webapp/authentication/views.py": ["/test_gen_webapp/authentication/models.py"], "/test_gen_webapp/authentication/urls.py": ["/test_gen_webapp/authentication/views.py"], "/test_gen_webapp/test_gen/views.py": ["/test_gen_webapp/test_gen/models.py"], "/test_gen_webapp/test_gen/urls.py": ["/test_gen_webapp/test_gen/views.py"]}
55,561
Gauravdarkslayer/school_project_demo
refs/heads/main
/test_gen_webapp/authentication/migrations/0001_initial.py
# Generated by Django 3.0.5 on 2020-10-11 21:15 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='user', fields=[ ('user_id', models.AutoField(primary_key=True, serialize=False)), ('full_name', models.CharField(max_length=100)), ('email_id', models.EmailField(max_length=254, unique=True)), ('password', models.CharField(max_length=500)), ('role', models.CharField(choices=[('stu', 'student'), ('org', 'organization'), ('schl', 'school')], max_length=50)), ], ), ]
{"/test_gen_webapp/authentication/views.py": ["/test_gen_webapp/authentication/models.py"], "/test_gen_webapp/authentication/urls.py": ["/test_gen_webapp/authentication/views.py"], "/test_gen_webapp/test_gen/views.py": ["/test_gen_webapp/test_gen/models.py"], "/test_gen_webapp/test_gen/urls.py": ["/test_gen_webapp/test_gen/views.py"]}
55,562
Gauravdarkslayer/school_project_demo
refs/heads/main
/test_gen_webapp/authentication/migrations/0002_auto_20201113_1915.py
# Generated by Django 3.1.2 on 2020-11-13 19:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('authentication', '0001_initial'), ] operations = [ migrations.AlterField( model_name='user', name='role', field=models.CharField(blank=True, choices=[('stu', 'student'), ('org', 'organization'), ('schl', 'school')], max_length=50), ), ]
{"/test_gen_webapp/authentication/views.py": ["/test_gen_webapp/authentication/models.py"], "/test_gen_webapp/authentication/urls.py": ["/test_gen_webapp/authentication/views.py"], "/test_gen_webapp/test_gen/views.py": ["/test_gen_webapp/test_gen/models.py"], "/test_gen_webapp/test_gen/urls.py": ["/test_gen_webapp/test_gen/views.py"]}
55,564
pritishakumar/creative-project-matchmaker
refs/heads/master
/app.py
import os from flask import Flask, render_template, request, flash, redirect, session, g, jsonify from flask_debugtoolbar import DebugToolbarExtension import requests from datetime import datetime from credentials import API_KEY from forms import UserAddForm, UserEditForm, ProjectForm, TagForm, LoginForm, GeocodeForm from models import db, connect_db, User, Project, Tag app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = ( os.environ.get('DATABASE_URL', 'postgres:///matchmaker')) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_ECHO'] = False app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = True app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY', "it's a secret") toolbar = DebugToolbarExtension(app) connect_db(app) def browser_login(user): """ Adds the User instance to session and g variable """ session['CURR_USER_KEY'] = user.id g.user = user def browser_logout(): """ Logs current user out of their account """ session.clear() g.user = None @app.before_request def add_user_to_g(): """ If we're logged in, add curr user to Flask global. """ if 'CURR_USER_KEY' in session: g.user = User.query.get(session['CURR_USER_KEY']) if not g.user: session.pop('CURR_USER_KEY') else: g.user = None if 'GUEST_GEOCODE' in session: g.guest = session['GUEST_GEOCODE'] @app.before_request def add_API_key(): """ Adds API key to the global variable g """ g.API_KEY = API_KEY @app.route("/") def landing_page(): """ Render initial landing page for user or redirect to the search page if the user is already logged in previously """ if 'CURR_USER_KEY' in session: return redirect("/search") return render_template("landing.html") @app.route("/profile/new", methods = ["GET", "POST"]) def sign_up_page(): """ Render the signup form or process the information """ if 'CURR_USER_KEY' in session: flash("You are already logged into an account, please log out before creating a new account.", "danger") return redirect("/search") form = UserAddForm(prefix='form-user-signup-') if form.validate_on_submit(): user_obj = { 'first_name': form.first_name.data, 'display_name': form.display_name.data, 'email': form.email.data, 'password': form.password.data, 'profile_pic': request.form.get('profile_pic'), 'lat': form.lat.data, 'long': form.long.data, 'privacy': request.form.get('privacy'), 'seeking_project': request.form.get('seeking_project'), 'seeking_help': request.form.get('seeking_help') } user_final = User.signup(user_obj) browser_login(user_final) flash("Signed up successfully", "success") return redirect("/search") return render_template("profile-new.html", form=form) @app.route("/login", methods = ["GET", "POST"]) def login_page(): """ Render the login form or process the information """ if 'CURR_USER_KEY' in session: flash("You are already logged into an account.", "success") return redirect("/search") form = LoginForm(prefix='form-user-login-') if form.validate_on_submit(): email = form.email.data password = form.password.data user_final = User.login(email, password) if user_final: browser_login(user_final) flash("Logged in successfully", "success") return redirect("/search") else: flash("Logged in failed. Please double check your email and password combination.", "danger") return redirect("/login") return render_template("login.html", form=form) @app.route("/logout", methods = ["POST"]) def logout(): """ Logs current user out of their account """ browser_logout() flash("Successfully logged out.", "success") return redirect("/") @app.route("/guest", methods = ["GET", "POST"]) def guest_page(): """ Renders the guest access page and prepares user for the search page by collecting geocode data """ if 'CURR_USER_KEY' in session: flash("You are already logged into an account.", "success") return redirect("/search") form = GeocodeForm(prefix='form-user-guest-') if form.validate_on_submit(): lat = form.lat.data long = form.long.data session['GUEST_GEOCODE'] = [lat, long] flash("Entering as a Guest. Some features are not displayed.", "success") return redirect("/search") return render_template("guest.html", form=form) @app.route("/search") def search_page(): """ Renders the main search page """ if ('GUEST_GEOCODE' not in session) and ('CURR_USER_KEY' not in session): flash("Please choose an option, before searching for projects","danger") return redirect("/") if ('CURR_USER_KEY' in session): g.user = User.lookup_user(session['CURR_USER_KEY']) return render_template("search.html") @app.route("/profile/edit", methods = ["GET", "POST"]) def profile_edit(): """ Renders form to edit the profile or process the information """ if not 'CURR_USER_KEY' in session: flash("Unauthorized access. Account needed to edit profile.", "danger") if 'GUEST_GEOCODE' in session: return redirect("/search") else: return redirect("/") form = UserEditForm(obj = g.user, prefix='form-user-edit-') if form.validate_on_submit(): user = User.login(form.email.data, form.password.data) if (user.id == g.user.id): user.first_name = form.first_name.data user.display_name = form.display_name.data user.profile_pic = form.profile_pic.data user.lat = form.lat.data user.long = form.long.data user.privacy = form.privacy.data user.seeking_project = form.seeking_project.data user.seeking_help = form.seeking_help.data db.session.commit() flash("Profile edited successfully.", "success") return redirect("/search") else: flash("Incorrect password. Profile changes not made", "danger") return redirect("/profile/edit") return render_template("profile-edit.html", form=form) @app.route("/profile/delete/<user_id>", methods = ["POST"]) def profile_delete(user_id): """ Deletes the currently logged in user """ if not 'CURR_USER_KEY' in session or int(user_id) != g.user.id: flash("Unauthorized access. Correct account needed to delete profile.", "danger") if 'GUEST_GEOCODE' in session: return redirect("/search") else: return redirect("/") user = User.lookup_user(user_id) db.session.delete(user) db.session.commit() browser_logout() flash("Profile deleted successfully.", "success") return redirect("/") @app.route("/project/new", methods = ["GET", "POST"]) def project_new(): """ Renders form to create new project or process the form """ if not 'CURR_USER_KEY' in session: flash("Unauthorized access. Account needed to create.", "danger") if 'GUEST_GEOCODE' in session: return redirect("/search") else: return redirect("/") form = ProjectForm(prefix='form-project-new-') tags_full_list = Tag.list_all() if form.validate_on_submit(): optional_date_keys = ['inquiry_deadline', 'work_start', 'work_end'] optional_date_values = [] for each in optional_date_keys: try: y, m, d = request.form.get(each).split('-') print(y,m,d,'out of if') if y and m and d: date = datetime(int(y), int(m), int(d)) optional_date_values.append(date) print(date, 'in if', optional_date_values) except ValueError: optional_date_values.append(None) print('caught value error', optional_date_values) except AttributeError: optional_date_values.append(None) print('caught value error', optional_date_values) inquiry_deadline_date, work_start_date, work_end_date = optional_date_values project_obj = { 'name': form.name.data, 'description': form.description.data, 'user_id': g.user.id, 'contact_info_type': form.contact_info_type.data, 'contact_info': form.contact_info.data, 'lat': form.lat.data, 'long': form.long.data, 'inquiry_deadline': inquiry_deadline_date, 'work_start': work_start_date, 'work_end': work_end_date, 'pic_url1': request.form.get('pic_url1'), 'pic_url2': request.form.get('pic_url2'), } project_final = Project.create_project(project_obj) tags = request.form.get('tags') if tags: tags = tags.split('|') tag_objs = [] if (len(tags) > 0): for name in tags: tag_obj = Tag.lookup_tag(name) if not tag_obj: tag_obj = Tag.create_tag(name) tag_objs.append(tag_obj) project_final.tags = tag_objs db.session.commit() flash("Project created successfully", "success") return redirect(f"/project/{project_final.id}") return render_template("project-new.html", form=form, tags_full_list = tags_full_list) @app.route("/project/<project_id>") def project_detail(project_id): """ Renders page for a specific project """ project = Project.lookup_project(project_id) tags = ', '.join([tag.name for tag in project.tags]) return render_template("project-detail.html", project=project, tags=tags) @app.route("/project/<project_id>/edit", methods = ["GET", "POST"]) def project_edit(project_id): """ Renders form to edit specific project or process the form """ if not 'CURR_USER_KEY' in session: flash("Unauthorized access. Account needed to edit.", "danger") return redirect(f"/project/{project_id}") project = Project.lookup_project(project_id) project = Project.lookup_project(project_id) if g.user.id != project.user.id: flash("Unauthorized user. Correct user account needed.", "danger") return redirect(f"/project/{project_id}") form = ProjectForm(obj = project, prefix='form-project-edit-') tags_full_list = Tag.list_all() project_tags = [tag.name for tag in project.tags] tags_list_str = "|".join(project_tags) if form.validate_on_submit(): project.name = form.name.data project.description = form.description.data project.user_id = g.user.id project.contact_info_type = form.contact_info_type.data project.contact_info = form.contact_info.data project.lat = form.lat.data project.long = form.long.data project.pic_url1 = request.form.get('pic_url1') project.pic_url2 = request.form.get('pic_url2') tags = request.form.get('tags') if (tags): tags = tags.split('|') tag_objs = [] if (tags and len(tags) > 0): for name in tags: tag_obj = Tag.lookup_tag(name) if not tag_obj: tag_obj = Tag.create_tag(name) tag_objs.append(tag_obj) project.tags = tag_objs optional_date_keys = ['inquiry_deadline', 'work_start', 'work_end'] optional_date_values = [] for each in optional_date_keys: try: y, m, d = request.form.get(each).split('-') print(y,m,d,'out of if') if y and m and d: date = datetime(int(y), int(m), int(d)) optional_date_values.append(date) print(date, 'in if', optional_date_values) except ValueError: pass optional_date_values.append(None) print('caught value error', optional_date_values) except AttributeError: optional_date_values.append(None) print('caught value error', optional_date_values) project.inquiry_deadline, project.work_start, project.work_end = optional_date_values db.session.commit() flash("Project edited successfully.", "success") return redirect(f"/project/{project_id}") return render_template("project-edit.html", form=form, project=project, tags_list_str=tags_list_str, tags_full_list=tags_full_list) @app.route("/project/<project_id>/delete", methods = ["POST"]) def project_delete(project_id): """ Renders form to delete a specific project""" if not 'CURR_USER_KEY' in session: flash("Unauthorized access. Account needed to delete.", "danger") return redirect(f"/project/{project_id}") project = Project.lookup_project(project_id) if g.user.id != project.user.id: flash("Unauthorized user. Correct user account needed.", "danger") return redirect(f"/project/{project_id}") db.session.delete(project) db.session.commit() flash("Project deleted successfully.", "success") return redirect("/search") @app.route("/api/geocode") def api_geocode(): """ Handle geocoding api get requests """ address = request.args['address'] url = "https://maps.googleapis.com/maps/api/geocode/json?" resp = requests.get(url, params={"key": API_KEY, "address": address}) json_data = resp.json() return jsonify(json_data) @app.route("/api/neighborhood") def api_neighborhood(): """ Handle project querying in the map vicinity """ north = float(request.args['north']) south = float(request.args['south']) east = float(request.args['east']) west = float(request.args['west']) neighborhood = Project.query_neighborhood(north, south, east, west) resp = { 'projects': []} for project in neighborhood: resp['projects'].append({'id': project.id, 'name': project.name, 'display_name': project.user.display_name, 'lat': project.lat, 'long': project.long, 'tags': [tag.name for tag in project.tags] }) return jsonify(resp) @app.route("/api/tags") def api_tag_list(): """ Generate and return a json list of all existing tags """ tags_full_list = Tag.list_all() return jsonify(tags_full_list)
{"/app.py": ["/forms.py", "/models.py"], "/seed.py": ["/app.py", "/models.py"], "/test_app.py": ["/app.py", "/models.py"]}
55,565
pritishakumar/creative-project-matchmaker
refs/heads/master
/seed.py
from app import db from models import User, Project, Tag db.drop_all() db.create_all() def seed_database(): u1 = User(first_name='Pat', display_name='pat', email='pat@email.com', password='password', lat=49.28778937014537, long=-123.11413092334273) u2 = User(first_name='Jill', display_name='jill', email='jill@email.com', password='password', lat=49.191682433834714, long=-122.84534638593648) u3 = User(first_name='Tester', display_name='tester', email='test@test.com', password='$2b$12$46DrbnRGb.he3uz138xWyuBbCG2zcPE8Y9dTJEi1OrB8zOvkGAJOC', lat=49.176662, long=-123.080341) t1 = Tag(name='glass art') t2 = Tag(name='green living') t3 = Tag(name='hardware') db.session.add_all([u1, u2, u3, t1, t2, t3]) db.session.commit() p1 = Project(name='Stained Glass', description=f"""I have a really boring window with a mediocre view! I would love to do a stained glass project of some sort with it? Does anyone have any expertise on this and be willing to help me?""", user_id=u1.id, contact_info_type='email', contact_info=u1.email, pic_url1='..\static\images\window-nicolas-solerieu-unsplash.jpg', lat=u1.lat, long=u1.long) p2 = Project(name='Compost Bin', description=f"""Anyone have metal welding equipment and skills that they'd be helping to lend to my project? I want to make a tumbler compost bin from a metal food grade drum I have lying around!""", user_id=u2.id, contact_info_type='email', contact_info=u2.email, lat=u2.lat, long=u2.long) p3 = Project(name='Wooden Pallet useful for you?', description=f"""I've got old wooden pallets, anyone want to make a fun project with them? I'd love to hear some ideas!""", user_id=u3.id, contact_info_type='email', contact_info=u3.email, pic_url1='..\static\images\wooden_pallet-reproductive-health-supplies-coalition-unsplash.jpg', lat=u3.lat, long=u3.long) db.session.add_all([p1, p2, p3]) db.session.commit() p1.tags = [t1] p2.tags = [t2, t3] p3.tags = [t2] db.session.commit() seed_database()
{"/app.py": ["/forms.py", "/models.py"], "/seed.py": ["/app.py", "/models.py"], "/test_app.py": ["/app.py", "/models.py"]}
55,566
pritishakumar/creative-project-matchmaker
refs/heads/master
/models.py
from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt from datetime import datetime bcrypt = Bcrypt() db = SQLAlchemy() def connect_db(app): """Connect to database.""" db.app = app db.init_app(app) class Project_Tag(db.Model): """ Project_Tag Model """ __tablename__ = "project_tags" id = db.Column(db.Integer, primary_key = True) project_id = db.Column(db.Integer, db.ForeignKey('projects.id', ondelete='CASCADE'), nullable=False, index=True) tag_name = db.Column(db.String(15), db.ForeignKey('tags.name', ondelete='CASCADE'), nullable=False) def __repr__(self): """ Show more useful info on Project_Tag """ return f"<Project_Tag {self.project_id} {self.tag_name}>" class User(db.Model): """ User Model """ __tablename__ = "users" id = db.Column(db.Integer, primary_key = True) email = db.Column(db.String(260), nullable = False, unique = True, index=True) password = db.Column(db.String(100), nullable = False) display_name = db.Column(db.String(20), nullable = False, unique = True) first_name = db.Column(db.String(20), nullable = False) profile_pic = db.Column(db.String(2000), nullable = True, default = "/static/images/junior-ferreira-profile.jpg") privacy = db.Column(db.Boolean, nullable = False, default = False) lat = db.Column(db.Float, nullable = False) long = db.Column(db.Float, nullable = False) seeking_project = db.Column(db.Boolean, nullable = False, default = True) seeking_help = db.Column(db.Boolean, nullable = False, default = True) projects = db.relationship("Project") def __repr__(self): """ Show more useful info on User """ return f"<User {self.display_name} {self.first_name}>" @classmethod def signup(cls, user_obj): """ Signs up new User with required info """ optional_params = ['profile_pic', 'privacy', 'seeking_project', 'seeking_help'] hashed_password = bcrypt.generate_password_hash(user_obj['password']).decode('UTF-8') user = cls( first_name= user_obj['first_name'], display_name= user_obj['display_name'], email= user_obj['email'], password=hashed_password, lat= user_obj['lat'], long= user_obj['long'] ) db.session.add(user) db.session.commit() for each in optional_params: if user_obj[each] != None: user.each = user_obj[each] db.session.commit() return user @classmethod def login(cls, email, password): """ Authenticates User with required info """ user = cls.query.filter_by(email=email).first() if user and bcrypt.check_password_hash(user.password, password): return user else: return False @classmethod def lookup_user(cls, id): """ Looks up User instance and returns it """ user = cls.query.get_or_404(id) return user class Project(db.Model): """ Project Model """ __tablename__ = "projects" id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String(30), nullable = False) description = db.Column(db.Text, nullable = False) user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False) contact_info_type = db.Column(db.String(20), nullable = False) contact_info = db.Column(db.String(260), nullable = False) lat = db.Column(db.Float, nullable = False, index=True) long = db.Column(db.Float, nullable = False, index=True) time_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow()) inquiry_deadline = db.Column(db.Date, nullable = True) work_start = db.Column(db.Date, nullable = True) work_end = db.Column(db.Date, nullable = True) pic_url1 = db.Column(db.String(2000), nullable = True) pic_url2 = db.Column(db.String(2000), nullable = True) user = db.relationship("User") tags = db.relationship( "Tag", secondary = "project_tags" ) def __repr__(self): """ Show more useful info on Project """ return f"<Project {self.name}>" @classmethod def create_project(cls, project_obj): """ Creates a new project instance by the current user """ optional_params = ['inquiry_deadline', 'work_start', 'work_end', 'pic_url1', 'pic_url2'] project = cls( name= project_obj['name'], description= project_obj['description'], user_id= project_obj['user_id'], contact_info_type= project_obj['contact_info_type'], contact_info= project_obj['contact_info'], lat= project_obj['lat'], long= project_obj['long'], inquiry_deadline= project_obj['inquiry_deadline'] or None, work_start= project_obj['work_start'] or None, work_end= project_obj['work_end'] or None, pic_url1= project_obj['pic_url1'] or None, pic_url2= project_obj['pic_url2'] or None ) db.session.add(project) db.session.commit() return project @classmethod def lookup_project(cls, project_id): """ Queries for a specific project """ project = cls.query.get_or_404(project_id) return project @classmethod def query_neighborhood(cls, north, south, east, west): """ Queries for projects within specific lat&long bounds """ neighborhood = cls.query.filter(Project.lat < north, Project.lat > south, Project.long > west, Project.long < east).all() return neighborhood class Tag(db.Model): """ Tag Model """ __tablename__ = "tags" name = db.Column(db.String(15), nullable = False, unique= True, primary_key = True) projects = db.relationship( "Project", secondary = "project_tags" ) def __repr__(self): """ Show more useful info on Tag """ return f"<Tag {self.name}>" @classmethod def create_tag(cls, name): """ Creates a tag instance given a name """ tag = cls(name = name) db.session.add(tag) db.session.commit() return tag @classmethod def list_all(cls): """ Creates a list of all existing tags """ object_list = cls.query.all() return [tag.name for tag in object_list] @classmethod def lookup_tag(cls, name): """ Looks up tag object based on name and returns it Returns None if not found """ tag = cls.query.filter_by(name=name).first() return tag
{"/app.py": ["/forms.py", "/models.py"], "/seed.py": ["/app.py", "/models.py"], "/test_app.py": ["/app.py", "/models.py"]}
55,567
pritishakumar/creative-project-matchmaker
refs/heads/master
/test_app.py
from unittest import TestCase from flask import session, g from app import app from models import db, User, Project, Tag app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///matchmaker_test' app.config['SQLALCHEMY_ECHO'] = False app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['DEBUG_TB_HOSTS'] = ['dont-show-debug-toolbar'] db.drop_all() db.create_all() user_data = { "first_name": 'Tester', "display_name": 'tester', "email": 'test@test.com', "password": '$2b$12$46DrbnRGb.he3uz138xWyuBbCG2zcPE8Y9dTJEi1OrB8zOvkGAJOC', "lat": 49.176662, "long": -123.080341, "profile_pic": "/static/images/junior-ferreira-profile.jpg", "privacy": False, "seeking_project": True, "seeking_help": True } user_data2 = { "first_name": 'Tester2', "display_name": 'tester2', "email": 'test2@test.com', "password": '$2b$12$46DrbnRGb.he3uz138xWyuBbCG2zcPE8Y9dTJEi1OrB8zOvkGAJOC', "lat": 49.176663, "long": -123.080342 } project1 = { "name":'Stained Glass', "description":f"""I have a really boring window with a mediocre view! I would love to do a stained glass project of some sort with it? Does anyone have any expertise on this and be willing to help me?""", "contact_info_type":'email', "contact_info": user_data["email"], "pic_url1":'..\static\images\window-nicolas-solerieu-unsplash.jpg', "lat":user_data["lat"], "long":user_data["long"] } project2 = { "name":'Compost Bin', "description":f"""Anyone have metal welding equipment and skills that they'd be helping to lend to my project? I want to make a tumbler compost bin from a metal food grade drum I have lying around!""", "contact_info_type":'email', "contact_info": user_data["email"], "lat":user_data["lat"], "long":user_data["long"] } class LandingTestCase(TestCase): """Tests for landing page""" def test_landing(self): """Tests rendering landing page""" with app.test_client() as client: resp = client.get("/") html = resp.get_data(as_text=True) self.assertEqual(resp.status_code, 200) self.assertIn("Welcome to <i>Creative Project Matchmaker", html) self.assertIn("An Existing Account?", html) self.assertIn("Proceed As A Guest?", html) self.assertIn("Guest Access!", html) with self.assertRaises(KeyError): session['CURR_USER_KEY'] with self.assertRaises(KeyError): session['GUEST_GEOCODE'] self.assertFalse(g.get('user', None)) class UserViewsTestCase(TestCase): """Tests for user profile related views""" def setUp(self): """Make demo data.""" db.drop_all() db.create_all() user = User(**user_data) db.session.add(user) db.session.commit() self.user = user def tearDown(self): """Clean up fouled transactions.""" db.session.rollback() def test_signup_get(self): """Tests the get request that renders the form""" with app.test_client() as client: resp = client.get("/profile/new") html = resp.get_data(as_text=True) self.assertEqual(resp.status_code,200) self.assertIn("Make A New Account", html) self.assertIn("Add New User", html) self.assertIn("Go Back to Options", html) with self.assertRaises(KeyError): session['CURR_USER_KEY'] with self.assertRaises(KeyError): session['GUEST_GEOCODE'] self.assertFalse(g.get('user', None)) def test_signup_post(self): """Ensures Post request redirects after processing data""" with app.test_client() as client: resp = client.post( "/profile/new", data={ 'form-user-signup-first_name': user_data2['first_name'], 'form-user-signup-display_name': user_data2['display_name'] , 'form-user-signup-email': user_data2['email'], 'form-user-signup-password': 'password', 'form-user-signup-confirm_password': 'password', 'form-user-signup-lat': user_data2['lat'], 'form-user-signup-long': user_data2['long'], 'form-user-signup-accept_rules': True }) self.assertEqual(resp.status_code,302) self.assertEqual(resp.location, "http://localhost/search") def test_signup_post_redirected(self): """Ensure Post request loads redirected page correctly""" with app.test_client() as client: resp = client.post( "/profile/new", data={ 'form-user-signup-first_name': user_data2['first_name'], 'form-user-signup-display_name': user_data2['display_name'] , 'form-user-signup-email': user_data2['email'], 'form-user-signup-password': 'password', 'form-user-signup-confirm_password': 'password', 'form-user-signup-lat': user_data2['lat'], 'form-user-signup-long': user_data2['long'], 'form-user-signup-accept_rules': True }, follow_redirects=True ) html = resp.get_data(as_text=True) self.assertEqual(resp.status_code,200) self.assertIn("Signed up successfully", html) self.assertIn("Log out</button>", html) self.assertIn("Edit Profile", html) self.assertTrue(session['CURR_USER_KEY']) with self.assertRaises(KeyError): session['GUEST_GEOCODE'] self.assertTrue(g.get('user', None)) def test_login_get(self): """ Tests rendering the form via Get request""" with app.test_client() as client: resp = client.get("/login") html = resp.get_data(as_text=True) self.assertEqual(resp.status_code,200) self.assertIn("Log In!", html) self.assertIn("Login", html) self.assertIn("Go Back to Options", html) with self.assertRaises(KeyError): session['CURR_USER_KEY'] with self.assertRaises(KeyError): session['GUEST_GEOCODE'] self.assertFalse(g.get('user', None)) def test_login_post(self): """Ensures Post request processes data and redirects""" with app.test_client() as client: resp = client.post( "/login", data={ 'form-user-login-email': user_data['email'], 'form-user-login-password': 'password', }) self.assertEqual(resp.status_code,302) self.assertEqual(resp.location, "http://localhost/search") def test_login_post_redirected(self): """Ensures redirected page renders correctly after Post request data is processed""" with app.test_client() as client: resp = client.post( "/login", data={ 'form-user-login-email': user_data['email'], 'form-user-login-password': 'password', }, follow_redirects=True ) html = resp.get_data(as_text=True) self.assertEqual(resp.status_code,200) self.assertIn("Logged in successfully", html) self.assertIn("Log out</button>", html) self.assertIn("Edit Profile", html) self.assertTrue(session['CURR_USER_KEY']) with self.assertRaises(KeyError): session['GUEST_GEOCODE'] self.assertTrue(g.get('user', None)) def test_guest_get(self): """Ensures Guest form renders correctly""" with app.test_client() as client: resp = client.get("/guest") html = resp.get_data(as_text=True) self.assertEqual(resp.status_code,200) self.assertIn("Guest Access!", html) self.assertIn("Enter Search Page", html) self.assertIn("Go Back to Options", html) with self.assertRaises(KeyError): session['CURR_USER_KEY'] with self.assertRaises(KeyError): session['GUEST_GEOCODE'] self.assertFalse(g.get('user', None)) def test_guest_post(self): """Ensures Guest Post request directs after submitting data""" with app.test_client() as client: resp = client.post( "/guest", data={ 'form-user-guest-lat': user_data2['lat'], 'form-user-guest-long': user_data2['long'], 'form-user-guest-accept_rules': True }) self.assertEqual(resp.status_code,302) self.assertEqual(resp.location, "http://localhost/search") def test_guest_post_redirected(self): """Ensure redirected page renders correctly after Post request""" with app.test_client() as client: resp = client.post( "/guest", data={ 'form-user-guest-lat': user_data2['lat'], 'form-user-guest-long': user_data2['long'], 'form-user-guest-accept_rules': True }, follow_redirects=True ) html = resp.get_data(as_text=True) self.assertEqual(resp.status_code,200) self.assertIn("Log out of Guest Mode", html) self.assertIn("Entering as a Guest. Some features are not displayed.", html) self.assertTrue(session['GUEST_GEOCODE']) with self.assertRaises(KeyError): session['CURR_USER_KEY'] self.assertFalse(g.get('user', None)) def test_logout(self): """Ensures user log out redirects""" with app.test_client() as client: with client.session_transaction() as change_session: change_session['CURR_USER_KEY'] = 999 resp = client.post("/logout") self.assertEqual(resp.status_code,302) self.assertEqual(resp.location, "http://localhost/") def test_logout_redirected(self): """Ensures user log out renders landing page correctly""" with app.test_client() as client: with client.session_transaction() as change_session: change_session['CURR_USER_KEY'] = 999 resp = client.post("/logout", follow_redirects=True) html = resp.get_data(as_text=True) self.assertEqual(resp.status_code,200) self.assertIn("Successfully logged out.", html) self.assertIn("Welcome to <i>Creative Project Matchmaker", html) self.assertIn("An Existing Account?", html) self.assertIn("Proceed As A Guest?", html) self.assertIn("Guest Access!", html) with self.assertRaises(KeyError): session['CURR_USER_KEY'] with self.assertRaises(KeyError): session['GUEST_GEOCODE'] self.assertFalse(g.get('user', None)) def test_user_edit_get(self): """Ensures user profile edit form renders""" with app.test_client() as client: with client.session_transaction() as change_session: change_session['CURR_USER_KEY'] = self.user.id g = {"user": user_data} resp = client.get("/profile/edit") html = resp.get_data(as_text=True) self.assertEqual(resp.status_code,200) self.assertIn("Update Your User Profile!", html) self.assertIn("To confirm any profile changes, enter your current password:", html) self.assertIn(self.user.email, html) with self.assertRaises(KeyError): session['GUEST_GEOCODE'] def test_user_edit_post(self): """Ensures user profile edit Post request redirects after processing data""" with app.test_client() as client: with client.session_transaction() as change_session: change_session['CURR_USER_KEY'] = self.user.id g = {"user": user_data} resp = client.post( "/profile/edit", data={ 'form-user-edit-first_name': user_data['first_name'], 'form-user-edit-display_name': user_data['display_name'] , 'form-user-edit-email': user_data['email'], 'form-user-edit-password': 'password', 'form-user-edit-profile_pic': "#", 'form-user-edit-lat': user_data['lat'], 'form-user-edit-long': user_data['long'], 'form-user-edit-privacy': False, 'form-user-edit-seeking_project': True, 'form-user-edit-seeking_help': True }) self.assertEqual(resp.status_code,302) self.assertEqual(resp.location, "http://localhost/search") def test_user_edit_post_redirected(self): """Ensures redirected page renders correctly after correctly processing Post request data""" with app.test_client() as client: with client.session_transaction() as change_session: change_session['CURR_USER_KEY'] = self.user.id g = {"user": user_data} resp = client.post( "/profile/edit", data={ 'form-user-edit-first_name': user_data['first_name'], 'form-user-edit-display_name': user_data['display_name'] , 'form-user-edit-email': user_data['email'], 'form-user-edit-password': 'password', 'form-user-edit-profile_pic': "#", 'form-user-edit-lat': user_data['lat'], 'form-user-edit-long': user_data['long'], 'form-user-edit-privacy': False, 'form-user-edit-seeking_project': True, 'form-user-edit-seeking_help': True }, follow_redirects=True ) html = resp.get_data(as_text=True) self.assertEqual(resp.status_code,200) self.assertIn("<h2>Search</h2>", html) self.assertIn("Profile edited successfully.", html) self.assertIn('img src="#"', html) with self.assertRaises(KeyError): session['GUEST_GEOCODE'] self.assertTrue(session['CURR_USER_KEY']) def test_user_delete_post(self): """Ensures user account deletion redirects""" with app.test_client() as client: with client.session_transaction() as change_session: change_session['CURR_USER_KEY'] = self.user.id g = {"user": user_data} resp = client.post(f"/profile/delete/{self.user.id}") self.assertEqual(resp.status_code,302) self.assertEqual(resp.location, "http://localhost/") def test_user_delete_post_redirected(self): """Ensures user account deletion occurs""" with app.test_client() as client: with client.session_transaction() as change_session: change_session['CURR_USER_KEY'] = self.user.id g = {"user": user_data} resp = client.post( f"/profile/delete/{self.user.id}", follow_redirects=True ) html = resp.get_data(as_text=True) self.assertEqual(resp.status_code,200) self.assertIn("Welcome to <i>Creative Project Matchmaker</i>", html) self.assertIn("Profile deleted successfully.", html) self.assertIn('An Existing Account?', html) with self.assertRaises(KeyError): session['CURR_USER_KEY'] with self.assertRaises(KeyError): session['GUEST_GEOCODE'] class SearchViewTestCase(TestCase): """Tests for search related views""" def setUp(self): """Make demo data.""" db.drop_all() db.create_all() user = User(**user_data) db.session.add(user) db.session.commit() self.user = user def tearDown(self): """Clean up fouled transactions.""" db.session.rollback() def test_search_get_user(self): """Ensures search page renders correctly for a registered user""" with app.test_client() as client: with client.session_transaction() as change_session: change_session['CURR_USER_KEY'] = self.user.id resp = client.get("/search") html = resp.get_data(as_text=True) self.assertEqual(resp.status_code,200) self.assertIn("Log out</button>", html) self.assertIn("<h2>Search</h2>", html) with self.assertRaises(KeyError): session['GUEST_GEOCODE'] def test_search_get_guest(self): """Ensures search page renders correctly for a guest user""" with app.test_client() as client: with client.session_transaction() as change_session: change_session['GUEST_GEOCODE'] = 99 resp = client.get("/search") html = resp.get_data(as_text=True) self.assertEqual(resp.status_code,200) self.assertIn("Log out of Guest Mode", html) self.assertIn("<h2>Search</h2>", html) with self.assertRaises(KeyError): session['CURR_USER_KEY'] class ProjectViewsTestCase(TestCase): """Tests for project related views""" def setUp(self): """Make demo data.""" db.drop_all() db.create_all() user = User(**user_data) t1 = Tag(name='glass art') db.session.add_all([user, t1]) db.session.commit() self.user = user self.tag1 = t1 p1 = Project( **project1, user_id =user.id, ) db.session.add(p1) db.session.commit() self.project1_id = p1.id p1.tags = [t1] db.session.commit() def tearDown(self): """Clean up fouled transactions.""" db.session.rollback() def test_project_detail_get(self): """Ensures project detail page renders correctly""" with app.test_client() as client: resp = client.get(f"/project/{self.project1_id}") html = resp.get_data(as_text=True) self.assertEqual(resp.status_code,200) self.assertIn(f"<h2>{project1['name']}</h2>", html) self.assertIn('<p>Tags: glass art</p>', html) with self.assertRaises(KeyError): session['GUEST_GEOCODE'] with self.assertRaises(KeyError): session['CURR_USER_KEY'] def test_project_new_get(self): """Ensures new project form renders correctly for a registered user""" with app.test_client() as client: with client.session_transaction() as change_session: change_session['CURR_USER_KEY'] = self.user.id resp = client.get("/project/new") html = resp.get_data(as_text=True) self.assertEqual(resp.status_code,200) self.assertIn("Log out</button>", html) self.assertIn("<h2>New Project</h2>", html) self.assertIn('<option value="glass art" />', html) with self.assertRaises(KeyError): session['GUEST_GEOCODE'] def test_project_new_post(self): """Ensures new project form Post request redirects""" with app.test_client() as client: with client.session_transaction() as change_session: change_session['CURR_USER_KEY'] = self.user.id g = {"user": user_data} resp = client.post( "/project/new", data={ 'form-project-new-name': project2['name'], 'form-project-new-description': project2['description'], 'form-project-new-contact_info_type': project2['contact_info_type'], 'form-project-new-contact_info': project2['contact_info'], 'form-project-new-lat': project2['lat'], 'form-project-new-long': project2['long'], }) self.assertEqual(resp.status_code,302) def test_project_new_post_redirected(self): """Ensures redirected page and data is processed correctly from the Post request""" with app.test_client() as client: with client.session_transaction() as change_session: change_session['CURR_USER_KEY'] = self.user.id g = {"user": user_data} resp = client.post( "/project/new", data={ 'form-project-new-name': project2['name'], 'form-project-new-description': project2['description'], 'form-project-new-contact_info_type': project2['contact_info_type'], 'form-project-new-contact_info': project2['contact_info'], 'form-project-new-lat': project2['lat'], 'form-project-new-long': project2['long'], }, follow_redirects=True ) html = resp.get_data(as_text=True) self.assertEqual(resp.status_code,200) self.assertIn("Project created successfully", html) self.assertIn(f"<h2>{project2['name']}</h2>", html) self.assertIn("Edit this Project", html) self.assertTrue(session['CURR_USER_KEY']) with self.assertRaises(KeyError): session['GUEST_GEOCODE'] self.assertTrue(g.get('user', None)) def test_project_edit_get(self): """Ensures project edit form renders correctly for the registered user who posted the post""" with app.test_client() as client: with client.session_transaction() as change_session: change_session['CURR_USER_KEY'] = self.user.id resp = client.get(f"/project/{self.project1_id}/edit") html = resp.get_data(as_text=True) self.assertEqual(resp.status_code,200) self.assertIn("Log out</button>", html) self.assertIn(" <h2>Edit Your Post</h2>", html) self.assertIn('Stained Glass', html) self.assertIn("Update Project", html) self.assertIn("Delete Project", html) with self.assertRaises(KeyError): session['GUEST_GEOCODE'] self.assertTrue(g.get('user', None)) def test_project_edit_post(self): """Ensures project edit form redirects""" with app.test_client() as client: with client.session_transaction() as change_session: change_session['CURR_USER_KEY'] = self.user.id g = {"user": user_data} resp = client.post( f"/project/{self.project1_id}/edit", data={ 'form-project-edit-name': project2['name'], 'form-project-edit-description': "#", 'form-project-edit-contact_info_type': project2['contact_info_type'], 'form-project-edit-contact_info': project2['contact_info'], 'form-project-edit-lat': project2['lat'], 'form-project-edit-long': project2['long'], 'form-project-edit-tags': "", }) self.assertEqual(resp.status_code,302) def test_project_edit_post_redirected(self): """Ensures rendered page renders and processes the data correctly from the Post request""" with app.test_client() as client: with client.session_transaction() as change_session: change_session['CURR_USER_KEY'] = self.user.id g = {"user": user_data} resp = client.post( f"/project/{self.project1_id}/edit", data={ 'form-project-edit-name': project2['name'], 'form-project-edit-description': "#", 'form-project-edit-contact_info_type': project2['contact_info_type'], 'form-project-edit-contact_info': project2['contact_info'], 'form-project-edit-lat': project2['lat'], 'form-project-edit-long': project2['long'], 'form-project-edit-tags': "", }, follow_redirects=True ) html = resp.get_data(as_text=True) self.assertEqual(resp.status_code,200) self.assertIn("Project edited successfully.", html) self.assertIn(f"<h2>{project2['name']}</h2>", html) self.assertIn("<p><i>#</i></p>", html) self.assertIn("Edit this Project", html) self.assertTrue(session['CURR_USER_KEY']) with self.assertRaises(KeyError): session['GUEST_GEOCODE'] self.assertTrue(g.get('user', None)) def test_project_delete_post(self): """Ensures project deletion redirects the registered user who posted the post""" with app.test_client() as client: with client.session_transaction() as change_session: change_session['CURR_USER_KEY'] = self.user.id g = {"user": user_data} resp = client.post(f"/project/{self.project1_id}/delete") self.assertEqual(resp.status_code,302) self.assertEqual(resp.location, "http://localhost/search") def test_project_delete_post_redirected(self): """Ensures the redirected page renders correctly and processes the Post request""" with app.test_client() as client: with client.session_transaction() as change_session: change_session['CURR_USER_KEY'] = self.user.id g = {"user": user_data} resp = client.post( f"/project/{self.project1_id}/delete", follow_redirects=True ) html = resp.get_data(as_text=True) self.assertEqual(resp.status_code,200) self.assertIn("Log out</button>", html) self.assertIn("Project deleted successfully.", html) self.assertIn("<h2>Search</h2>", html) self.assertTrue(session['CURR_USER_KEY']) with self.assertRaises(KeyError): session['GUEST_GEOCODE'] self.assertTrue(g.get('user', None)) class APIGeocodeTestCase(TestCase): """Tests for API geocode""" def test_api_geocode(self): """Ensures geocode is received correctly from API""" with app.test_client() as client: resp = client.get("/api/geocode?address=3211%20Grant%20McConachie") self.assertEqual(resp.status_code, 200) data = resp.json self.assertEqual(data['results'][0]['address_components'][0]['long_name'], "3211") class APINeighbourhoodTestCase(TestCase): """Tests for api neighbourhood""" def setUp(self): """Make demo data.""" db.drop_all() db.create_all() user = User(**user_data) t1 = Tag(name='glass art') db.session.add_all([user, t1]) db.session.commit() self.user = user self.tag1 = t1 p1 = Project( **project1, user_id =user.id, ) db.session.add(p1) db.session.commit() self.project1_id = p1.id p1.tags = [t1] db.session.commit() def tearDown(self): """Clean up fouled transactions.""" db.session.rollback() def test_api_neighborhood(self): """Ensures nearby projects can be queried from database""" with app.test_client() as client: resp = client.get("""api/neighborhood?north=49.376019219200614&south=49.107045276672984&east=-122.75234442225093&west=-123.5310004281103""") self.assertEqual(resp.status_code, 200) data = resp.json self.assertEqual(data['projects'][0]['name'], project1['name'] ) class APITagsTestCase(TestCase): """Tests for api tags""" def setUp(self): """Make demo data.""" db.drop_all() db.create_all() t1 = Tag(name='glass art') t2 = Tag(name='renovations') db.session.add_all([t1, t2]) db.session.commit() def tearDown(self): """Clean up fouled transactions.""" db.session.rollback() def test_api_tags(self): """Ensures full tag list can be queried""" with app.test_client() as client: resp = client.get("/api/tags") self.assertEqual(resp.status_code, 200) data = resp.json self.assertEqual(data, ['glass art', 'renovations'] )
{"/app.py": ["/forms.py", "/models.py"], "/seed.py": ["/app.py", "/models.py"], "/test_app.py": ["/app.py", "/models.py"]}
55,568
pritishakumar/creative-project-matchmaker
refs/heads/master
/forms.py
from flask_wtf import FlaskForm from wtforms import StringField, HiddenField, PasswordField, TextAreaField, BooleanField#, DateField from wtforms.fields.html5 import DateField from wtforms.validators import InputRequired, Length, Email, EqualTo, Optional class LoginForm(FlaskForm): """Form for logging in""" email = StringField("Email Address", validators = [InputRequired(), Length(max=260), Email()]) password = PasswordField("Password", validators = [InputRequired(), Length(max=30)]) class GeocodeForm(FlaskForm): """ Form for guests to enter geocode data and accept rules of the website """ lat = StringField("Approx User Latitude", validators = [InputRequired()]) long = StringField("Approx User Longitude", validators = [InputRequired()]) accept_rules = BooleanField("Have you read and accepted the rules for this website?", validators = [InputRequired()]) class UserAddForm(FlaskForm): """Form for adding users""" first_name = StringField("First Name", validators = [InputRequired(), Length(max=20)]) display_name = StringField("Display Name", validators = [InputRequired(), Length(max=20)]) email = StringField("Email Address", validators = [InputRequired(), Length(max=260), Email()]) password = PasswordField("Password", validators = [InputRequired(), Length(max=30)]) confirm_password = PasswordField("Confirm Your Password", validators = [InputRequired(), Length(max=30), EqualTo("password", message='Passwords must match')]) profile_pic = StringField("Profile Picture URL (optional)", validators = [Optional()]) lat = StringField("Default Approx User Latitude", validators = [InputRequired()]) long = StringField("Default Approx User Longitude", validators = [InputRequired()]) privacy = BooleanField("Profile Hidden from Search") seeking_project = BooleanField("Open to Finding New Projects to Help") seeking_help = BooleanField("Seeking Help on Your Projects") accept_rules = BooleanField("Have you read and accepted the rules for this website?", validators = [InputRequired()]) class UserEditForm(FlaskForm): """Form for editing users""" first_name = StringField("First Name", validators = [InputRequired(), Length(max=20)]) display_name = StringField("Display Name", validators = [InputRequired(), Length(max=20)]) email = StringField("Email Address", validators = [InputRequired(), Length(max=260), Email()]) password = PasswordField("Password", validators = [InputRequired(), Length(max=30)]) profile_pic = StringField("Profile Picture URL (optional)", validators = [Optional()]) lat = StringField("Default Approx User Latitude", validators = [InputRequired()]) long = StringField("Default Approx User Longitude", validators = [InputRequired()]) privacy = BooleanField("Profile Hidden from Search") seeking_project = BooleanField("Open to Finding New Projects to Help") seeking_help = BooleanField("Seeking Help on Your Projects") class ProjectForm(FlaskForm): """Form for adding/editing projects""" name = StringField("Project Name", validators = [InputRequired(), Length(max=30)]) description = TextAreaField("Project Description", validators = [InputRequired()]) contact_info_type = StringField("Contact Info Type", validators = [InputRequired(), Length(max=20)]) contact_info = StringField("Contact Info", validators = [InputRequired(), Length(max=260)]) lat = StringField("Default Approx Project Latitude", validators = [InputRequired()]) long = StringField("Default Approx Project Longitude", validators = [InputRequired()]) inquiry_deadline = DateField("Deadline for Receiving Inquiries (Optional)", validators = [Optional()], format='%Y-%m-%d') work_start = DateField("Proposed Project Start Date (Optional)", validators = [Optional()], format='%Y-%m-%d') work_end = DateField("Proposed Project End Date (Optional)", validators = [Optional()], format='%Y-%m-%d') pic_url1 = StringField("Project Picture 1 (Optional)", validators = [Length(max=2000), Optional()]) pic_url2 = StringField("Project Picture 2 (Optional)", validators = [Length(max=2000), Optional()]) tags = HiddenField("Tags", validators = [Optional()]) class TagForm(FlaskForm): """Form for adding/edit custom tags""" name = StringField("Tag Name", validators = [InputRequired(), Length(max=15)])
{"/app.py": ["/forms.py", "/models.py"], "/seed.py": ["/app.py", "/models.py"], "/test_app.py": ["/app.py", "/models.py"]}
55,597
CyanGirl/DjangoUserAuth
refs/heads/main
/handleusers/urls.py
from django.conf.urls import include, url from .views import dashboard,register,addHobby,viewhobby urlpatterns = [ url(r"accounts/", include("django.contrib.auth.urls")), url(r"dashboard/", dashboard, name="dashboard"), url(r"register/",register,name="register"), url(r"hobby/",addHobby,name="hobby"), url(r"hobbylist/",viewhobby,name="viewhobby"), ]
{"/handleusers/urls.py": ["/handleusers/views.py"], "/handleusers/forms.py": ["/handleusers/models.py"], "/handleusers/views.py": ["/handleusers/forms.py", "/handleusers/models.py"]}
55,598
CyanGirl/DjangoUserAuth
refs/heads/main
/handleusers/forms.py
from django.contrib.auth.forms import UserCreationForm from django import forms from django.forms import ModelForm from .models import * #extending usercreationform class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): #adding the email field fields = UserCreationForm.Meta.fields + ("email",) class HobbyForm(forms.ModelForm): class Meta: model=Hobby fields=['hobbyname']
{"/handleusers/urls.py": ["/handleusers/views.py"], "/handleusers/forms.py": ["/handleusers/models.py"], "/handleusers/views.py": ["/handleusers/forms.py", "/handleusers/models.py"]}
55,599
CyanGirl/DjangoUserAuth
refs/heads/main
/handleusers/apps.py
from django.apps import AppConfig class HandleusersConfig(AppConfig): name = 'handleusers'
{"/handleusers/urls.py": ["/handleusers/views.py"], "/handleusers/forms.py": ["/handleusers/models.py"], "/handleusers/views.py": ["/handleusers/forms.py", "/handleusers/models.py"]}
55,600
CyanGirl/DjangoUserAuth
refs/heads/main
/handleusers/models.py
from django.db import models from django.contrib.auth.models import User # Create your models here. class Hobby(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) hobbyname=models.CharField(max_length=100,blank=False)
{"/handleusers/urls.py": ["/handleusers/views.py"], "/handleusers/forms.py": ["/handleusers/models.py"], "/handleusers/views.py": ["/handleusers/forms.py", "/handleusers/models.py"]}
55,601
CyanGirl/DjangoUserAuth
refs/heads/main
/handleusers/views.py
from django.shortcuts import render,redirect from django.http import HttpResponse from django.contrib.auth import login from django.contrib.auth.models import User from django.urls import reverse from .forms import CustomUserCreationForm,HobbyForm from .models import Hobby # Create your views here. def dashboard(request): return render(request, "handleusers/dashboard.html") def register(request): #if the user is authenticated, redirect them to home if request.user.is_authenticated: return redirect('/') #when the signup form is accessed if request.method=="GET": return render(request, "handleusers/register.html",{"form":CustomUserCreationForm}) #when an user is trying to sign up elif request.method=="POST": #make a new form with the details filled up form=CustomUserCreationForm(request.POST) #check if all the fields given are valid for saving to database if form.is_valid(): #checking for the already existing #this will get all the fields that have been filled by the user userDict=form.cleaned_data #getting the username and email entered username=userDict['username'] email=userDict['email'] #cchecking the database checkUser=User.objects.filter(username=username).exists() checkEmail=User.objects.filter(email=email).exists() if checkEmail or checkUser: msg='Looks like username or email already exists..!' print(msg) return render(reverse("dashboard")) #raise forms.ValidationError(msg) else: user=form.save() #make the user login login(request,user) #reverse() is used to get the URL from the url_name return redirect(reverse("dashboard")) return redirect(reverse("dashboard")) def addHobby(request): if request.user.is_authenticated: if request.method=="POST": hobbyform=HobbyForm(data=request.POST) if hobbyform.is_valid(): hobbyf=hobbyform.cleaned_data hobbyname=hobbyf['hobbyname'] username=request.user checksave=Hobby.objects.create(user=username,hobbyname=hobbyname) else: context={ 'form':HobbyForm, } return render (request, 'handleusers/hobby.html',context=context) else: return render(request,'handleusers/requestlogin.html') return redirect(reverse('dashboard')) def viewhobby(request): if request.user.is_authenticated: if request.method=="POST": hobbyid=request.POST.get('hobbyname') #get the instance from the hobby id instance=Hobby.objects.get(id=hobbyid) if instance: #on successful retrieval instance.delete() print(f"{instance} deleted...") else: print("Error") hobbylist=request.user.hobby_set.all() context={ 'list':hobbylist, } return render(request,'handleusers/hobbylist.html',context=context) else: return render(request,'handleusers/requestlogin.html')
{"/handleusers/urls.py": ["/handleusers/views.py"], "/handleusers/forms.py": ["/handleusers/models.py"], "/handleusers/views.py": ["/handleusers/forms.py", "/handleusers/models.py"]}
55,639
michaelbelete/edir_backend_fast_api
refs/heads/main
/app/db/repository/member.py
from app.dependencies.authorization import user from app.db.repository.user import get_user from sqlalchemy.orm import Session, joinedload from app.schemas import Member as MemberSchema, MemberCreate, MemberUpdate, User from app.db.models import Member, Payment from app.db.repository.edir import get_edir_by_id, get_edir_by_username def get_all_members(db: Session, edir_id: int, skip: int = 0, limit:int = 0): db_edir = db.query(Member).filter(Member.edir_id == edir_id).options(joinedload(Member.user)).all() return db_edir def get_member_by_id(db:Session, edir_id: int, user_id: int): db_member = db.query(Member).filter(Member.edir_id == edir_id, Member.user_id == user_id).first() return db_member def get_member_by_edir_username(db:Session, username:str): edir = get_edir_by_username(db=db, username=username) db_member = db.query(Member).filter(Member.edir_id == edir.id).first() return db_member def get_member_by_user_id(db:Session, user_id: int): db_member = db.query(Member).filter(Member.user_id == user_id).options(joinedload(Member.edir)).first() return db_member def get_member_by_member_id(db:Session, id: int): db_member = db.query(Member).filter(Member.id == id).first() return db_member def check_member_exist(db:Session, edir_id: int, user_id: int): db_member = get_member_by_id(db=db, edir_id=edir_id, user_id=user_id) if db_member is None: return False return True def create_member(db:Session, member: MemberCreate): user = get_user(db=db, user_id=member.user_id); edir = get_edir_by_username(db=db, username=member.edir_username); db_member = Member(user_id=user.id, edir_id=edir.id, status="p") db.add(db_member) db.commit() return db_member def update_member(db:Session, member_id: int): db_member = db.query(Member).filter(Member.id == member_id).first() db_member.status = "a" db.commit() db.refresh(db_member) return db_member def delete_member(db: Session, member_id: int): member = db.query(Member).filter(Member.id == member_id) fetch = member.first() for payment in fetch.payments: db.query(Payment).filter(Payment.id == payment.id).delete() member.delete() db.commit()
{"/app/db/repository/member.py": ["/app/dependencies/authorization.py", "/app/db/repository/user.py", "/app/schemas.py", "/app/db/models.py", "/app/db/repository/edir.py"], "/app/routers/v1/event.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/event.py", "/app/db/repository/edir.py"], "/app/routers/v1/auth.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/edir.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/edir.py", "/app/dependencies/authorization.py"], "/app/db/models.py": ["/app/db/database.py"], "/app/main.py": ["/app/db/database.py"], "/app/dependencies/authorization.py": ["/app/db/database.py", "/app/db/repository/user.py"], "/app/db/repository/payment.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/member.py"], "/app/routers/v1/user.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/member.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/member.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/event.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/user.py": ["/app/schemas.py", "/app/db/models.py"], "/app/db/repository/edir.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py"], "/app/routers/v1/payment.py": ["/app/dependencies/authorization.py", "/app/db/repository/payment.py", "/app/db/repository/member.py", "/app/db/repository/edir.py", "/app/db/database.py", "/app/schemas.py"]}
55,640
michaelbelete/edir_backend_fast_api
refs/heads/main
/app/routers/v1/event.py
from app.dependencies.authorization import admin from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from app.db.repository.auth import AuthHandler from app.schemas import EventCreate, EventUpdate, Event as EventSchema from app.db.database import get_db from app.db.repository.event import get_event_by_user_id, get_events, get_event_by_id, create_event, update_event, delete_event from app.db.repository.edir import get_edir_by_id auth_handler = AuthHandler() router = APIRouter( prefix="/api/v1/events", tags=["Manage Events"], responses={404: {"description": "Not found"}}, ) @router.get("/{edir_id}") def get_all_events(edir_id: int, skip: int = 0, limit: int = 10, email=Depends(auth_handler.auth_wrapper), db: Session = Depends(get_db)): if get_edir_by_id(db=db, id=edir_id) is None: raise HTTPException(status_code=404, detail="Edir doesn't exist") else: events = get_events(db=db, edir_id=edir_id, skip=skip, limit=limit) return events @router.get("/user/{user_id}") def get_event_by_user_id(user_id: int, skip: int = 0, limit: int = 10, email=Depends(auth_handler.auth_wrapper), db: Session = Depends(get_db)): events = get_event_by_user_id(db=db, user_id=user_id, skip=skip, limit=limit) return events @router.get("/{edir_id}/{event_id}") def get_one_event(edir_id: int, event_id: int, db: Session = Depends(get_db), email=Depends(auth_handler.auth_wrapper)): event = get_event_by_id(db=db, id=event_id) return event @router.post("/") def create_new_event(event: EventCreate, email=Depends(auth_handler.auth_wrapper), db: Session = Depends(get_db), check_admin = Depends(admin)): if get_edir_by_id(db=db, id=event.edir_id) is None: raise HTTPException(status_code=404, detail="Edir doesn't exist") else: return create_event(db=db, email=email, event=event) @router.put("/{event_id}") def update_existing_event(event_id: int, event: EventUpdate, email=Depends(auth_handler.auth_wrapper), db: Session = Depends(get_db), check_admin = Depends(admin)): return update_event(db=db, event_id=event_id, event=event) @router.delete("/{event_id}") def delete_existing_event(event_id: int, email=Depends(auth_handler.auth_wrapper), db: Session = Depends(get_db), check_admin = Depends(admin)): return delete_event(db=db, event_id=event_id)
{"/app/db/repository/member.py": ["/app/dependencies/authorization.py", "/app/db/repository/user.py", "/app/schemas.py", "/app/db/models.py", "/app/db/repository/edir.py"], "/app/routers/v1/event.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/event.py", "/app/db/repository/edir.py"], "/app/routers/v1/auth.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/edir.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/edir.py", "/app/dependencies/authorization.py"], "/app/db/models.py": ["/app/db/database.py"], "/app/main.py": ["/app/db/database.py"], "/app/dependencies/authorization.py": ["/app/db/database.py", "/app/db/repository/user.py"], "/app/db/repository/payment.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/member.py"], "/app/routers/v1/user.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/member.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/member.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/event.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/user.py": ["/app/schemas.py", "/app/db/models.py"], "/app/db/repository/edir.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py"], "/app/routers/v1/payment.py": ["/app/dependencies/authorization.py", "/app/db/repository/payment.py", "/app/db/repository/member.py", "/app/db/repository/edir.py", "/app/db/database.py", "/app/schemas.py"]}
55,641
michaelbelete/edir_backend_fast_api
refs/heads/main
/app/db/database.py
from sqlalchemy import create_engine, engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm.session import Session from sqlalchemy.sql.expression import false SQLALCHEMY_DATABASE_URL = "mysql+pymysql://liyu:root@localhost:3306/edir" # engine = create_engine( # SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} # ) engine = create_engine(SQLALCHEMY_DATABASE_URL) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() def get_db(): db = SessionLocal() try: yield db finally: db.close() def create_database(): return Base.metadata.create_all(bind=engine)
{"/app/db/repository/member.py": ["/app/dependencies/authorization.py", "/app/db/repository/user.py", "/app/schemas.py", "/app/db/models.py", "/app/db/repository/edir.py"], "/app/routers/v1/event.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/event.py", "/app/db/repository/edir.py"], "/app/routers/v1/auth.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/edir.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/edir.py", "/app/dependencies/authorization.py"], "/app/db/models.py": ["/app/db/database.py"], "/app/main.py": ["/app/db/database.py"], "/app/dependencies/authorization.py": ["/app/db/database.py", "/app/db/repository/user.py"], "/app/db/repository/payment.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/member.py"], "/app/routers/v1/user.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/member.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/member.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/event.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/user.py": ["/app/schemas.py", "/app/db/models.py"], "/app/db/repository/edir.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py"], "/app/routers/v1/payment.py": ["/app/dependencies/authorization.py", "/app/db/repository/payment.py", "/app/db/repository/member.py", "/app/db/repository/edir.py", "/app/db/database.py", "/app/schemas.py"]}
55,642
michaelbelete/edir_backend_fast_api
refs/heads/main
/app/routers/v1/auth.py
from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from app.db.repository.auth import AuthHandler from app.schemas import UserCreate, AuthDetails, User as UserSchema from app.db.database import get_db from app.db.repository.user import create_user, check_user_exist ,check_encrypted_password, get_user_by_email auth_handler = AuthHandler() router = APIRouter( prefix="/api/v1/auth", tags=["Authentication"], responses={404: {"description": "Not found"}}, ) @router.post("/login") def login(auth_details: AuthDetails, db: Session = Depends(get_db)): if(check_user_exist(db, auth_details.email, auth_details.password)): token = auth_handler.encode_token(auth_details.email) user = get_user_by_email(db, auth_details.email) return { 'token': token, 'role': user.role } else: raise HTTPException(status_code=401, detail='Invalid email and/or password') @router.post("/signup", status_code=201) def sign_up(user: UserCreate, db: Session = Depends(get_db)): db_user = get_user_by_email(db=db, email=user.email) if db_user: raise HTTPException( status_code=400, detail="woops the email is in use" ) return create_user(db=db,user=user) @router.get("/logout") def log_out(): return "logout"
{"/app/db/repository/member.py": ["/app/dependencies/authorization.py", "/app/db/repository/user.py", "/app/schemas.py", "/app/db/models.py", "/app/db/repository/edir.py"], "/app/routers/v1/event.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/event.py", "/app/db/repository/edir.py"], "/app/routers/v1/auth.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/edir.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/edir.py", "/app/dependencies/authorization.py"], "/app/db/models.py": ["/app/db/database.py"], "/app/main.py": ["/app/db/database.py"], "/app/dependencies/authorization.py": ["/app/db/database.py", "/app/db/repository/user.py"], "/app/db/repository/payment.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/member.py"], "/app/routers/v1/user.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/member.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/member.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/event.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/user.py": ["/app/schemas.py", "/app/db/models.py"], "/app/db/repository/edir.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py"], "/app/routers/v1/payment.py": ["/app/dependencies/authorization.py", "/app/db/repository/payment.py", "/app/db/repository/member.py", "/app/db/repository/edir.py", "/app/db/database.py", "/app/schemas.py"]}
55,643
michaelbelete/edir_backend_fast_api
refs/heads/main
/app/routers/v1/edir.py
from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from app.db.repository.auth import AuthHandler from app.schemas import EdirCreate, EdirUpdate, Edir as EdirSchema from app.db.database import get_db from app.db.repository.edir import ( get_edirs, get_edir_by_id, get_edir_by_username, create_edir, update_edir, delete_edir, ) from app.dependencies.authorization import admin, user auth_handler = AuthHandler() router = APIRouter( prefix="/v1/edirs", tags=["Manage Edir"], responses={404: {"description": "Not found"}}, ) @router.get("/") def get_all_edirs( skip: int = 0, limit: int = 10, email=Depends(auth_handler.auth_wrapper), db: Session = Depends(get_db), ): posts = get_edirs(db=db, email=email, skip=skip, limit=limit) return posts @router.get("/{edir_id}") def get_one_edir( edir_id: int, db: Session = Depends(get_db), email=Depends(auth_handler.auth_wrapper), ): edir = get_edir_by_id(db=db, id=edir_id) return edir @router.post("/") def create_new_edir( edir: EdirCreate, email=Depends(auth_handler.auth_wrapper), db: Session = Depends(get_db), check_admin=Depends(admin), ): if get_edir_by_username(db=db, username=edir.username): raise HTTPException(status_code=400, detail="Username already taken!") else: return create_edir(db=db, email=email, edir=edir) @router.put("/{edir_id}") def update_existing_edir( edir_id: int, edir: EdirUpdate, email=Depends(auth_handler.auth_wrapper), db: Session = Depends(get_db), check_admin=Depends(admin), ): return update_edir(db=db, edir_id=edir_id, edir=edir) @router.delete("/{edir_id}") def delete_existing_edir( edir_id: int, email=Depends(auth_handler.auth_wrapper), db: Session = Depends(get_db), check_admin=Depends(admin), ): return delete_edir(db=db, edir_id=edir_id)
{"/app/db/repository/member.py": ["/app/dependencies/authorization.py", "/app/db/repository/user.py", "/app/schemas.py", "/app/db/models.py", "/app/db/repository/edir.py"], "/app/routers/v1/event.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/event.py", "/app/db/repository/edir.py"], "/app/routers/v1/auth.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/edir.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/edir.py", "/app/dependencies/authorization.py"], "/app/db/models.py": ["/app/db/database.py"], "/app/main.py": ["/app/db/database.py"], "/app/dependencies/authorization.py": ["/app/db/database.py", "/app/db/repository/user.py"], "/app/db/repository/payment.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/member.py"], "/app/routers/v1/user.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/member.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/member.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/event.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/user.py": ["/app/schemas.py", "/app/db/models.py"], "/app/db/repository/edir.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py"], "/app/routers/v1/payment.py": ["/app/dependencies/authorization.py", "/app/db/repository/payment.py", "/app/db/repository/member.py", "/app/db/repository/edir.py", "/app/db/database.py", "/app/schemas.py"]}
55,644
michaelbelete/edir_backend_fast_api
refs/heads/main
/app/db/models.py
import datetime as _dt from sqlalchemy import Column, Integer, String, DateTime, Float, Text from sqlalchemy.orm import relationship, backref from sqlalchemy.sql.schema import ForeignKey from app.db.database import Base class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True, index=True) full_name = Column(String(255), nullable=False) email = Column(String(255), unique=True, index=True, nullable=False) phone = Column(String(45), unique=True, index=True, nullable=False) password = Column(Text(4294000000), nullable=False) role = Column(String(255)) edirs = relationship("Edir", back_populates="owner") joined = relationship("Edir", secondary="members") class Edir(Base): __tablename__ = "edirs" id = Column(Integer, primary_key=True, index=True) name = Column(String(255)) payment_frequency = Column(String(255)) initial_deposit = Column(Float) username = Column(String(45),unique=True, index=True) owner_id = Column(Integer, ForeignKey('users.id')) owner = relationship("User", back_populates="edirs") events = relationship("Event", back_populates="edir") members = relationship("User", secondary="members") class Event(Base): __tablename__ = "events" id = Column(Integer, primary_key=True, index=True) title = Column(String(255)) description = Column(String(255)) event_date = Column(String(255)) edir_id = Column(Integer, ForeignKey('edirs.id')) # owner edir edir = relationship("Edir", back_populates="events") class Member(Base): __tablename__ = "members" id = Column(Integer, primary_key=True, index=True) user_id = Column(Integer, ForeignKey('users.id'), index=True) edir_id = Column(Integer, ForeignKey('edirs.id'), index=True) status = Column(String(255)) # owner user = relationship("User", backref=backref("member", cascade="all, delete-orphan")) edir = relationship("Edir", backref=backref("member", cascade="all, delete-orphan")) payments = relationship("Payment", back_populates='member') class Payment(Base): __tablename__ = "payments" id = Column(Integer, primary_key=True, index=True) note = Column(String(255)) payment = Column(Float) member_id = Column(Integer, ForeignKey('members.id')) payment_date = Column(String(255)) member = relationship("Member", back_populates='payments')
{"/app/db/repository/member.py": ["/app/dependencies/authorization.py", "/app/db/repository/user.py", "/app/schemas.py", "/app/db/models.py", "/app/db/repository/edir.py"], "/app/routers/v1/event.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/event.py", "/app/db/repository/edir.py"], "/app/routers/v1/auth.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/edir.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/edir.py", "/app/dependencies/authorization.py"], "/app/db/models.py": ["/app/db/database.py"], "/app/main.py": ["/app/db/database.py"], "/app/dependencies/authorization.py": ["/app/db/database.py", "/app/db/repository/user.py"], "/app/db/repository/payment.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/member.py"], "/app/routers/v1/user.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/member.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/member.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/event.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/user.py": ["/app/schemas.py", "/app/db/models.py"], "/app/db/repository/edir.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py"], "/app/routers/v1/payment.py": ["/app/dependencies/authorization.py", "/app/db/repository/payment.py", "/app/db/repository/member.py", "/app/db/repository/edir.py", "/app/db/database.py", "/app/schemas.py"]}
55,645
michaelbelete/edir_backend_fast_api
refs/heads/main
/app/main.py
from fastapi import FastAPI, Depends from fastapi.middleware.cors import CORSMiddleware from app.db.database import create_database # routers from app.routers.v1 import auth, edir, event, member, payment, user app = FastAPI() create_database() origins = [ "*" ] # origins = [ # "http://localhost.tiangolo.com", # "https://localhost.tiangolo.com", # "http://localhost", # "http://localhost:8080", # ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Verson 1 api routers app.include_router(auth.router) app.include_router(edir.router) app.include_router(event.router) app.include_router(member.router) app.include_router(payment.router) app.include_router(user.router)
{"/app/db/repository/member.py": ["/app/dependencies/authorization.py", "/app/db/repository/user.py", "/app/schemas.py", "/app/db/models.py", "/app/db/repository/edir.py"], "/app/routers/v1/event.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/event.py", "/app/db/repository/edir.py"], "/app/routers/v1/auth.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/edir.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/edir.py", "/app/dependencies/authorization.py"], "/app/db/models.py": ["/app/db/database.py"], "/app/main.py": ["/app/db/database.py"], "/app/dependencies/authorization.py": ["/app/db/database.py", "/app/db/repository/user.py"], "/app/db/repository/payment.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/member.py"], "/app/routers/v1/user.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/member.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/member.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/event.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/user.py": ["/app/schemas.py", "/app/db/models.py"], "/app/db/repository/edir.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py"], "/app/routers/v1/payment.py": ["/app/dependencies/authorization.py", "/app/db/repository/payment.py", "/app/db/repository/member.py", "/app/db/repository/edir.py", "/app/db/database.py", "/app/schemas.py"]}
55,646
michaelbelete/edir_backend_fast_api
refs/heads/main
/app/dependencies/authorization.py
from fastapi import Depends, HTTPException from app.db.repository.auth import AuthHandler from sqlalchemy.orm import Session from app.db.database import get_db from app.db.repository.user import get_user_role auth_handler = AuthHandler() async def admin(db: Session = Depends(get_db), email: str = Depends(auth_handler.auth_wrapper)): role = get_user_role(db=db, email=email) if role == "u": raise HTTPException(status_code=401, detail="User unauthorized. admin only") elif role == "a": pass else: raise HTTPException(status_code=401, detail="Unknown user role. contact the developer") async def user(db: Session = Depends(get_db), email: str = Depends(auth_handler.auth_wrapper)): role = get_user_role(db=db, email=email) if role == "a": raise HTTPException(status_code=401, detail="Admin unauthorized. user only") elif role == "u": pass else: raise HTTPException(status_code=401, detail="Unknown user role. contact the developer")
{"/app/db/repository/member.py": ["/app/dependencies/authorization.py", "/app/db/repository/user.py", "/app/schemas.py", "/app/db/models.py", "/app/db/repository/edir.py"], "/app/routers/v1/event.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/event.py", "/app/db/repository/edir.py"], "/app/routers/v1/auth.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/edir.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/edir.py", "/app/dependencies/authorization.py"], "/app/db/models.py": ["/app/db/database.py"], "/app/main.py": ["/app/db/database.py"], "/app/dependencies/authorization.py": ["/app/db/database.py", "/app/db/repository/user.py"], "/app/db/repository/payment.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/member.py"], "/app/routers/v1/user.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/member.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/member.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/event.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/user.py": ["/app/schemas.py", "/app/db/models.py"], "/app/db/repository/edir.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py"], "/app/routers/v1/payment.py": ["/app/dependencies/authorization.py", "/app/db/repository/payment.py", "/app/db/repository/member.py", "/app/db/repository/edir.py", "/app/db/database.py", "/app/schemas.py"]}
55,647
michaelbelete/edir_backend_fast_api
refs/heads/main
/app/db/repository/payment.py
from sqlalchemy.orm import Session from app.schemas import Payment, PaymentCreate, PaymentUpdate from app.db.models import Member, Payment from app.db.repository.member import get_member_by_id def get_all_members_payment(db: Session, edir_id: int, user_id: int, skip: int = 0, limit: int = 10): db_payments = db.query(Payment).filter( Payment.member_id == user_id).offset(skip).limit(limit).all() return db_payments def get_all_user_payment(db: Session, user_id: int, skip: int = 0, limit: int = 10): edir = db.query(Member).filter(Member.user_id == user_id).first() member_id = edir.id; db_payments = db.query(Payment).filter( Payment.member_id == member_id).offset(skip).limit(limit).all() return db_payments def create_payment(db: Session, payment: PaymentCreate): db_payment = Payment(note=payment.note, payment=payment.payment, member_id=payment.member_id, payment_date=payment.payment_date) db.add(db_payment) db.commit() return db_payment def update_payment(db: Session, payment_id: int, payment: PaymentUpdate): db_payment = db.query(Payment).filter(Payment.id == payment_id).first() db_payment.note = payment.note db_payment.payment = payment.payment db_payment.payment_date = payment.payment_date db.commit() db.refresh(db_payment) return db_payment def delete_payment(db: Session, payment_id): db.query(Payment).filter(Payment.id == payment_id).delete() db.commit()
{"/app/db/repository/member.py": ["/app/dependencies/authorization.py", "/app/db/repository/user.py", "/app/schemas.py", "/app/db/models.py", "/app/db/repository/edir.py"], "/app/routers/v1/event.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/event.py", "/app/db/repository/edir.py"], "/app/routers/v1/auth.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/edir.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/edir.py", "/app/dependencies/authorization.py"], "/app/db/models.py": ["/app/db/database.py"], "/app/main.py": ["/app/db/database.py"], "/app/dependencies/authorization.py": ["/app/db/database.py", "/app/db/repository/user.py"], "/app/db/repository/payment.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/member.py"], "/app/routers/v1/user.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/member.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/member.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/event.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/user.py": ["/app/schemas.py", "/app/db/models.py"], "/app/db/repository/edir.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py"], "/app/routers/v1/payment.py": ["/app/dependencies/authorization.py", "/app/db/repository/payment.py", "/app/db/repository/member.py", "/app/db/repository/edir.py", "/app/db/database.py", "/app/schemas.py"]}
55,648
michaelbelete/edir_backend_fast_api
refs/heads/main
/app/routers/v1/user.py
from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from app.db.repository.auth import AuthHandler from app.schemas import UserUpdate from app.db.database import get_db from app.db.repository.user import get_user_by_email, update_user, delete_user auth_handler = AuthHandler() router = APIRouter( prefix="/api/v1/user", tags=["User"], responses={404: {"description": "Not found"}}, ) #get user @router.get("/") def auth_user(email=Depends(auth_handler.auth_wrapper), db: Session = Depends(get_db)): return get_user_by_email(db=db, email=email) #update user @router.put("/") def auth_user_update(user: UserUpdate, email=Depends(auth_handler.auth_wrapper), db: Session = Depends(get_db)): return update_user(db=db, email=email, user=user) #delete user @router.delete("/") def auth_user_delete(db: Session = Depends(get_db), email=Depends(auth_handler.auth_wrapper)): return delete_user(db=db, email=email)
{"/app/db/repository/member.py": ["/app/dependencies/authorization.py", "/app/db/repository/user.py", "/app/schemas.py", "/app/db/models.py", "/app/db/repository/edir.py"], "/app/routers/v1/event.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/event.py", "/app/db/repository/edir.py"], "/app/routers/v1/auth.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/edir.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/edir.py", "/app/dependencies/authorization.py"], "/app/db/models.py": ["/app/db/database.py"], "/app/main.py": ["/app/db/database.py"], "/app/dependencies/authorization.py": ["/app/db/database.py", "/app/db/repository/user.py"], "/app/db/repository/payment.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/member.py"], "/app/routers/v1/user.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/member.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/member.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/event.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/user.py": ["/app/schemas.py", "/app/db/models.py"], "/app/db/repository/edir.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py"], "/app/routers/v1/payment.py": ["/app/dependencies/authorization.py", "/app/db/repository/payment.py", "/app/db/repository/member.py", "/app/db/repository/edir.py", "/app/db/database.py", "/app/schemas.py"]}
55,649
michaelbelete/edir_backend_fast_api
refs/heads/main
/app/routers/v1/member.py
from os import stat from app.dependencies.authorization import admin from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from app.db.repository.auth import AuthHandler from app.schemas import Member as MemberSchema, MemberCreate, MemberUpdate from app.db.database import get_db from app.db.repository.member import ( get_all_members, create_member, delete_member, get_member_by_edir_username, get_member_by_id, get_member_by_user_id, update_member, ) from app.db.repository.user import get_user from app.db.repository.edir import get_edir_by_id, get_edir_by_username auth_handler = AuthHandler() router = APIRouter( prefix="/api/v1/members", tags=["Manage Members"], responses={404: {"description": "Not found"}}, ) # get members @router.get("/{edir_id}") def get_edir_members( edir_id: int, skip: int = 0, limit: int = 10, db: Session = Depends(get_db), email=Depends(auth_handler.auth_wrapper), check_admin=Depends(admin), ): return get_all_members(db=db, edir_id=edir_id, skip=skip, limit=limit) @router.get("/user/{user_id}") def get_member_by_user_id_with_edir( user_id: int, db: Session = Depends(get_db), email=Depends(auth_handler.auth_wrapper), ): return get_member_by_user_id(db=db, user_id=user_id) # add a member @router.post("/") def add_member( member: MemberCreate, email=Depends(auth_handler.auth_wrapper), db: Session = Depends(get_db), ): # if the user doesn't exist if not get_user(db=db, user_id=member.user_id): raise HTTPException(status_code=404, detail="Oops, User doesn't exist") # if the edir doesn't exist if not get_edir_by_username(db=db, username=member.edir_username): raise HTTPException(status_code=404, detail="Oops, Edir doesn't exist") if get_member_by_edir_username(db=db, username=member.edir_username): raise HTTPException(status_code=403, detail="Member already exist") return create_member(db=db, member=member) # approval @router.put("/{member_id}") def approve_member( member_id: int, email=Depends(auth_handler.auth_wrapper), db: Session = Depends(get_db), check_admin=Depends(admin), ): return update_member(db=db, member_id=member_id) # delete member @router.delete("/{member_id}") def remove_member( member_id: int, email=Depends(auth_handler.auth_wrapper), db: Session = Depends(get_db), ): return delete_member(db=db, member_id=member_id)
{"/app/db/repository/member.py": ["/app/dependencies/authorization.py", "/app/db/repository/user.py", "/app/schemas.py", "/app/db/models.py", "/app/db/repository/edir.py"], "/app/routers/v1/event.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/event.py", "/app/db/repository/edir.py"], "/app/routers/v1/auth.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/edir.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/edir.py", "/app/dependencies/authorization.py"], "/app/db/models.py": ["/app/db/database.py"], "/app/main.py": ["/app/db/database.py"], "/app/dependencies/authorization.py": ["/app/db/database.py", "/app/db/repository/user.py"], "/app/db/repository/payment.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/member.py"], "/app/routers/v1/user.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/member.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/member.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/event.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/user.py": ["/app/schemas.py", "/app/db/models.py"], "/app/db/repository/edir.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py"], "/app/routers/v1/payment.py": ["/app/dependencies/authorization.py", "/app/db/repository/payment.py", "/app/db/repository/member.py", "/app/db/repository/edir.py", "/app/db/database.py", "/app/schemas.py"]}
55,650
michaelbelete/edir_backend_fast_api
refs/heads/main
/app/db/repository/event.py
from sqlalchemy.orm import Session from app.schemas import Event, EventCreate, EventUpdate from app.db.models import Event, Member from app.db.repository.user import get_user_by_email from app.db.repository.edir import get_edir_by_id def get_events(db: Session, edir_id: int, skip: int = 0, limit: int = 10): return db.query(Event).filter(Event.edir_id == edir_id).offset(skip).limit(limit).all() def get_event_by_id(db: Session, id: int): return db.query(Event).filter(Event.id == id).first() def get_event_by_user_id(db:Session, user_id: int, skip: int = 0, limit: int = 10): member = db.query(Member).filter(Member.user_id == user_id).first(); edir_id = member.edir_id; return db.query(Event).filter(Event.edir_id == edir_id).offset(skip).limit(limit).all() def create_event(db: Session, email: str, event: EventCreate): db_event = Event(title=event.title, description=event.description, event_date=event.event_date, edir_id=event.edir_id) db.add(db_event) db.commit() return db_event def update_event(db: Session, event_id: int, event: EventUpdate): db_event = get_event_by_id(db=db, id=event_id) db_event.title = event.title db_event.description = event.description db_event.event_date = event.event_date db.commit() db.refresh(db_event) return db_event def delete_event(db: Session, event_id: int): db.query(Event).filter(Event.id == event_id).delete() db.commit()
{"/app/db/repository/member.py": ["/app/dependencies/authorization.py", "/app/db/repository/user.py", "/app/schemas.py", "/app/db/models.py", "/app/db/repository/edir.py"], "/app/routers/v1/event.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/event.py", "/app/db/repository/edir.py"], "/app/routers/v1/auth.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/edir.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/edir.py", "/app/dependencies/authorization.py"], "/app/db/models.py": ["/app/db/database.py"], "/app/main.py": ["/app/db/database.py"], "/app/dependencies/authorization.py": ["/app/db/database.py", "/app/db/repository/user.py"], "/app/db/repository/payment.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/member.py"], "/app/routers/v1/user.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/member.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/member.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/event.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/user.py": ["/app/schemas.py", "/app/db/models.py"], "/app/db/repository/edir.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py"], "/app/routers/v1/payment.py": ["/app/dependencies/authorization.py", "/app/db/repository/payment.py", "/app/db/repository/member.py", "/app/db/repository/edir.py", "/app/db/database.py", "/app/schemas.py"]}
55,651
michaelbelete/edir_backend_fast_api
refs/heads/main
/app/db/repository/user.py
from sqlalchemy.orm import Session from starlette import responses from app.schemas import UserCreate, UserUpdate from passlib.context import CryptContext from app.db.models import User, Edir pwd_context = CryptContext( schemes=["pbkdf2_sha256"], default="pbkdf2_sha256", pbkdf2_sha256__default_rounds=30000 ) def encrypt_password(password): return pwd_context.encrypt(password) def check_encrypted_password(password, hashed): return pwd_context.verify(password, hashed) def check_user_exist(db: Session, email: str, password: str): user_exist = db.query(User).filter(User.email == email).first() if user_exist is None: return False else: if check_encrypted_password(password, user_exist.password): return True else: return False def get_user(db: Session, user_id: int): return db.query(User).filter(User.id == user_id).first() def get_user_by_email(db: Session, email: str): return db.query(User).filter(User.email == email).first() def get_user_role(db: Session, email: str): user = get_user_by_email(db=db, email=email) return user.role def get_users(db: Session, skip: int = 0, limit: int = 100): return db.query(User).offset(skip).limit(limit).all() def get_users_role(db: Session, user_id: int): return get_user(db, user_id).role def create_user(db: Session, user: UserCreate): hashed_password = encrypt_password(user.password) db_user = User(full_name=user.full_name, email=user.email, phone=user.phone, password=hashed_password, role=user.role) db.add(db_user) db.commit() db.refresh(db_user) return db_user def update_user(db: Session, email: str, user: UserUpdate): db_user = get_user_by_email(db=db, email=email) db_user.full_name = user.full_name db_user.email = user.email db_user.phone = user.phone db_user.password = user.password db.commit() db.refresh(db_user) return db_user def delete_user(db: Session, email: str): response = db.query(User).filter(User.email == email) user = response.first() if user.edirs: for edir in user.edirs: db.query(Edir).filter(Edir.id == edir.id).delete() response.delete() db.commit()
{"/app/db/repository/member.py": ["/app/dependencies/authorization.py", "/app/db/repository/user.py", "/app/schemas.py", "/app/db/models.py", "/app/db/repository/edir.py"], "/app/routers/v1/event.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/event.py", "/app/db/repository/edir.py"], "/app/routers/v1/auth.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/edir.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/edir.py", "/app/dependencies/authorization.py"], "/app/db/models.py": ["/app/db/database.py"], "/app/main.py": ["/app/db/database.py"], "/app/dependencies/authorization.py": ["/app/db/database.py", "/app/db/repository/user.py"], "/app/db/repository/payment.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/member.py"], "/app/routers/v1/user.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/member.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/member.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/event.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/user.py": ["/app/schemas.py", "/app/db/models.py"], "/app/db/repository/edir.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py"], "/app/routers/v1/payment.py": ["/app/dependencies/authorization.py", "/app/db/repository/payment.py", "/app/db/repository/member.py", "/app/db/repository/edir.py", "/app/db/database.py", "/app/schemas.py"]}
55,652
michaelbelete/edir_backend_fast_api
refs/heads/main
/app/schemas.py
from sqlalchemy.sql.functions import user from pydantic import BaseModel from typing import List, Optional from sqlalchemy.sql.sqltypes import Enum # event defnation class _EventBase(BaseModel): title: str description: str event_date: str class EventCreate(_EventBase): edir_id: int class EventUpdate(_EventBase): pass class Event(_EventBase): id: int edir_id: int class Config: orm_mode = True #edir defnition class _EdirBase(BaseModel): name:str payment_frequency: str initial_deposit:int username: str class EdirCreate(_EdirBase): pass class Edir(_EdirBase): id: int owner_id: int events: List[Event] = [] class Config: orm_mode = True class EdirUpdate(BaseModel): name: str payment_frequency: str initial_deposite: int class RoleChoice(str, Enum): u = "u" a = "a" # user defnition class _UserBase(BaseModel): full_name: str email: str phone: str role: RoleChoice class UserUpdate(BaseModel): full_name: str email: str phone: str password: str class UserCreate(_UserBase): password:str class User(_UserBase): id: int edirs: List[Edir] = [] joined: List[Edir] =[] class config: orm_mode = True class _PaymentBase(BaseModel): note: str payment:str member_id: int payment_date:str class Payment(_PaymentBase): id: int class config: orm_mode = True class PaymentCreate(_PaymentBase): pass class PaymentUpdate(BaseModel): note:str payment:str payment_date:str # member defnition class _MemberBase(BaseModel): user_id:str edir_id:str status:str class MemberCreate(BaseModel): user_id:int edir_username: str status: str class Member(_MemberBase): id: int user: List[User] = [] edir: List[Edir] = [] payments: List[Payment] = [] class MemberUpdate(BaseModel): status:str class Token(BaseModel): accessToken:str tokenType:str class TokenData(BaseModel): email: Optional[str] = None userType: Optional[str] = None class AuthDetails(BaseModel): email: str password: str
{"/app/db/repository/member.py": ["/app/dependencies/authorization.py", "/app/db/repository/user.py", "/app/schemas.py", "/app/db/models.py", "/app/db/repository/edir.py"], "/app/routers/v1/event.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/event.py", "/app/db/repository/edir.py"], "/app/routers/v1/auth.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/edir.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/edir.py", "/app/dependencies/authorization.py"], "/app/db/models.py": ["/app/db/database.py"], "/app/main.py": ["/app/db/database.py"], "/app/dependencies/authorization.py": ["/app/db/database.py", "/app/db/repository/user.py"], "/app/db/repository/payment.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/member.py"], "/app/routers/v1/user.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/member.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/member.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/event.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/user.py": ["/app/schemas.py", "/app/db/models.py"], "/app/db/repository/edir.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py"], "/app/routers/v1/payment.py": ["/app/dependencies/authorization.py", "/app/db/repository/payment.py", "/app/db/repository/member.py", "/app/db/repository/edir.py", "/app/db/database.py", "/app/schemas.py"]}
55,653
michaelbelete/edir_backend_fast_api
refs/heads/main
/app/db/repository/edir.py
from sqlalchemy.orm import Session from app.schemas import Edir, EdirCreate, EdirUpdate from app.db.models import Edir from app.db.repository.user import get_user_by_email def get_edirs(db: Session, email: str, skip: int = 0, limit: int = 10): db_user = get_user_by_email(db, email) return db.query(Edir).filter(Edir.owner_id == db_user.id).offset(skip).limit(limit).first() def get_edir_by_id(db: Session, id: int): return db.query(Edir).filter(Edir.id == id).first() def get_edir_by_username(db:Session, username: str): return db.query(Edir).filter(Edir.username == username).first() def create_edir(db: Session, email: str, edir: EdirCreate): db_user = get_user_by_email(db, email) db_edir = Edir(name=edir.name, payment_frequency=edir.payment_frequency, initial_deposit=edir.initial_deposit, username=edir.username, owner_id=db_user.id) db.add(db_edir) db.commit() db.refresh(db_user) return db_edir def update_edir(db: Session, edir_id: int, edir: EdirUpdate): db_edir = get_edir_by_id(db=db, id=edir_id) db_edir.name = edir.name db_edir.payment_frequency = edir.payment_frequency db_edir.initial_deposit = edir.initial_deposit db.commit() db.refresh(db_edir) return db_edir def delete_edir(db: Session, edir_id: int): db.query(Edir).filter(Edir.id == edir_id).delete() db.commit()
{"/app/db/repository/member.py": ["/app/dependencies/authorization.py", "/app/db/repository/user.py", "/app/schemas.py", "/app/db/models.py", "/app/db/repository/edir.py"], "/app/routers/v1/event.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/event.py", "/app/db/repository/edir.py"], "/app/routers/v1/auth.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/edir.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/edir.py", "/app/dependencies/authorization.py"], "/app/db/models.py": ["/app/db/database.py"], "/app/main.py": ["/app/db/database.py"], "/app/dependencies/authorization.py": ["/app/db/database.py", "/app/db/repository/user.py"], "/app/db/repository/payment.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/member.py"], "/app/routers/v1/user.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/member.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/member.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/event.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/user.py": ["/app/schemas.py", "/app/db/models.py"], "/app/db/repository/edir.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py"], "/app/routers/v1/payment.py": ["/app/dependencies/authorization.py", "/app/db/repository/payment.py", "/app/db/repository/member.py", "/app/db/repository/edir.py", "/app/db/database.py", "/app/schemas.py"]}
55,654
michaelbelete/edir_backend_fast_api
refs/heads/main
/app/routers/v1/payment.py
from app.dependencies.authorization import admin from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from app.db.repository.auth import AuthHandler from app.db.repository.payment import get_all_members_payment, create_payment, get_all_user_payment, update_payment, delete_payment from app.db.repository.member import get_member_by_id, get_member_by_member_id from app.db.repository.edir import get_edir_by_id from app.db.database import get_db from app.schemas import Payment, PaymentCreate, PaymentUpdate auth_handler = AuthHandler() router = APIRouter( prefix="/api/v1/payments", tags=["Manage Payments"], responses={404: {"description": "Not found"}}, ) # get payments by a member @router.get("/user/{user_id}") def get_all_payments_by_user_id(user_id: int, skip: int = 0, limit: int = 10, db:Session = Depends(get_db), email=Depends(auth_handler.auth_wrapper)): payments = get_all_user_payment(db=db, user_id=user_id, skip=skip, limit=limit) #if there's no payment if payments is None: raise HTTPException(status_code=404, detail="No payment exist") return payments @router.get("user/{member_id}") def get_all_payments(edir_id: int, member_id: int, skip: int = 0, limit: int = 10, db:Session = Depends(get_db), email=Depends(auth_handler.auth_wrapper)): #if member doesn't exist if not get_member_by_member_id(db=db, id=member_id): raise HTTPException(status_code=404, detail="Oops, User doesn't exist in this edir") #if edir doesn't exist if not get_edir_by_id(db=db, id=edir_id): raise HTTPException(status_code=404, detail="Oops, Edir doesn't exist") payments = get_all_members_payment(db=db, edir_id=edir_id, user_id=member_id, skip=skip, limit=limit) #if there's no payment if payments is None: raise HTTPException(status_code=404, detail="No payment exist") return payments #add payment @router.post("/") def add_new_payment(payment: PaymentCreate, email=Depends(auth_handler.auth_wrapper), db: Session = Depends(get_db),check_admin = Depends(admin)): if not get_member_by_member_id(db=db, id=payment.member_id): raise HTTPException(status_code=404, detail="Oops, User doesn't exist in this edir") return create_payment(db=db, payment=payment) #update payment @router.put("/{payment_id}") def update_member_payment(payment_id: int, payment: PaymentUpdate, email=Depends(auth_handler.auth_wrapper), db: Session = Depends(get_db), check_admin = Depends(admin)): return update_payment(db=db, payment_id=payment_id, payment=payment) #remove payment @router.delete("/{payment_id}") def remove_member_payment(payment_id: int, email=Depends(auth_handler.auth_wrapper), db: Session = Depends(get_db), check_admin = Depends(admin)): return delete_payment(db=db, payment_id=payment_id)
{"/app/db/repository/member.py": ["/app/dependencies/authorization.py", "/app/db/repository/user.py", "/app/schemas.py", "/app/db/models.py", "/app/db/repository/edir.py"], "/app/routers/v1/event.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/event.py", "/app/db/repository/edir.py"], "/app/routers/v1/auth.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/edir.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/edir.py", "/app/dependencies/authorization.py"], "/app/db/models.py": ["/app/db/database.py"], "/app/main.py": ["/app/db/database.py"], "/app/dependencies/authorization.py": ["/app/db/database.py", "/app/db/repository/user.py"], "/app/db/repository/payment.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/member.py"], "/app/routers/v1/user.py": ["/app/schemas.py", "/app/db/database.py", "/app/db/repository/user.py"], "/app/routers/v1/member.py": ["/app/dependencies/authorization.py", "/app/schemas.py", "/app/db/database.py", "/app/db/repository/member.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/event.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py", "/app/db/repository/edir.py"], "/app/db/repository/user.py": ["/app/schemas.py", "/app/db/models.py"], "/app/db/repository/edir.py": ["/app/schemas.py", "/app/db/models.py", "/app/db/repository/user.py"], "/app/routers/v1/payment.py": ["/app/dependencies/authorization.py", "/app/db/repository/payment.py", "/app/db/repository/member.py", "/app/db/repository/edir.py", "/app/db/database.py", "/app/schemas.py"]}
55,655
open-sourcepad/python-testing-framework
refs/heads/master
/libs/selenium.py
from selenium import webdriver from seleniumrequests import Firefox from selenium.webdriver.firefox.options import Options from seleniumrequests.request import headers class SeleniumError(Exception): pass class Selenium: def __init__(self, **kwargs): self.options = Options() self._options() def browser(self, url): try: driver = Firefox(options=self.options) driver.get(url) return driver except Exception as e: raise SeleniumUatError(f"Error setting instance of Firefox.\nError: {e}") def _options(self): self.options.headless = True
{"/models/base.py": ["/config.py"], "/main.py": ["/config.py", "/procedures.py"], "/config.py": ["/helpers/typecast_helper.py"], "/modules/sample.py": ["/libs/csv_reader.py", "/modules/base.py"], "/modules/base.py": ["/libs/selenium.py", "/config.py", "/libs/callback.py"], "/libs/csv_reader.py": ["/config.py"]}
55,656
open-sourcepad/python-testing-framework
refs/heads/master
/helpers/typecast_helper.py
for dtype in [ 'int', 'float', 'str', 'list', 'dict', 'tuple' ]: exec(f""" def to_{ dtype }(value): try: return {dtype}(value) except Exception as e: return value """)
{"/models/base.py": ["/config.py"], "/main.py": ["/config.py", "/procedures.py"], "/config.py": ["/helpers/typecast_helper.py"], "/modules/sample.py": ["/libs/csv_reader.py", "/modules/base.py"], "/modules/base.py": ["/libs/selenium.py", "/config.py", "/libs/callback.py"], "/libs/csv_reader.py": ["/config.py"]}