LaTeX, GitHub, Google Drive and ChatGPT in action

Chapter 1

In the life of every student there comes a moment when it is necessary to write a final qualifying work (WQR). Former graduates say that the success of the WRC largely depends on the correct execution of documentation, while the main content of the work remains in the background. But why not introduce an automated registration process that would comply with GOSTs and the internal standards of the university, would be convenient for the supervisor to check, and would allow the student to concentrate on the essence of his WRC project? In short, in the process of reading, you will learn why and how to implement LaTeX in the WRC, set up sending documents to Google Drive via Github Actions to recall the supervisor, and use contextual hints for ChatGPT.

Chapter 2. (Xe)LaTeX

All the benefits of using TeX can be found here https://www.ctan.org/tex. When writing a WRC, it is important:

  • TeX has the best output. Your document will have math formulas, lots of cross-references, and placement of floating environments (pictures, listings, tables).

  • TeX knows about typesetting. All layout will be in the document class, and macros are declared in the preamble.

  • TeX is fast. Compilation and document creation time is less than 1 second. You can use texstudio as your development environment which will automatically detect the compilation command with magical comments.

  • TeX is stable, but not rigid. For the convenience of using a custom Cyrillic font, you can use XeLaTeX.

  • The input is plain text. You can create documents using git features, Github, and Github Actions.

  • The output can be anything. The document can be compiled into PDF format.

  • TeX is free. Spreading distributions TeX system is provided free of charge.

  • TeX runs anywhere. My WRC and all the examples from the article were compiled on the Apple M1.

  • TeX is the standard. There are many packages available to meet your requirements, as well as many answers to questions on stack exchange, stack overflow, chat in Telegram.

My stack: MacTeX system distribution (TeXLive for Windows) and texstudio.

Document class

We create a class of the future document mirea.clswhich will provide backwards compatibility with the default class article. This class will only contain changes to existing constructs to ease the transition to the new format.

mirea.cls
% !TeX program  = xelatex
% !TeX encoding = UTF-8
% !TeX root     = course-work.tex
\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{mirea}[2023/09/01]


\DeclareOption*{\PassOptionsToClass{\CurrentOption}{extarticle}} 
\ProcessOptions\relax

\LoadClass[14pt, a4paper, titlepage]{extarticle}


\RequirePackage{hyperref}
\hypersetup{colorlinks=false, pdfborder={0 0 0}} % Отключение подсветки ссылок


\RequirePackage[english,main=russian]{babel}
\RequirePackage{fontspec}
\setmainfont{Times New Roman} % Если возникают проблемы при компиляции с данной строкой, необходимо на компьютер установить  Times New Roman
\RequirePackage{newtxmath} % Поменять гарнитуру в фомулах на Times New Roman

\RequirePackage[left=30mm, right=15mm, top=20mm, bottom=20mm]{geometry}

\RequirePackage{indentfirst} % Красная строка у первого абзаца раздела

\RequirePackage{graphicx}

\parindent=1.25cm % Размер красной строки

\parskip=0pt % Отступ между абзацами

\righthyphenmin=2 % Разрешить переносить слоги в 2 буквы (стандартное значение 3)

\linespread{1.3} % полуторный межстрочный интервал

\RequirePackage{tocbibind} % Добавить раздел содержание в содержание

% Настройка заголовка содержания
\addto\captionsrussian{\renewcommand{\contentsname}{Содержание}}

\RequirePackage[normalem]{ulem} % underline some lines


\RequirePackage{tocloft}
% Формат содержания
\renewcommand\cfttoctitlefont{\hfill\fontsize{16pt}{16pt}\selectfont\bfseries\MakeUppercase}
\renewcommand\cftaftertoctitle{\hfill\hfill}

%\setlength{\cftbeforesecskip}{0pt} % Addtional space between sections in toc

%\setlength{\cftsecindent}{0pt} % Remove indent in toc for \section
%\setlength{\cftsubsecindent}{0pt} % Remove indent in toc for \subsection
%\setlength{\cftsubsubsecindent}{0pt} % Remove indent in toc for \subsubsection

\renewcommand{\cftsecleader}{\cftdotfill{\cftdotsep}} % Добавить точки у разделов в содержании

\RequirePackage{placeins} % Команда \FloatBarrier для размещения плавающего окружения в пределах раздела, подраздела, пункта

% Настройка раздела, подраздела, подподраздела
\RequirePackage{titlesec}
\titleformat{\section}{\FloatBarrier\parskip=6pt\filcenter\fontsize{16pt}{16pt}\selectfont\bfseries\uppercase}{\thesection}{.5em}{}
\titleformat{\subsection}{\FloatBarrier\filcenter\bfseries}{\thesubsection}{.5em}{}
\titleformat{\subsubsection}{\FloatBarrier\filcenter\bfseries}{\thesubsubsection}{.5em}{}


\AddToHook{cmd/section/before}{\clearpage} % Начинать раздел с новой страницы

\renewenvironment{abstract}{\clearpage\section*{\MakeUppercase{\abstractname}}}{\clearpage}

\labelwidth=1.25cm % Горизонтальный отступ у элемента списка

% Ненумерованные списки разной вложенности
\renewcommand\labelitemi{---}
\renewcommand\labelitemii{---}
\renewcommand\labelitemiii{---}
\renewcommand\labelitemiv{---}

% Нумерованные списки разной вложенности
\renewcommand\labelenumi{\arabic{enumi})}
\renewcommand\labelenumii{\asbuk{enumii})}
\renewcommand\labelenumiii{\arabic{enumiii})}
\renewcommand\labelenumiv{\asbuk{enumiv})}

% Форматирование списков
\RequirePackage{enumitem}
\setlist{itemsep=0pt, parsep=0pt} % Возможна опция wide
\makeatletter
\AddEnumerateCounter*{\asbuk}{\c@asbuk}
\makeatother

\makeatletter
% Буквы для нумерации списка (исключены ё, з, щ, ч, ъ, ы, ь)
% Подробнее https://ctan.math.illinois.edu/macros/latex/required/babel/contrib/russian/russianb.pdf 
\def\russian@alph#1{\ifcase#1\or
	а\or б\or в\or г\or д\or е\or ж\or
	и\or к\or л\or м\or н\or о\or п\or 
	р\or с\or т\or у\or ф\or х\or ц\or 
	ш\or э\or ю\or я\else\@ctrerr\fi}
\def\russian@Alph#1{\ifcase#1\or
	А\or Б\or В\or Г\or Д\or Е\or Ж\or
	И\or К\or Л\or М\or Н\or О\or П\or 
	Р\or С\or Т\or У\or Ф\or Х\or Ц\or 
	Ш\or Э\or Ю\or Я\else\@ctrerr\fi}

\patchcmd{\l@section}{#1}{\textnormal{\uppercase{#1}}}{}{} % Разделы в содержании без выделения жирным, в верхнем регистре
\patchcmd{\l@section}{#2}{\textnormal{#2}}{}{} % Страницы без выделения жирным

\apptocmd{\appendix}{
	\renewcommand{\thesection}{\Asbuk{section}}
	\titleformat{\section}{\filcenter\fontsize{16pt}{16pt}\selectfont\bfseries}{}{0pt}{\MakeUppercase{\appendixname}~\thesection \\}{}{} % Изменение формата раздела приложения
	\renewcommand\thefigure{\Asbuk{section}.\arabic{figure}} % Изменении формата нумерации иллюстрации
	\renewcommand\thetable{\Asbuk{section}.\arabic{table}} % Изменении формата нумерации таблицы
	\renewcommand\theequation{\Asbuk{section}.\arabic{equation}} % Изменении формата нумерации формулы
	
	\let\oldsec\section
	\renewcommand{\section}{
		\clearpage
		\phantomsection
		\refstepcounter{section}
		\setcounter{figure}{0} % Счёт иллюстраций в пределах одного приложения
		\setcounter{table}{0} % Счёт таблиц в пределах одного приложения
		\setcounter{equation}{0} % Счёт иллюстраций в пределах одного приложения
		\addcontentsline{toc}{section}{\appendixname~\thesection}
		\oldsec*} % Нумерация раздела после названия
}

\makeatother


\RequirePackage[labelsep=endash]{caption} % Настройка пунктуации
\captionsetup[table]{justification=raggedright, singlelinecheck=false} % Выравнивание по левому краю надписи таблицы

\addto\captionsrussian{\renewcommand{\figurename}{Рисунок}} % Переопределение caption из babel


% Настройка заголовка списка использованных источников
\addto\captionsrussian{\renewcommand{\refname}{СПИСОК ИСПОЛЬЗОВАННЫХ ИСТОЧНИКОВ}}

\BeforeBeginEnvironment{thebibliography}{
	\phantomsection % для корректной ссылки в содержании 
	\makeatletter
	\renewcommand*{\@biblabel}[1]{#1.\hfill} % формат нумерации списка
	\makeatother}

\setlength{\bibindent}{-1.25cm} % Убрать отступы у элементов списка использованных источников + \{thebibliography}{99\kern\bibindent}

Document Preamble

The preamble of the document will contain and be supplemented by the import of the necessary packages, as well as the definition of new macros.

preamble.tex
% !TeX program  = xelatex
% !TeX encoding = UTF-8
% !TeX root     = course-work.tex
\usepackage{hyperref}
\hypersetup{pdftitle={Курсовая работа}, pdfauthor={Автор не указан}}

\usepackage{graphicx}

% Создание введения или заключения
\newcommand{\supersection}[1]{
	\section*{#1}
	\phantomsection
	\addcontentsline{toc}{section}{#1}
}

Main Document

course-work.tex
% !TeX program  = xelatex
% !TeX encoding = UTF-8
% !TeX root     = course-work.tex
\documentclass{mirea}

\include{preambule.tex}

\begin{document}
	
\addtocounter{page}{2}

% Содержание
\tableofcontents


\supersection{Введение}

\section{Аналитический раздел}

\subsection{Первый подраздел}
TODO

\subsubsection{Первый подподраздел}
TODO

\subsection*{Вывод по разделу}
TODO

\section{Специальный раздел}

\section{Технологический раздел}

\section{Экономический раздел}

\BeforeBeginEnvironment{thebibliography}{\clearpage\phantomsection}
\begin{thebibliography}{99\kern\bibindent}
	\bibitem{bib:mybook} Моя книга.
\end{thebibliography}

\appendix

\section{Первое приложение}

Первое приложение

\end{document}

Compilation example:

Document constructs

annotation

\begin{abstract}
    ...
\end{abstract}
Annotation titles

Annotation subsection

\subsection*{...}

Annotation subsection

\subsubsection*{...}

Content

\tableofcontents

PS If necessary, change the name to Оглавление possible in the document class

Introduction, conclusion, unnumbered section

\supersection{...}

Chapter

\section{...}

Subsection

\subsection{...}

Subsubsection

\subsubsection{...}

List of sources used

\BeforeBeginEnvironment{thebibliography}{\clearpage\phantomsection}
\begin{thebibliography}{99\kern\bibindent}
    \bibitem{bib:example} ...
    ...
\end{thebibliography}

Link to source

\cite{bib:example}

Application

\appendix
\section{...}
\label{appendix:...}
...
\section{...}
...

Application Link

\ref{appendix:...}

Lists

Unordered list
\begin{itemize}
	\item[] Пример списка с~тире:
	\item первый элемент,
	\item второй элемент.
\end{itemize}
numbered list
\begin{enumerate}
	\item[] Пример списка с~закрывающей скобкой и~числом:
	\item первый элемент,
	\item второй элемент.
\end{enumerate}
nested list
\begin{enumerate}
	\item[] Пример вложенного списка:
	\item первый уровень вложенности,
	\begin{enumerate}
		\item второй уровень вложенности;
		\begin{itemize}
			\item третий уровень вложенности;
			\item элемент;
			\item элемент.
		\end{itemize}
	\end{enumerate}
\end{enumerate}

Illustration

См. рисунок~\ref{fig:example} на~с.~\pageref{fig:example}.	
\begin{figure}[htb]
    \centering
    \includegraphics[width=.5\textwidth]{example.jpeg}
    \parskip=6pt
    \caption{Пример подписи}
    \label{fig:example}
\end{figure}

Table

См. таблицу~\ref{tab:example} на~с.~\pageref{tab:example}.
\begin{table}[htb]
    \caption{Пример подписи}
    \centering
    \begin{tabular}{ |c|c|c|c|c| } 
        \hline
        1 & 2 & 3 & 4 & 5 \\ \hline
        6 & 7 & 8 & 9 & 10 \\ \hline
    \end{tabular}
    \label{tab:example}
\end{table}

P.S. floating environments can float within a section (move from one subsection to another). To prevent this from happening, google option H from the package float.

Equation and formula

См. формулу~(\ref{eq:example}).
\begin{equation}\label{eq:example}
    \text{минус}\,a\times b=c ,
\end{equation}
где $a$~--- первая переменная; \\
$b$~--- вторая переменная; \\
$c$~--- третья переменная.

Chapter 3 Github

Let’s add a file .gitignore for TeX to exclude intermediate compilation files from Github push:

curl https://raw.githubusercontent.com/ValeryVerkhoturov/lost-and-found/main/course-work/.gitignore --output .gitignore

Chapter 4 Github Actions

In order for the supervisor to leave a comment, you can use the Github Issues functionality (although this is not always convenient), or use comments on the document on Google Drive. To upload a PDF document, I suggest creating a file .github/workflows/course-work-deploy.yml.

course-work-deploy.yml
name: Course Work Deploy
on:
  push:
    branches:
      - main

jobs:
  course-work-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Get current time
        uses: josStorer/get-current-time@v2
        id: current-time
        with:
          format: YYYY-MM-DD-HH:mm
          utcOffset: "+03:00"
          timezone: "Europe/Moscow"
      - name: Checkout code
        uses: actions/checkout@v2
      - name: Upload to gdrive
        uses: adityak74/google-drive-upload-git-action@main
        with:
          credentials: ${{ secrets.DRIVE_CREDENTIALS }}
          filename: course-work.pdf
          folderId: ${{ secrets.DRIVE_FOLDER_ID }}
          name: ${{ steps.current-time.outputs.formattedTime }}-sha-${{ github.sha }}.pdf
          overwrite: "true"

By instructions we get secrets.DRIVE_CREDENTIALS And secrets.DRIVE_FOLDER_ID, on Github add them to Settings ==> Settings and variables ==> Actions ==> Repository secrets. To sort a document, it is enough to apply sorting on Google Drive by name.

It remains to monitor comments to documents and delete old documents.

Chapter 5

To use the OpenAI API, you must have a valid key. To create a custom chat, you can use the GUI provided in the repository https://github.com/Yidadaa/ChatGPT‑Next‑Web. Go to the repository, click on the blue “Deploy” button, fill in the environment variables and access your chat. In the settings on the site, fill in the fields “Access code” and “API key”.

To avoid having to enter context in each new ChatGPT conversation, context hints can be used. To do this, click on the “Masks” button in the interface and select “Find more”. You can then create a contextual hint that can be used in further dialogs.

Hints:

  • system: You are an AI assistant who helps to write a term paper for the institute on the topic “My topic”.

  • user: Coursework consists of sections INTRODUCTION, ANALYTICAL SECTION, SPECIAL SECTION, TECHNOLOGICAL SECTION, ECONOMIC SECTION, CONCLUSION, LIST OF USED SOURCES. It is necessary to create subsections and fill them with content.

Other settings

Other settings

PS If you encounter difficulties with registration in OpenAI by phone number, you can use the SMS activation bot (for example, https://t.me/getPhoneNumberRoBot) or buy a registered account.

Chapter 6. Conclusion

I shared my experience of creating a document for the WRC. It is important to note that layout requirements may vary from university to university and may also depend on the chosen topic and teacher preferences. However, I will try to describe the general steps that can help you create a quality document.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *