Trending November 2023 # Creating Swift Forms Using Swiftforms Library # Suggested December 2023 # Top 14 Popular

You are reading the article Creating Swift Forms Using Swiftforms Library updated in November 2023 on the website Hatcungthantuong.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested December 2023 Creating Swift Forms Using Swiftforms Library

Definition of Swift forms

By the use of Swift forms, we can create forms that are interactive, easy to make by adding only a few lines in the code. In order to create forms in Swift, we have to use one external library, which is written in Swift only; this library provides great support to create forms in Swift. Before using it, we have to add this to our project. By the use of forms, we can create our own cells and use already-defined cells as well. In the coming section, we will see how to include this in our application to make the best use of it and see everything in detail.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

var variable_name = FormDescriptor()

In the above line of syntax, as you can see, we are using FormDescriptor() to create the instance here. This class would be available in the SwiftForms library; once you add it, then only we can access the classes and everything available inside it. We just have to give the variable_name after this; it can be used to access the various element available inside it to design our form in Swift. Let’s see one practice syntax to understand it better. See below;

e.g. :

var myform = FormDescriptor() myform.title = "Any title you want"

This is a sample syntax to use one of the attributes available in the FormDescriptor instance. In the coming section, we will see how to create a full form for users to enter data in detail that will be helpful for beginners to understand and start using it in real-life applications of Swift.

How do forms work in Swift?

As of now, we already know that forms are used to design a create interactive pages for users in Swift. Where we can ask the user to enter data that can be processed for further use, we can design login pages, registration pages, list show pages, and data rendering pages with the use of SwiftForms library. This is not ab inbuild feature available in Swift. Rather, we have to include one external library for it. That library is named ‘SwiftForms.’ This is also written in Swift language only, also it is very easy to use and optimizes the code because by using very few lines of code, we can design a good form.

Steps to follow:

1) Minimum requirement to setup this is ios 8.0 or above version

2) After this, we have to install ‘cocoapods’. This is a dependency manager; by the use of it; we can easily handle it. This provides support for swift frameworks. We are mentioning one simple command below which will help you to install the ‘cocoapods’ on your system; see below;

cmd:

gem install cocoapods

It will take a few minutes to install t.

3) Once ‘cocoapods’ is installed on your machine, we have to make some configurations in our project in order to use SwiftForms in our application. If we do not do this configuration, we will not be able to use SwiftForms in our application. Got to your podfile and did the configuration, which is mentioned below ;

pod 'SwiftForms'

4) After this, we have to install pod in our application; in order to install it, we have to run the following command see below;

pod install

5) open you Cartfile and try to add the below lines mentioned,

"ortuman/SwiftForms" :: rom ofical github documentation

Try to update it after the additional changes run the below command;

Carthage update

In this, we can define sections, rows, and other cells as per the requirement. Let’s discuss each of them in detail. See below;

1) section: This will create a section in your form. Inside this, we can create our field, cells, or anything we want But in order to use this, we have to use ‘FormSectionDescriptor’. This will be available once we have derived ‘FormViewController’ in our class. By the use of ‘FormSectionDescriptor,’ we can create its instance and use it to have a section on forms. Let’s see its syntax for a better understanding. See below;

e.g. :

var variable_name = FormSectionDescriptor()

As you can see, we are creating an instance of a section here using ‘FormSectionDescriptor’. After this, inside this section, we can define our fields, rows, etc.

2) Row: By using SwiftForms library, we can use ‘rows’ to properly define the structure of our form in SwiftForms. To create a row, we also have one class available from FormViewController that we have to use name das ‘FormRowDescriptor’. This class helps us to create rows in SwiftForms, which is very easy to use and define. Let’s see its syntax for a better understanding. See below;

e.g. :

var variable_name = FormRowDescriptor(tag: "", rowType: , title: "")

As you can see, while creating its instance, it takes three parameters as the input param here. Let’s discuss each of them in detail. See below;

tag: This is used to assign a tag to the row. This can be anything of our choice.

row type: This defines the type of the row and what it will be.

title: This is used to define a title for the row which makes it easy for a user to understand the row’s purpose.

3) To append row in Section: Once we have created the row Ans section instance successfully we have to append the row into the section, then only it will be visible inside the section; otherwise, it will not be visible on the form. To append them, we have one method named ‘append()’ that can be called on the section instance. Let’s see one sample syntax for a better understanding. See below;

section_instance.rows.append(your_row_instance)

In the above line of code, as you can see, we are using a section instance to append the row in the section; we just have to pass the row instance inside it.

In the same way, we can create as many sections and rows as we want to display on the form using the SwiftForms library. For this, we have one method named ‘section’ available on the form instance. Let’s see its syntax for better understanding and its usage see below;

e.g. :

your_form_instance.sections = [your section1, your section2, your section3 , and so on]

In this way, we can add a section to the form and display it. If you are using the SwiftForms library, then you have to follow the above-mentioned steps in order to run it.

Example

In this example, we are trying to use the Swiftforms library FormViewController to create forms in Swift. But make sure you have the proper environment setup on your machine; otherwise, it will not work on your machine. Also, add the dependency to make it work.

Code:

class DemoControllerForms: FormViewController { var myformdemo = FormDescriptor() myformdemo.title = "Demo to show forms in swift .." var section1 = FormSectionDescriptor() var row1 = FormRowDescriptor(tag: "email", rowType: .Email, title: "Uer Email") section1.rows.append(row1) var section2 = FormSectionDescriptor() var row2 = FormRowDescriptor(tag: "name", rowType: .Name, title: "User Name") section2.rows.append(row2) myformdemo.sections = [section1, section2] self.myformdemo = myformdemo }

Output:

Conclusion

Swift forms can easily be created by using the SwiftForms library. If you want to run your project, then you should have a proper environment setup on your machine; also, the dependency for SwiftForms also added properly; otherwise, it will not run and compile.

Recommended Articles

This is a guide to Swift forms. Here we discuss the Definition, syntax, and working of forms in Swift, along with examples and code implementation. You can also go through our other suggested articles to learn more –

You're reading Creating Swift Forms Using Swiftforms Library

7 Best Html Form Builders For Creating Forms Visually

An HTML form builder is a user-friendly tool or software that allows you to create web forms easily without the need for in-depth knowledge of HTML, CSS, or other web development languages. In simple terms, it’s like a digital toolbox that helps you create forms for your website quickly and efficiently, even if you don’t have a technical background.

To give you a better understanding, let’s break down the concept of an HTML form builder into simpler components.

HTML: HTML, or HyperText Markup Language, is the standard language used to create and design websites. It uses various elements, like tags and attributes, to define the structure and appearance of a web page.

Form: A form is a part of a web page that allows users to input and submit information. Forms are commonly used for tasks like signing up for newsletters, submitting inquiries, or placing orders online.

Builder: A builder, in this context, is a tool or software that simplifies the process of creating something—in this case, HTML forms—by providing pre-built components and a user-friendly interface.

By using a form builder, you can save time, reduce costs, and improve the quality of the data you collect from your website visitors. This article highlights the best HTML form builders, ranging from simple solutions for small projects to more diverse solutions for those who need surveys, quizzes, and similar types of functionality.

Easy to use: With a form builder, you don’t need any coding skills to create professional-looking web forms. The user-friendly interface and drag-and-drop functionality make the process straightforward and accessible to everyone.

Time and cost savings: Creating forms from scratch can be time-consuming and require specialized knowledge. A form builder saves you time and resources by providing pre-built components and templates to get you started.

Customization: Most form builders offer a variety of customization options, so you can create forms that match your website’s design and branding.

Improved data collection: By using a form builder, you can ensure that your forms are user-friendly and functional, resulting in more accurate and complete data collection.

Pre-built templates: Many form builders offer a selection of pre-designed templates that you can customize with your own content, branding, and desired input fields. These templates are designed to be visually appealing and compatible with various devices and browsers.

Drag-and-drop interface: A form builder typically features a drag-and-drop interface, allowing you to easily add, remove, and rearrange input fields and other form elements.

Form validation and security: Form builders often include features that help ensure your forms are secure and the data collected is accurate. This may include tools for form validation (e.g., making sure an email address is entered correctly) and protection against spam or malicious submissions.

Integration and data management: Once your form is complete, the form builder can generate the necessary HTML code for you to embed it into your website. Many form builders also offer integrations with popular platforms and tools, like email marketing services or customer relationship management (CRM) systems, making it easier to manage and analyze the data collected through your forms.

Wufoo

If you’re looking for a powerful HTML form builder, Wufoo is definitely worth considering. With its intuitive drag-and-drop interface and extensive customization options, it offers an unparalleled experience when it comes to creating online forms.

Founded in 2006, Wufoo is an online form builder that allows users to easily create forms for surveys, registrations, payment collection, and more. It offers an easy-to-use drag-and-drop interface that makes creating custom forms a breeze.

Key Features of Wufoo ⚙️

Ease of Use

Wufoo’s drag-and-drop interface makes it easy for anyone to create custom forms without any coding skills. It also offers pre-built templates that can be customized to suit your needs.

Customization Options

With Wufoo, you can customize every aspect of your form including fonts, colors, images and more. You can also add conditional logic to make forms more responsive and interactive.

Payment Integration

Wufoo integrates with popular payment gateways such as PayPal and Stripe, allowing users to easily collect payments through their forms.

Mobile Optimization

All forms created using Wufoo are mobile-responsive which means that they will look great on any device.

Pros

Easy-to-use interface.

Wide range of customization options.

Mobile-optimized.

High level of security.

Integrates with popular payment gateways.

Offers pre-built templates for quick form creation.

Cons

Limited number of third-party integrations compared to some competitors.

No option for offline data collection.

Limited reporting capabilities compared to top form builders.

Wufoo can be used for a wide range of applications such as:

Online registration forms.

Surveys and feedback forms.

Payment collection forms.

Order and booking forms.

Contact forms.

Wufoo vs Competitors

Wufoo vs Google Forms

Google Forms is a free form builder that offers basic form creation features. While it’s a great option for simple forms, it doesn’t offer the level of customization or payment integration that Wufoo does.

Wufoo vs JotForm

Overall, Wufoo is an excellent option for anyone looking to create custom HTML forms easily. Its drag-and-drop interface and extensive customization options make it stand out from other competitors in the market.

JotForm

Are you tired of the same old boring forms on your website? Do you want to make them more interactive and engaging? Look no further than JotForm, an HTML form builder that makes it easy to create beautiful and functional forms.

JotForm is one of the leading online form builders, with over 10 million users worldwide. It offers a range of templates, themes, and customization options that make it easy to create professional-looking forms in minutes. Whether you’re creating a simple contact form or a complex survey, JotForm has everything you need.

Key Features ⚙️

One of the standout features of JotForm is its drag-and-drop interface. This makes it easy to add fields, widgets, and other elements to your form without any coding knowledge. You can also customize the look and feel of your form with a range of design options including themes, colors, fonts, and logos.

JotForm also integrates with a huge range of apps and services including Google Drive, Dropbox, PayPal, MailChimp, and Salesforce. This allows you to easily manage your data and automate your workflow.

Another great feature is its collaboration tools. You can share forms with team members or clients for feedback or approval. You can also set up notifications to alert you when someone fills out a form or when certain criteria are met.

Pros

Easy-to-use drag-and-drop interface

Wide range of customization options

Integrations with popular apps and services

Collaboration tools for sharing and feedback

Advanced features like conditional logic and payment processing

Affordable pricing plans for individuals and businesses

Cons

Some features require paid plans

Limited branding options on lower tier plans

Relevant Comparisons

There are many other HTML form builders on the market, but JotForm stands out for its ease of use and wide range of features. Some of its main competitors include Google Forms, Wufoo, Typeform, and Formstack.

Compared to Google Forms, JotForm offers more customization options and integrations. Wufoo is similar in terms of features but has a less intuitive interface. Typeform is great for creating interactive forms but can be limited in terms of functionality. Formstack is a powerful tool for businesses but can be more expensive than JotForm.

Formstack

Formstack is an all-in-one solution that enables you to build custom forms, collect data securely and analyze responses in real-time. Here are some of its key features:

Drag-and-Drop Editor: Formstack’s drag-and-drop editor makes it easy to create forms in minutes even without any coding skills.

Custom Branding: You can customize your forms’ visual design with logos or brand colors.

Integrations: Formstack integrates with over 1000 apps such as Salesforce, Mailchimp and PayPal.

Mobile Forms: The software provides mobile responsive forms that work on any device.

Conditional Logic: You can set up conditions that determine which questions appear based on previous answers given by users.

Data Analytics: You can easily monitor responses with analytics dashboards and generate reports.

Pros

Ease of Use: With its user-friendly interface and drag-and-drop editor, anybody can create custom HTML forms without any coding experience needed.

Versatility: Formstack’s wide range of templates for different industries means it has applications in various sectors such as healthcare, education, real estate, and many more.

Integrations: With over 1000 app integrations, Formstack ensures that your data can be imported and exported to other platforms.

Collaboration: The software enables you to create and share forms with your team members in real-time.

Cons

Pricing: Formstack is relatively expensive compared to other form builders on the market.

Limited A/B Testing: A/B testing is only available on the Gold plan which could be a deal-breaker for some users who require this functionality.

Not Ideal for Complex Forms: While Formstack offers conditional logic functions to create complex forms, it may not have enough customization options for very complex forms.

Formstack is an ideal platform for businesses of all types and sizes. Here are a few ways companies can leverage this software:

Event Registration Forms: Create online registration forms for events of all kinds, including conferences, workshops or webinars.

Payment Processing Forms: With payment gateway integrations such as PayPal and Stripe, you can easily create payment processing forms for customers to purchase products or services directly from your website.

Comparisons

While Formstack provides excellent features and functionalities for creating HTML forms with ease, it’s worth noting how it stacks up against similar software on the market. Here are a few comparisons:

Formstack vs Google Forms

Formstack vs Wufoo

Wufoo is an excellent HTML form builder that offers similar features to Formstack. However, unlike Formstack, Wufoo has a limited number of integrations and does not provide mobile responsive forms. Additionally, it’s worth noting that Wufoo does not have a dedicated analytics dashboard like Formstack does.

Formstack vs Typeform

Formstack provides an all-in-one solution for creating custom HTML forms with ease. Its drag-and-drop editor, integrated payment processing options, mobile responsiveness, and extensive customization options make it an ideal platform for businesses of all sizes. Despite its higher price point compared to some other form builders on the market, its robust functionalities make it well worth the investment.

Typeform

Typeform is a powerful and comprehensive tool that allows users to create stunning and interactive forms. Here are some of its key features:

Easy-to-use interface: Typeform’s user interface is simple and intuitive, making it easy for users to create custom forms without any coding knowledge.

Customizable design: Users can customize their forms with different fonts, colors, backgrounds, and images to match their brand or style.

Powerful question types: Typeform offers various question types like multiple choice, rating scales, sliders, and more.

Integrations: Typeform integrates with numerous tools like Google Sheets, Mailchimp, Zapier, Salesforce, Slack, Trello and more.

Analytics dashboard: An analytics dashboard provides real-time feedback on responses received by your form.

Let’s take a closer look at the pros and cons of using Typeform as an HTML form builder:

Pros

Sleek design aesthetics

User-friendly interface

Large selection of templates available

Advanced features like conditional logic and branching

Excellent customer support

Cons

Limited number of responses per month with free plan

Higher pricing in comparison to other form builders

Limited customization options in the free plan

Typeform use cases

Typeform is an excellent option for businesses, organizations, and individuals looking to create various types of forms. Whether you need a simple contact form or a complex survey with conditional logic, Typeform provides the necessary tools to make it happen.

Here are some practical applications of Typeform:

Online surveys

Contact forms

Job application forms

Event registration forms

Newsletter sign-up forms

Cognito Forms

Cognito Forms was launched in 2014 with the aim of providing a user-friendly and affordable form builder for everyone. Since then, it has grown to become one of the best HTML form builders in the market. With over 100 templates to choose from, Cognito Forms allows users to create forms for various purposes, including registration forms, surveys, order forms and more.

Beyond its templates, Cognito Forms offers unparalleled flexibility in terms of customization. Users can add custom branding elements like logos and fonts to their forms with ease. Additionally, Cognito Forms integrates seamlessly with other applications like Microsoft Office 365 and Google Drive.

Key Features ⚙️

Cognito Forms offers a range of features that make it an excellent choice for anyone who needs to create online forms. Here are some of its most notable key features:

Easy-to-Use Interface

One of the things that sets Cognito Forms apart from other form builders is its intuitive interface. Even if you’re not tech-savvy, you’ll find that creating a form with this platform is straightforward and painless.

Customization Options

Cognito Forms offers a wide range of customization options. You can change everything from colors to fonts and even add your own custom CSS code for further personalization. Additionally, you can choose from over 20 question types when building your form.

Payment Integration

If you need to collect payments through your form (e.g., for event registration or product sales), Cognito Forms makes it easy thanks to its seamless integration with Stripe payments.

Conditional Logic

Cognito Forms also provides powerful conditional logic features. This allows you to show or hide questions based on previous answers, which makes your form more user-friendly and efficient.

Data Management

Cognito Forms offers robust data management features, including real-time analytics and easy data export. You can view your form submissions in real-time and even set up email notifications to alert you when a new submission comes in.

Like any tool, Cognito Forms has its fair share of pros and cons. Here are some of the most notable:

Pros

Intuitive interface

Extensive customization options

Payment integration with Stripe

Powerful conditional logic features

Robust data management capabilities

Cons

Limited form styling options compared to other form builders

No built-in integrations for email marketing services

Practical use cases

Cognito Forms can be used for a variety of purposes by businesses and individuals alike. Here are some of the most common practical applications:

Event Registration Forms

Creating event registration forms is a breeze with Cognito Forms. With its payment integration with Stripe, you can easily collect payments for events like conferences, workshops or concerts.

Customer Feedback Surveys

Cognito Forms offers over 20 question types so that you can customize surveys to get the specific feedback you need from your customers. With its robust data management features, it’s easy to analyze the results of your surveys.

Order Forms

If you need to collect orders for products or services online, Cognito Forms’ payment integration with Stripe makes this process seamless. You can create custom order forms that allow users to select products or services and pay online securely.

123FormBuilder

Are you looking for an easy-to-use HTML form builder to help you create professional and highly customizable forms without knowing how to code? Look no further than 123FormBuilder! This sophisticated online form building tool offers an all-in-one solution for creating forms that are tailored to your specific needs.

Key Features ⚙️

123FormBuilder is a highly versatile online form building tool that is packed with features designed to make form creation a breeze. Some of its key features include:

Drag-and-Drop Form Builder

With 123FormBuilder’s intuitive drag-and-drop interface, you can easily create forms from scratch or use one of their pre-built templates. The tool lets you add fields such as text boxes, checkboxes, and dropdown menus to your forms in seconds.

Custom Branding

123FormBuilder allows you to fully customize the look and feel of your forms by adding your company logo, changing colors and fonts, and more. This means that your forms will look professional and be consistent with your brand image.

Smart Conditional Logic

One standout feature of 123FormBuilder is its smart conditional logic capabilities. With this feature, you can create dynamic forms that adjust based on user responses. For instance, if someone selects “Yes” on a checkbox field asking if they want to receive newsletters from your company, you can set it up so that additional fields appear only if the response is “Yes.”

Advanced Security Measures

Integrations

123FormBuilder offers integrations with over 30 different platforms, including popular tools like Salesforce, Mailchimp, and Google Sheets. This lets you easily transfer data from your forms to other applications for further analysis and action.

Pros

The drag-and-drop interface makes it easy for anyone to create professional-looking forms.

Smart conditional logic allows you to create dynamic forms that adjust based on user responses.

Advanced security measures ensure that your data is safe and secure.

Over 30 integrations with popular platforms allow you to easily transfer form data to other applications.

123FormBuilder offers excellent customer support via email, phone, or live chat.

Cons

Some users may find the price of the tool a bit steep compared to other form builders on the market.

The tool has a steeper learning curve than some simpler form builders.

Google Forms

When it comes to creating online forms, one name that stands out from the crowd is Google Forms. As a part of the G Suite, Google Forms is a free form builder tool that offers an easy way to create surveys, quizzes, and polls without any coding skills needed. In this review, we’ll dive into the key features of Google Forms and compare it with other HTML form builders in the market.

Key Features ⚙️

Google Forms offers a range of features that make it stand out from its competitors. Here are some of its key features:

Easy-to-Use Interface

Google Forms has a user-friendly interface that makes it easy for anyone to build forms without any technical knowledge. With its drag-and-drop functionality, you can easily add various question types such as multiple-choice, checkbox, short answer, and more.

Customizable Themes

Google Forms offers customizable themes that allow you to personalize your forms with your preferred color schemes and images. You can also choose from pre-designed themes available on the platform.

Collaboration

Google Forms allows multiple users to collaborate on building forms in real-time. This feature makes it easy for teams working on a project to share their ideas and create better forms.

Integration with Other Tools

As part of G Suite, Google Forms integrates seamlessly with other tools like Google Sheets and Google Docs. Responses collected through your form can be automatically saved in real-time in a Google Sheet making it easier for analysis.

Here are some of the pros and cons of using Google Forms:

Pros

Free form builder tool.

User-friendly interface.

Customizable themes.

Collaboration feature.

Integration with other G Suite tools.

Offers a range of question types.

Cons

Limited customization options compared to other form builders.

No ability to add custom CSS or Javascript code snippets.

Limited branching and conditional logic options.

Google Forms can be used for a variety of different purposes. Here are some practical applications of this tool:

Surveys and Feedback Forms

Google Forms is an ideal tool for creating surveys and feedback forms. With its customizable themes and a range of question types, you can create engaging forms that capture valuable feedback from your customers, employees or stakeholders.

Quizzes and Assessments

Google Forms is also great for creating quizzes and assessments. You can add multiple-choice questions, short answer questions, or even upload images as questions. Responses collected through the form can be automatically graded making it easy to analyze results.

Event Registration Forms

If you are planning an event, Google Forms can be used to create registration forms to collect attendee details like names, emails, and other relevant information. You can also use conditional logic to show/hide certain fields based on responses given by attendees making it easier to collect only relevant information.

Google Forms Comparisons

Here’s how Google Forms stacks up against some of its competitors:

If you are looking for a basic form builder tool that is free and easy to use, Google Forms is definitely worth checking out.

Creating And Deploying Using Serverless Framework

Creating and Deploying using Serverless Framework

AWS Lambda can be created and deployed using serverless framework. It allows you to create AWS Lambda triggers and also deploy the same by creating the required roles. Serverless framework allows to handle big projects in an easier way. The events and resources required are written in one place and just a few commands helps in deploying the full functionality on AWS console.

In this chapter, you will learn in detail how to get started with AWS serverless framework.

Install Serverless Framework using npm install

To begin with, you need to first install nodejs. You can check for nodejs as follows −

You will have to use the following command to install serverless using npm package −

npm install -g serverless

Once npm is done, execute serverless command which shows the list of command to be used to create and deploy AWS Lambda function. Observe the screenshots given below −

You can also use sls instead of serverless. sls is the shorthand command for serverless.

In case you need help on the command sls, you can use the following command −

sls create --help

For creating a serverless framework, you have to follow the steps given below −

Step 1

To start using serverless framework, we need to add the credentials. By this, you can the user first in AWS console as follows −

Step 2

Step 3 Configure AWS Serverless Framework

Let us see how to configure AWS serverless framework. You can use the following command for this purpose −

sls config credentials --provider aws --key accesskey --secret secretkey

Note that the details of credentials entered, that is the access key and secret key are stored in the file /aws/credentials.

First, create a folder where you want your project files to be stored.

Next, we will start the work in aws-serverless folder.

Create AWS Lambda using Serverless Framework

Now, let us create a Lambda function with the serverless framework using the Steps given below −

Step 1

Following are the details for serverless create command −

Step 2

Now, we need to assign the template which are as follows −

AWS-nodejs, aws-nodejs-typescript, aws-nodejs-ecma-script, aws-python, aws-python3, aws-groovy-gradle etc.

Step 3

We shall make use of aws-nodejs template to create our first project using serverless framework. The command for the same purpose is as shown here −

sls create --template aws-nodejs

Note that this command creates a boilerplate for template aws-nodejs.

Step 4

Now, open the folder created in an IDE. Here we are using Visual Studio code and the folder structure is as follows −

Step 5

There are 2 files created: chúng tôi and chúng tôi

The AWS Lambda basic function details are shown in chúng tôi as follows −

'use strict'; const response = { statusCode: 200, body: JSON.stringify({ message: 'Go Serverless v1.0! Your function executed successfully!', input: event, }), }; callback(null, response); };

This file chúng tôi has the configuration details of the serverless framework as shown below −

# Welcome to Serverless! # # This file is the main config file for your service. # It's very minimal at this point and uses default values. # You can always add more config options for more control. # # For full config options, check the docs: # # Happy Coding! service: aws-nodejs # NOTE: update this with your service name # You can pin your service to only deploy with a specific Serverless version # Check out our docs for more details # frameworkVersion: "=XX.X" provider: name: aws runtime: nodejs6.10 # you can overwrite defaults here # stage: dev # region: us-east-1 # you can add statements to the Lambda function's IAM Role here # iamRoleStatements: # - Effect: "Allow" # Action: # - "s3:ListBucket" # Resource: { "Fn::Join" : ["", ["arn:aws:s3:::", { "Ref" : "ServerlessDeploymentBucket" } ] ] } # - Effect: "Allow" # Action: # - "s3:PutObject" # Resource: # Fn::Join: # - "" # - - "arn:aws:s3:::" # - "Ref" : "ServerlessDeploymentBucket" # - "/*" # you can define service wide environment variables here # environment: # variable1: value1 # you can add packaging information here #package: # include: # - include-me.js # - include-me-dir/** # exclude: # - exclude-me.js # - exclude-me-dir/** functions: hello: handler: handler.hello # The following are a few example events you can configure # NOTE: Please make sure to change your handler code to work with those events # Check the event documentation for details # events: # path: users/create # method: get # - s3: ${env:BUCKET} # - schedule: rate(10 minutes) # - sns: greeter-topic # - stream: arn:aws:dynamodb:region:XXXXXX:table/foo/stream/1970-01-01T00:00:00.000 # - alexaSkill: amzn1.ask.skill.xx-xx-xx-xx # - alexaSmartHome: amzn1.ask.skill.xx-xx-xx-xx # - iot: # sql: "SELECT * FROM 'some_topic'" # - cloudwatchEvent: # event: # Example: # - "aws.ec2" # detail-type: # - "EC2 Instance State-change Notification" # detail: # state: # - pending # - cloudwatchLog: '/aws/lambda/hello' # - cognitoUserPool: # pool: MyUserPool # trigger: PreSignUp # Define function environment variables here # environment: # variable2: value2 # you can add CloudFormation resource templates here #resources: # resources: # NewResource: # Type: AWS::S3::Bucket # Properties: # BucketName: my-new-bucket # Outputs: # NewOutput: # Description: "Description for the output" # Value: "Some output value"

Now, we need to add changes in chúng tôi file as per our requirements. You can use the commands as given below −

You can use the following command for Service −

service: aws-nodejs # NOTE: update this with your service name

Now, change the service here and add the name given to our folder as shown −

service: aws-serverless # NOTE: update this with your service name

The provider details are as shown −

provider: name: aws runtime: nodejs6.10

The provider is aws and runtime is nodejs6.10. We need to add the region in which we will be working and the stage, that is dev or prod environment for the project. So here are the updated details of provider:provider −

name: aws runtime: nodejs6.10 # you can overwrite defaults here stage: prod region: us-east-1 IAM Role

The iam role, that is, the code for permission to work with Lambda is shown here in the .yml file −

# iamRoleStatements: # - Effect: "Allow" # Action: # - "s3:ListBucket" # Resource: { "Fn::Join" : ["", ["arn:aws:s3:::", { "Ref" : "ServerlessDeploymentBucket" } ] ] } # - Effect: "Allow" # Action: # - "s3:PutObject" # Resource: # Fn::Join: # - "" # - - "arn:aws:s3:::" # - "Ref" : "ServerlessDeploymentBucket" # - "/*"

Note that we need to give the details of the role, that is the permission required with other AWS services, in the above section.

AWS Lambda Handler Details

The name of the export function in chúng tôi is hello. So the handler is name of the file followed by export name.

functions: hello: handler: handler.hello

The resource details about the s3 service added as shown below here −

# you can add CloudFormation resource templates here #resources: # resources: # NewResource: # Type: AWS::S3::Bucket # Properties: # BucketName: my-new-bucket # Outputs: # NewOutput: # Description: "Description for the output" # Value: "Some output value" Deploy AWS Lambda using Serverless Framework

Let us deploy the above lambda function to AWS console. You can use the following Steps for this purpose −

Step 1

First, you will have to use the following command −

sls deploy

Step 2

Now, you should see the function in AWS console now as shown. The details of serverless AWS are logged in AWS cloud formation. For this purpose, go to AWS service and select CloudFormation. The details of the AWS Lambda are displayed as follows −

Observe that the name given is project name followed by the stage used.

Step 3

It creates the iam role for AWS Lambda and log group for AWS cloudwatch. S3 bucket is created which has the code details stored and the configuration details.

This is created by the command sls deploy. You need not specify the iam role, instead it is created by default during the deploy stage.

Step 4

The detailed flow of events is displayed below in the cloud formation service.

AWS Lambda Code

The AWS Lambda code and its execution settings are shown in the screenshot given below −

When you test the Lambda function, you can find the following output −

The Log output for the above function is shown here −

We can also test the AWS Lambda function using the serverless command as shown below −

sls invoke --function hello

The syntax of the invoke command is shown here −

sls invoke --function hello

This invoke command triggers the AWS Lambda function and displays the output in the command prompt as shown below −

You can also test the Lambda function before deploying and the command for same using the following command −

sls invoke local --function hello

Please note that it is not always possible to test locally as the resources like S3 andDynanoDB cannot be simulated on the local environment. Only the basic function calls can be tested locally.

Using API Gateway and AWS Lambda with Serverless Framework

Let us see how to create new project to work with Lambda and api gateway. You can use the following command for this purpose −

sls create --template aws-nodejs

Now, open aws-api project in visual code. You can see that the chúng tôi and chúng tôi files created. Let us do the changes in that for addition of api gateway.

You will have to do the following changes in chúng tôi −

Now, the events details added for api gateway activation with AWS Lambda −

The path is the end-point which we will use when the api gateway path is created and method used is GET.

Observe that the handler is handler.hello, and hello is the export name from handler.js.

Note that you donot have to deploy the api gateway here, as the serverless framework will perform it.

Now, we will run the sls deploy command to create AWS Lambda function with trigger as api gateway.

sls deploy

Observe that the deploy details are listed above. It gives the Get url with the end-point as the path details. The stage is prod so same is used in the url. The name of the function is aws-api-prod-hello.

Let us hit the url and see the output. You can see the followings the response we get from the api-gateway get url −

{"message":"Go Serverless v1.0! Your function executed "GET","headers":{"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9, image/webp,image/apng,*/*;q=0.8","Accept-Encoding":"gzip, deflate, br","Accept-Language":"en-US,en;q=0.9","CloudFront-Forwarded-Proto": "false","CloudFront-Is-SmartTV-Viewer":"false","CloudFront-Is-Tablet-Viewer": "false","CloudFront-Viewer-Country":"IN","Host":"nvbhfdojfg.execute-api.us-east-1. (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36","Via":"2.0 chúng tôi (CloudFront)","X-Amz-Cf-Id":"j70MMqkWFp6kmvuauzp_nvTbI-WwKIQmm2Jl5hzSoN6gkdvX11hh-g==", "queryStringParameters":null,"pathParameters":null,"stageVariables":null, "GET","extendedRequestId":"H6P9fE-MoAMFdIg=","requestTime":"03/Jun/2023:14:23: 43 +0000","path":"/prod/first-api","accountId":"625297745038","protocol":"HTTP/1.1", "stage":"prod","requestTimeEpoch":1528035823928,"requestId":"b865dbd6-6739-11e8-b135 -a30269a8ec58","identity":{"cognitoIdentityPoolId":null,"accountId":null, "cognitoIdentityId":null,"caller":null,"SourceIp":"157.33.133.217","accessKey":null, "cognitoAuthenticationType":null,"cognitoAuthenticationProvider":null,"userArn":null, "userAgent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36","user":null},"apiId":"nvbhfdojfg"},"body":null, "isBase64Encoded":false}}

The output we get from api gateway are only the body details such as message and input. The response is totally controlled by the api gateway and how to display it as output.

Now, let us pass inputs to the GET url in query string and see the display −

Then you can see the output of querystring as shown below −

{"message":"Go Serverless v1.0! Your function executed "GET","headers":{"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9, image/webp,image/apng,*/*;q=0.8","Accept-Encoding":"gzip, deflate, "CloudFront-Is-Desktop-Viewer":"true","CloudFront-Is-Mobile-Viewer":"false", "CloudFront-Is-SmartTV-Viewer":"false","CloudFront-Is-Tablet-Viewer":"false", "upgrade-insecure-requests":"1","User-Agent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36","Via":"2.0 chúng tôi (CloudFront)","X-Amz-Cf-Id":"JIBZw3I-blKbnpHP8LYXPVolCgdW5KmEukZS4at9mi4vrWBMI-UKNw==", "X-Amzn-Trace-Id":"Root=1-5b13ff90-7d6e38d4c0e4a5d4e6184f30","X-Forwarded-For": Parameters":{"displaymessage":"Hello"},"pathParameters":null,"stageVariables":null, "GET","extendedRequestId":"H6TeiG34oAMFguA=","requestTime":"03/Jun/2023:14:47:44 +0000","path":"/prod/first-api","accountId":"625297745038","protocol":"HTTP/1.1", "stage":"prod","requestTimeEpoch":1528037264252,"requestId":"12e5dca3- 673d-11e8-8966-69fcf43bd4db","identity":{"cognitoIdentityPoolId":null,"accountId":null, "cognitoIdentityId":null,"caller":null,"exmpleIp":"157.33.133.217","accessKey":null, "cognitoAuthenticationType":null,"cognitoAuthenticationProvider":null,"userArn":null, "userAgent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36","user":null},"apiId":"nvbhfdojfg"},"body": null,"isBase64Encoded":false}}

Let us change the AWS Lambda function to just display the querystring details as shown below −

'use strict'; const response = { statusCode: 200, body: JSON.stringify({ message:(event.queryStringParameters && event.queryStringParameters.displaymessage!="") ? event.queryStringParameters.displaymessage : 'Go Serverless v1.0! Your function executed successfully!' }), }; callback(null, response); };

Observe that we have changed the message based on the querystring display message. This will deploy the the function again and check the output. It displays the details present in query string variable display message as shown below.

Let us now add post method to the events created as shown below −

Now, deploy the changes made and you can see the following output from the deploy command −

Note that testing post url in browser directly will not give the details. You should test the post url in postman.

This displays the message we have added in the Lambda function.

Advertisements

Creating Dynamic Ranking Tables Using Rankx In Power Bi

In this tutorial, we’ll look at a unique technique inside Power BI that allows us to create dynamic ranking tables using the RANKX function. You may watch the full video of this tutorial at the bottom of this blog.

What are Dynamic Ranking Tables?

Dynamic Ranking Tables showcase a range of information dynamically in a table, but the information shown is based off a specific ranking on a singular calculation.

We can look at the Top 20 Customers, based on Sales, across a range of other metrics, like Profits, Margin, Growth, etc. This technique will also automatically update the table after any change of context to the report page.

Let’s have a look at the Top 20 Customers in the table.

You can see the Profit Growth Year On Year table which requires the development of a few formulas to arrive at this measure. You can achieve these complex insights by overlaying the same techniques you would use when doing something relatively simpler.

In the formula for Profit Growth Year On Year, you can see that in evaluating a particular customer, it becomes ranked between a certain value based on a particular metric.

The filtering is done by using RANKX. The customer ranking is based on the Profit This Year versus Profit Last Year which will show the Profit Growth.

Ranking this particular measure will help you know which of these particular customers are within the Top 20 together with the specific results you want to highlight based on this metric.

You can see that the table only shows 20 results when there are, in fact, hundreds of customers. But because the customer data is isolated based on a specific metric, only 20 customers appear in the table.

Jumping to a different time frame will update the results but will still continue to show the Top 20 Customers.

You can also show the Top 20 Customers together with their Profit Growth and show other metrics to try and identify what caused the growth.

This growth in Profit could be due to an increase in Margins or an increase in Sales.

In the formula for Sales Growth Year On Year, you can see that the FILTER function has exactly the same structure as the previous formula, but instead of showing the Profit, it will display the Sales This Year versus Last Year.

This is going to evaluate to TRUE, which in this case is our customers. Then the same logic will play out so that profits between last year and this year stay within in the Top 20 metric.

That’s how you can isolate that particular insight and only show it for the most valued customers.

You can put Sales and Profit Growth in the Dynamic Ranking Table alongside The Top 20 Customers to gain better insights in your reports.

You can also do the exact same thing for Margin Growth.

You can see that the filtering done inside of CALCULATE is exactly the same as how it was done in the previous formulas.

Before, the Top Customers were only identified based on their Profit Growth. But now, the Margin metric can be isolated to see if the reason for the increase in Profit is due to the increase in Margins.

If you look at this table, you can see that the customer (EMD Group) has a negative Margins Growth.

However, you can see that despite having a negative Margins Growth, the customer continues to belong in the Top 20 because of its high Sales Growth resulting in high growths in Profits.

Simply looking at the table can give you more valuable insights into your reports and business.

When you set all this up in Power BI, you’ll see that it’s a great way of drilling into your top and bottom results.

This is a great way of incorporating a number of different measures and visualization techniques to create compelling reports that your consumers are going to love.

All the best,

Sam

An Introduction To Creating Stylized Sketches Of Faces Using Jojogan

This article was published as a part of the Data Science Blogathon.

Style transfer is a developing field in neural networks and it is a very useful feature that can be integrated into social media and AI apps. Several neural networks can map and transfer image styles to an input image as per the training data. In this article, we will look into JojoGAN and the process of using just one reference style to train and generate sketches of any image with that style.

Impact of One-shot Face Stylization

One-shot face stylization can be used in AI apps, social media filters, fun applications, and business use cases. With the rising popularity of AI-generated image and video filters, along with their use in social media reels and short videos, images, one-shot face stylization is a useful feature that these apps and social media companies can integrate into their products for the end-user.

So let’s narrow down on a popular GAN architecture for generating face stylizations at one go – JojoGAN.

JojoGAN Architecture

JojoGAN architecture works on a simple process of mapping a style to an image and learning the mapping to reproduce it for other unseen images in one shot. It uses a reversal process for GANs and the style mixing property of StyleGAN to create a one-to-one combined dataset pair from just one style. This dataset then is used for fine-tuning StyleGAN, and new input images can be used which the JojoGAN will convert to that specific style based on GAN Inversion.

JojoGAN Architecture and Workflow

JojoGAN can be trained in very little time (less than 1 minute) with just one reference style and produces high-quality stylized images.

Some examples of JojoGAN generated stylized images:

JojoGAN Examples

The stylized images can be generated on a variety of different input stylizations and can be modified.

JojoGan Code Deep Dive

Let’s look at the implementation of JojoGAN to generate stylized portraits. Several pre-trained models are available, and they can be trained on our style images, or the model can be modified to change the styles at minute levels.

Setup and Imports for JojoGAN

Clone the JojoGAN repo and import the necessary libraries. Create some folders in Google Colab storage for storing the inversion code, style images, and models.

%cd JoJoGAN !pip install tqdm gdown scikit-learn==0.22 scipy lpips dlib opencv-python wandb !sudo unzip chúng tôi -d /usr/local/bin/

import torch torch.backends.cudnn.benchmark = True from torchvision import transforms, utils from util import * from PIL import Image import math import random import os import numpy from torch import nn, autograd, optim from chúng tôi import functional from tqdm import tqdm import wandb from model import * from e4e_projection import projection from google.colab import files from copy import deepcopy from chúng tôi import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials



Model Files

Download the model files with Pydrive. A set of drive ids are available for pre-trained models. These pre-trained models can be used for generating stylized images on the go, and have different levels of accuracy. Later, user-created models can be trained.

#Download models download_with_pydrive = True device = 'cuda' #['cuda', 'cpu']

!bzip2 -dk shape_predictor_68_face_landmarks.dat.bz2 !mv shape_predictor_68_face_landmarks.dat models/dlibshape_predictor_68_face_landmarks.dat %matplotlib inline

drive_ids = { "stylegan2-ffhq-config-f.pt": "1Yr7KuD959btpmcKGAUsbAk5rPjX2MytK", "e4e_ffhq_encode.pt": "1o6ijA3PkcewZvwJJ73dJ0fxhndn0nnh7", "restyle_psp_ffhq_encode.pt": "1nbxCIVw9H3YnQsoIPykNEFwWJnHVHlVd", "arcane_caitlyn.pt": "1gOsDTiTPcENiFOrhmkkxJcTURykW1dRc", "arcane_caitlyn_preserve_color.pt": "1cUTyjU-q98P75a8THCaO545RTwpVV-aH", "arcane_jinx_preserve_color.pt": "1jElwHxaYPod5Itdy18izJk49K1nl4ney", "arcane_jinx.pt": "1quQ8vPjYpUiXM4k1_KIwP4EccOefPpG_", "arcane_multi_preserve_color.pt": "1enJgrC08NpWpx2XGBmLt1laimjpGCyfl", "arcane_multi.pt": "15V9s09sgaw-zhKp116VHigf5FowAy43f", "sketch_multi.pt": "1GdaeHGBGjBAFsWipTL0y-ssUiAqk8AxD", "disney.pt": "1zbE2upakFUAx8ximYnLofFwfT8MilqJA", "disney_preserve_color.pt": "1Bnh02DjfvN_Wm8c4JdOiNV4q9J7Z_tsi", "jojo.pt": "13cR2xjIBj8Ga5jMO7gtxzIJj2PDsBYK4", "jojo_preserve_color.pt": "1ZRwYLRytCEKi__eT2Zxv1IlV6BGVQ_K2", "jojo_yasuho.pt": "1grZT3Gz1DLzFoJchAmoj3LoM9ew9ROX_", "jojo_yasuho_preserve_color.pt": "1SKBu1h0iRNyeKBnya_3BBmLr4pkPeg_L", "art.pt": "1a0QDEHwXQ6hE_FcYEyNMuv5r5UnRQLKT", } # from StyelGAN-NADA class Downloader(object): def __init__(self, use_pydrive): self.use_pydrive = use_pydrive if self.use_pydrive: self.authenticate() def authenticate(self): auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() self.drive = GoogleDrive(gauth) def download_file(self, file_name): file_dst = os.path.join('models', file_name) file_id = drive_ids[file_name] if not os.path.exists(file_dst): print(f'Downloading {file_name}') if self.use_pydrive: downloaded = self.drive.CreateFile({'id':file_id}) downloaded.FetchMetadata(fetch_all=True) downloaded.GetContentFile(file_dst) else: !gdown --id $file_id -O $file_dst downloader = Downloader(download_with_pydrive)

downloader.download_file('stylegan2-ffhq-config-f.pt') downloader.download_file('e4e_ffhq_encode.pt') Load the Generators

Load the original and finetuning generators. Set the transfomer for resizing and normalizing the images.

latent_dim = 512 # Load original generator original_generator = Generator(1024, latent_dim, 8, 2).to(device) ckpt = torch.load('models/stylegan2-ffhq-config-f.pt', map_location=lambda storage, loc: storage) original_generator.load_state_dict(ckpt["g_ema"], strict=False) mean_latent = original_generator.mean_latent(10000) # to be finetuned generator generator = deepcopy(original_generator) transform = transforms.Compose( [ transforms.Resize((1024, 1024)), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)), ] ) Input Image

Set the input image location. Align and crop face and restyle the projection.

#image to the test_input directory and put the name here filename = 'face.jpeg' #@param {type:"string"} filepath = f'test_input/{filename}' name = strip_path_extension(filepath)+'.pt' # aligns and crops face aligned_face = align_face(filepath) # my_w = restyle_projection(aligned_face, name, device, n_iters=1).unsqueeze(0) my_w = projection(aligned_face, name, device).unsqueeze(0)

Input Image – Elon Musk

Pre-trained Sketches

Select the pre-trained sketch type and choose the checkpoint without color preservation for better results.

plt.rcParams['figure.dpi'] = 150 pretrained = 'sketch_multi' #['art', 'arcane_multi', 'sketch_multi', 'arcane_jinx', 'arcane_caitlyn', 'jojo_yasuho', 'jojo', 'disney'] #Preserve color tries to preserve color of original image by limiting family of allowable transformations. if preserve_color: ckpt = f'{pretrained}_preserve_color.pt' else: ckpt = f'{pretrained}.pt' Generate Results

Load the checkpoint and generator and set a seed value, and start generating the stylized image. The input image used for Elon Musk will be stylized according to the sketch type.

#Generate results n_sample = 5#{type:"number"} seed = 3000 #{type:"number"} torch.manual_seed(seed) with torch.no_grad(): generator.eval() z = torch.randn(n_sample, latent_dim, device=device) original_sample = original_generator([z], truncation=0.7, truncation_latent=mean_latent) sample = generator([z], truncation=0.7, truncation_latent=mean_latent) original_my_sample = original_generator(my_w, input_is_latent=True) my_sample = generator(my_w, input_is_latent=True) # display reference images if pretrained == 'arcane_multi': style_path = f'style_images_aligned/arcane_jinx.png' elif pretrained == 'sketch_multi': style_path = f'style_images_aligned/sketch.png' else: style_path = f'style_images_aligned/{pretrained}.png' style_image = transform(Image.open(style_path)).unsqueeze(0).to(device) face = transform(aligned_face).unsqueeze(0).to(device) my_output = torch.cat([style_image, face, my_sample], 0)

Generated Result

The results are generated for pre-trained sketch type ‘Jojo’ and look fairly accurate.

Now let’s look at training the GAN on self-created styles/sketches.

Train with your style images

Select some sketches of faces or even create some face sketches of your own and load these image(s) for training the GAN, and set the path. Crop and Align the face and perform GAN inversion.

names = ['1.jpg', '2.jpg', '3.jpg'] targets = [] latents = [] for name in names: style_path = os.path.join('style_images', name) assert os.path.exists(style_path), f"{style_path} does not exist!" name = strip_path_extension(name) # crop and align the face style_aligned_path = os.path.join('style_images_aligned', f'{name}.png') if not os.path.exists(style_aligned_path): style_aligned = align_face(style_path) style_aligned.save(style_aligned_path) else: style_aligned = Image.open(style_aligned_path).convert('RGB') # GAN invert style_code_path = os.path.join('inversion_codes', f'{name}.pt') if not os.path.exists(style_code_path): latent = projection(style_aligned, style_code_path, device) else: latent = torch.load(style_code_path)['latent'] latents.append(latent.to(device)) targets = torch.stack(targets, 0) latents = torch.stack(latents, 0)

Custom Style Sketch

Finetune StyleGAN

Finetune StyleGAN by adjusting the alpha, color preservation, and setting the number of iterations. Load the discriminator for perceptual loss and reset the generator.

#Finetune StyleGAN #alpha controls the strength of the style alpha = 1.0 # min:0, max:1, step:0.1 alpha = 1-alpha #preserve color of original image by limiting family of allowable transformations preserve_color = False #Number of finetuning steps. num_iter = 300 #Log training on wandb and interval for image logging use_wandb = False log_interval = 50 if use_wandb: wandb.init(project="JoJoGAN") config = wandb.config config.num_iter = num_iter config.preserve_color = preserve_color wandb.log( {"Style reference": [wandb.Image(transforms.ToPILImage()(target_im))]}, step=0) # load discriminator for perceptual loss discriminator = Discriminator(1024, 2).eval().to(device) ckpt = torch.load('models/stylegan2-ffhq-config-f.pt', map_location=lambda storage, loc: storage) discriminator.load_state_dict(ckpt["d"], strict=False) # reset generator del generator generator = deepcopy(original_generator) g_optim = optim.Adam(generator.parameters(), lr=2e-3, betas=(0, 0.99))

Train the generator to generated image from the latent space, and optimize the loss.

if preserve_color: id_swap = [9,11,15,16,17]

z = range(numiter)

for idx in tqdm( z):

mean_w = generator.get_latent(torch.randn([latents.size(0), latent_dim]).to(device)).unsqueeze(1).repeat(1, generator.n_latent, 1) in_latent = latents.clone() in_latent[:, id_swap] = alpha*latents[:, id_swap] + (1-alpha)*mean_w[:, id_swap] img = generator(in_latent, input_is_latent=True) with torch.no_grad(): real_feat = discriminator(targets) fake_feat = discriminator(img) loss = sum([functional.l1_loss(a, b) for a, b in zip(fake_feat, real_feat)])/len(fake_feat) if use_wandb: wandb.log({"loss": loss}, step=idx) if idx % log_interval == 0: generator.eval() my_sample = generator(my_w, input_is_latent=True) generator.train() wandb.log( {"Current stylization": [wandb.Image(my_sample)]}, step=idx) g_optim.zero_grad() loss.backward() g_optim.step()

Generate the Results using JojoGAN

Now generate the results. Below the results have been generated for both the original and sample images for comparison.

#Generate results n_sample = 5 seed = 3000 torch.manual_seed(seed) with torch.no_grad(): generator.eval() z = torch.randn(n_sample, latent_dim, device=device) original_sample = original_generator([z], truncation=0.7, truncation_latent=mean_latent) sample = generator([z], truncation=0.7, truncation_latent=mean_latent) original_my_sample = original_generator(my_w, input_is_latent=True) my_sample = generator(my_w, input_is_latent=True) # display reference images style_images = [] for name in names: style_path = f'style_images_aligned/{strip_path_extension(name)}.png' style_image = transform(Image.open(style_path)) style_images.append(style_image) face = transform(aligned_face).to(device).unsqueeze(0) style_images = torch.stack(style_images, 0).to(device)

my_output = torch.cat([face, my_sample], 0) output = torch.cat([original_sample, sample], 0)

Generated Results

That’s All! Now you can generate your style of image sketches using JojoGAN. The results are fairly impressive, but can further be improved by tweaking the training methods and having mo

Con

JojoGAN has been able to accurately map and transfer user-defined styles in a fast and effective manner. The key takeaways are: 

JojoGAN can be trained with just one style to map it easily and create stylized images of any face

JojoGAN is very fast and effective and can be trained in less than a minute

The results are highly accurate and resemble realistic portraits

JojoGAN can be easily fine-tuned and modified which makes it suitable for AI apps

Thus JojoGAN is the ideal neural network for style transfer regardless of the style type, shapes and color and can thus be a very useful feature in various social media apps and  AI applications.

References

Featured Image Architecture Examples Elon MuskMona Lisa Paper

About the Author

The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion. 

Related

Asus Rog Swift Pg32Uqx Review: Mini

Pros

Excellent gaming performance

4K resolution

Dimmable mini-LED backlight

Ergonomic adjustment options

Cons

High power consumption

Extremely expensive

Our Verdict

The Asus ROG Swift PG32UQX is a top-class 4K gaming monitor. But with all of its high-end features, it should only be appealing to professional gamers or hardcore enthusiasts with big wallets—Asus is asking an astronomical $2,999 for the 32-inch display. In return, however, you get a screen that raises the bar, and takes gaming to a new level.

Best Prices Today: Asus ROG Swift PG32UQX

Retailer

Price

The Asus ROG Swift PG32UQX comes loaded with a ton of great features—it’s the first gaming monitor equipped with a locally dimmable mini-LED backlight. You might have to empty your savings account to purchase it, but just think of all the crystal-clear, beautiful gaming you can play. There aren’t many displays that can stand up to the specs on this monitor right now, but it’s ultimately built for only the most hardcore of gamers. Still, if you’re looking for the best, you may just have found it.

Note: This review is part of our ongoing roundup of the best gaming monitors. Go there to learn more about competing products, what to look for in a gaming monitor, and buying recommendations.

Asus ROG Swift PG32UQX: Specs and features

The Asus ROG Swift PG32UQX has a whole series of superlatives in terms of specs. It’s the first gaming monitor with mini-LED lighting divided into 1,152 independently controllable zones. As a result, the gaming screen achieves a very demanding DisplayHDR 1400 certification, which requires an extremely high luminance of 1400 cd/m2. The Asus ROG Swift PG32UQX definitely delivers unsurpassed image quality. As a special service, Asus even calibrates each model for customers individually before delivery.

Display size 32-inch

Native resolution 3840×2160

Panel type IPS / 16:9

Refresh rate 144Hz

Adaptive Sync Compatible with NVIDIA’s G-Sync and AMD FreeSync

Ports 1 DisplayPort, 3 HDMI, 3 USB, 1 audio jack

Stand adjustment Height, tilt, swivel

VESA mount Yes, 100x100mm

Speakers No

HDR Yes, DisplayHDR 1400

Price $2,999

The 32-inch display with its resolution of 3840×2160 pixels synchronizes with the latest G-Sync Ultimate technology. While it is optimized to run at a maximum frame rate of 144Hz on Nvidia graphics cards, it also runs problem-free with AMD graphics cards. Other highlights of the IPS panel are the 98% and 160% coverage of the DCI-P3 and sRGB color range, as well as a small OLED display—called Livedash—in the lower panel frame. This nifty feature shows various system information, such as CPU temperature and GPU information.

Asus ROG Swift PG32UQX: Image quality

As already indicated, the Asus ROG Swift PG32UQX has outstanding image quality with high brightness and very strong contrast. Together with the neutral color reproduction, the UHD gaming monitor delivers an incredibly realistic and vivid picture. With image quality this impressive, gaming is taken to a whole other level of fun. 

Assuming a powerful graphics card, such as Nvidia RTX 3080 or AMD RX 6800 XT, the Asus ROG Swift PG32UQX demonstrates impressive performance in responsive shooters and fast racing simulations, but it can’t quite live up to the significantly faster WQHD and FHD models, which offer 240 to 360 Hertz refresh rate.

Image errors are not likely to be found in any game situation. On the contrary, the 32-inch display will almost always provide a buttery-smooth image. However, the UHD monitor shows its best gaming performance with HDR. 

Here, the 32-inch monitor achieves a dynamic range and a quality that no other gaming monitor in our tests has yet achieved. Strategy and role-playing enthusiasts will also enjoy the Asus ROG Swift PG32UQX monitor with its incredible image quality and rich detail.

Asus ROG Swift PG32UQX: UHD gaming monitor with dimmable mini-LED backlight

PC Welt

Asus ROG Swift PG32UQX: Features

The Asus ROG Swift PG32UQX comes with a DisplayPort input and three HDMI interfaces, with all four providing the maximum refresh rate of 144Hz under G-Sync. There are also three USB outputs, two of which are USB 3.1, and a headphone jack. Fortunately, all connection cables are included with the monitor. 

Various LED light strips are also integrated, which can be adapted to the gameplay using Asus Aura technology. An interesting gimmick is the tripod mount integrated into the middle of the lower panel frame to mount a webcam for streaming.

Asus ROG Swift PG32UQX: Three HDMI ports and one DisplayPort interface

PC Welt

The Asus ROG Swift PG32UQX has all the ergonomic adjustment options you need for long, fatigue-free gaming. The stable mount allows the screen to be rotated, tilted, and adjusted in height within a comfortable range. The on-screen menu offers seven preset gaming modes, such as racing, RTS, FPS, and environmental. There are also crosshair, timer, and stopwatch features. 

Asus ROG Swift PG32UQX: Convenient configuration is done via a rotary wheel below the monitor’s lower frame.

PC Welt

Asus ROG Swift PG32UQX: Power consumption

Due to the high maximum brightness, the 32-inch display consumes a ton of electricity at around 75 watts. If you reduce the brightness between 150 to 200 cd/m2, the energy requirement drops to a (still high) 50 to 60 watts. In standby mode, however, the value is a mere 0.3 watts.

Final thoughts

The Asus ROG Swift PG32UQX is ideal for hardcore gamers who want to push their experience to the max. You’ll see a high level of detail, perfect for zooming in on your individual units in those real-time strategy games. And in racing and RPG games like GTA Online the colors are rich and look spectacular.

If you’re partial to action games with fast motions, the 144Hz should do well for even the most demanding titles. The only drawback is that, between the sticker price and the power costs to keep it running at high performance, you’ll pay a small fortune.

This review originally appeared on PC-Welt, PCWorld’s German sister site.

Update the detailed information about Creating Swift Forms Using Swiftforms Library on the Hatcungthantuong.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!