extr.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. #!/home/moi/Memoires/venv/bin/python
  2. # de docx ou odt ver LaTeX
  3. #
  4. import sys,pypandoc,os,re,subprocess,yaml,hashlib
  5. #---------------------------------------------
  6. #sys.path.append(f"{os.getcwd()}/..")
  7. sys.path.append("/home/moi/Memoires/progs")
  8. from memmod import *
  9. import parsebib
  10. #----
  11. def fancyshort(s,t):
  12. # restreindre le texte de fancyhead (s est le nom, t le titre,
  13. # qu'il faut éventuellement racourcir pour qu'il tienne sur une seule
  14. # ligne.
  15. #
  16. # s (le nom de l'orateur, par exemple) est toujours affiché.
  17. # t est éventuellement raccourci.
  18. #
  19. # NOTE : ne devrait plus être utile, car on définira plutôt
  20. # ---- un "titre court"
  21. #
  22. limit =75 #taille max en caratères
  23. if len(s+t)<limit:
  24. return s,t
  25. else:
  26. tl=t.split()
  27. tl.pop()
  28. while sum(len(x) for x in tl)>limit:
  29. tl.pop()
  30. return s, " ".join(tl)+"\\ldots"# pointillés à la fin.
  31. def star_sec(l):
  32. # \section est transformée en \section* et on ne garde comme argument
  33. # que ce qui est nécessaire.
  34. it=iter(L)
  35. ret=[]
  36. passed= False
  37. for x in it:
  38. if "begin{document" in x:
  39. passed= True
  40. if passed and "section[" in x:
  41. s=x
  42. while "label" not in x:
  43. x=next(it)
  44. s=s+" "+x
  45. if not "}" in s:
  46. x=next(it)
  47. s=s+x
  48. k=s.find("]")
  49. r=(s[:k]+"}").replace("[","*{")+" "
  50. ret.append(r)
  51. ret.append("\n")
  52. else:
  53. ret.append(x)
  54. return ret
  55. #---------------------------------------------------------------------
  56. # ligne de command [nocompile]
  57. #
  58. # nocompile pour ne pas compiler
  59. #
  60. #
  61. compile= not "nocompile" in sys.argv
  62. #
  63. # Tout citer, si citeall sur la ligne de commade
  64. # (et biblio defini dans data.yml):
  65. citeall = "citeall" in sys.argv
  66. #-----------------------------------------------------------------------
  67. # Construire le titre à partir du fichier data.yml.
  68. #-----------------------------------------------------------------------
  69. #---clés du fichier data.yml
  70. data_yml_mandatory_keys=['fichier', 'date', 'auteur', 'titre']
  71. data_yml_order=['date','type','auteur','statut','titre']
  72. #
  73. with open("data.yml") as f:
  74. lt=yaml.safe_load(f)
  75. print("data_yml lu")
  76. # on vérifie que le fichier "data.yml" est correct:
  77. for x in data_yml_mandatory_keys: #vérifier la présence des clés obligatoires
  78. if not x in lt.keys():
  79. raise Exception(f"\n\n Il manque la clé {x} dans data.yml\n\n")
  80. # si statut est défini, type doit l'être aussi:
  81. if "statut" in lt.keys(): # membre t=itulaire, correspondant, d'honneur...
  82. if "type" not in lt.keys():
  83. raise Exception(f"\n\n statut est défini, mais pas type\n\n")
  84. #
  85. add_virgule = True
  86. else: # si statut n'est pas défini, on le définit à " " et type à "Conférence".
  87. add_virgule =False
  88. lt["statut"]=" "
  89. if "type" not in lt.keys():
  90. lt["type"]="Conférence"
  91. print("data.yml analysé")
  92. # ---les paramètres:
  93. auteur= lt["auteur"]
  94. titre= lt["titre"]
  95. #label=dolabel(auteur,titre)
  96. if add_virgule:
  97. auteur=auteur+","
  98. lt["auteur"] = auteur
  99. # biblio ?
  100. has_bib= "biblio"in lt.keys()
  101. if has_bib:
  102. bibfile= lt["biblio"]
  103. if citeall:
  104. parsebib.parsebib(bibfile)
  105. #-------------------------------------------------
  106. #
  107. # le fichier (docx, odt) qu'on va traiter:
  108. #
  109. fich=lt["fichier"].strip()
  110. #
  111. # fabriquer le titre à partir des données yml
  112. #
  113. titre_elements="}{".join([lt[x].replace("\n","") for x in data_yml_order])
  114. s,t=fancyshort(lt['auteur'],lt['titre'])
  115. #
  116. #--------------------------------------------------------------------
  117. template=sys.path[0]+"/tpl.tex" # le template
  118. #---------------------------------------------------------------------
  119. exten=fich.split(".")[-1]
  120. #
  121. # Traitement du fichier source
  122. # ---------------------------
  123. if exten=="docx" or exten=="odt":
  124. futurTex= fich.replace(exten,"tex")
  125. else:
  126. s=f"\n{fich} : extension incorrecte"
  127. raise Exception(s)
  128. #répertoire pour les images
  129. images= fich.split(".")[0]+"-media"
  130. print("Répertoire des images : ",images)
  131. if not os.path.isdir(images):
  132. os.mkdir(images)
  133. #
  134. # conversion en latex
  135. #
  136. extra_args= ["-s",f"--template={template}",f"--extract-media={images}"]
  137. #extra_args= ["-s",f"--template={template}",f"--extract-media={images}",
  138. # f"--lof=true"]
  139. L = pypandoc.convert_file(fich, 'tex',
  140. extra_args=extra_args).splitlines()
  141. #-----------------------------------------------------------------------
  142. # section -> section*
  143. rechsec= r"section[{\[]"
  144. rechsecc=re.compile(rechsec)
  145. # pour modifier le latex en changeant le chemin vers les images.
  146. if exten=="docx":
  147. rechgra=r"includegraphics\[.*\]{media.*}"
  148. repPath=("media",f"{images}/word/media")
  149. elif exten=="odt":
  150. rechgra=r"includegraphics\[.*\]{Pictures.*}"
  151. repPath=("Pictures",f"{images}/Pictures")
  152. rechgrac=re.compile(rechgra)
  153. #
  154. # On crée le fichier LaTex
  155. #
  156. with open(futurTex,"w") as f:
  157. L1=star_sec(L)
  158. rp0,rp1= repPath
  159. for l in L1:
  160. if has_bib and "addbibresource{}" in l:
  161. l=l.replace("{","{"+bibfile)
  162. while (q:=rechgrac.search(l)) != None:
  163. l=l.replace(rp0,rp1)
  164. l=treatline(l)
  165. #
  166. if "@@fin" in l:
  167. if has_bib:
  168. f.write("\\section*{Bibliographie}")
  169. if citeall:
  170. f.write(nocite_all(bibfile)+"\n")
  171. f.write("\\printbibliography[heading=none]\n")
  172. f.write("\\FloatBarrier\n")
  173. f.write("\\end{refsection}\n")
  174. f.write(l)
  175. f.write("\n")
  176. if "@@debut" in l:
  177. f.write("\\begin{refsection}\n")
  178. f.write("\\fancyhead{}\n")
  179. f.write("\\fancyhead[CE]{Mémoires: 2\\ieme{} partie}\n")
  180. #f.write(f"\\fancyhead[CO]{{{s} {t}}}\n")
  181. #f.write(le_titre)
  182. f.write("\\input{titre}")
  183. #f.write(f"\\label{{{label}}}\n")
  184. #
  185. #---fin d'éciture du fichier tex
  186. #
  187. # lualatex, 2 fois si pas de bib, 3 fois + biber sinon:
  188. #
  189. if compile:
  190. subprocess.run(["/usr/bin/lualatex", futurTex])
  191. if has_bib:
  192. subprocess.run(["/usr/bin/biber", futurTex.replace(".tex","")])
  193. subprocess.run(["/usr/bin/lualatex", futurTex])
  194. subprocess.run(["/usr/bin/lualatex", futurTex])
  195. #--- fin