extr.py 6.5 KB

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