| 1 |
import pypdf |
| 2 |
import re |
| 3 |
from pathlib import Path |
| 4 |
from typing import List, Dict |
| 5 |
import ollama |
| 6 |
import os |
| 7 |
import json |
| 8 |
import glob |
| 9 |
from collections import defaultdict |
| 10 |
from pypdf import PdfReader |
| 11 |
|
| 12 |
def get_outline_tree(reader: PdfReader) -> List[Dict]: |
| 13 |
""" |
| 14 |
Extract the complete outline/bookmark structure from a PDF. |
| 15 |
|
| 16 |
Args: |
| 17 |
reader (PdfReader): PyPDF Reader object |
| 18 |
|
| 19 |
Returns: |
| 20 |
list: List of dictionaries containing outline information |
| 21 |
""" |
| 22 |
outlines = reader.outline |
| 23 |
|
| 24 |
if not outlines: |
| 25 |
return [] |
| 26 |
|
| 27 |
def extract_destinations(outline_item): |
| 28 |
"""Recursively extract all destinations from an outline item""" |
| 29 |
if isinstance(outline_item, list): |
| 30 |
return [item for i in outline_item for item in extract_destinations(i)] |
| 31 |
|
| 32 |
if not hasattr(outline_item, '__getitem__'): |
| 33 |
return [] |
| 34 |
|
| 35 |
try: |
| 36 |
title = outline_item.get('/Title', 'Untitled') |
| 37 |
page_num = reader.get_destination_page_number(outline_item) |
| 38 |
|
| 39 |
result = [{ |
| 40 |
'title': title, |
| 41 |
'page': page_num |
| 42 |
}] |
| 43 |
|
| 44 |
|
| 45 |
if '/First' in outline_item: |
| 46 |
result.extend(extract_destinations(outline_item['/First'])) |
| 47 |
|
| 48 |
|
| 49 |
if '/Next' in outline_item: |
| 50 |
result.extend(extract_destinations(outline_item['/Next'])) |
| 51 |
|
| 52 |
return result |
| 53 |
|
| 54 |
except Exception as e: |
| 55 |
print(f"Error processing outline item: {e}") |
| 56 |
return [] |
| 57 |
|
| 58 |
return extract_destinations(outlines) |
| 59 |
|
| 60 |
def find_sections_in_outline(outline: List[Dict], pattern: str, flags: int = re.IGNORECASE) -> List[Dict]: |
| 61 |
""" |
| 62 |
Search for sections in the outline that match the regex pattern. |
| 63 |
|
| 64 |
Args: |
| 65 |
outline (list): Outline structure from get_outline_tree |
| 66 |
pattern (str): Regular expression pattern to search for |
| 67 |
flags (int): Regular expression flags (default: case insensitive) |
| 68 |
|
| 69 |
Returns: |
| 70 |
list: Matching sections with their details |
| 71 |
""" |
| 72 |
matches = [] |
| 73 |
|
| 74 |
try: |
| 75 |
regex = re.compile(pattern, flags) |
| 76 |
|
| 77 |
for item in outline: |
| 78 |
title = item.get('title', '') |
| 79 |
if regex.search(title): |
| 80 |
matches.append(item) |
| 81 |
|
| 82 |
except re.error as e: |
| 83 |
print(f"Invalid regular expression: {e}") |
| 84 |
return [] |
| 85 |
|
| 86 |
return matches |
| 87 |
|
| 88 |
def print_outline(outline: List[Dict]) -> None: |
| 89 |
""" |
| 90 |
Print the outline structure. |
| 91 |
|
| 92 |
Args: |
| 93 |
outline (list): Outline structure from get_outline_tree |
| 94 |
""" |
| 95 |
if not outline: |
| 96 |
return |
| 97 |
|
| 98 |
for item in outline: |
| 99 |
title = item.get('title', 'Untitled') |
| 100 |
page = item.get('page', 0) |
| 101 |
print(f"- {title} (Page {page + 1})") |
| 102 |
|
| 103 |
|
| 104 |
def analyze_primitives(json_pattern): |
| 105 |
primitive_counts = defaultdict(int) |
| 106 |
|
| 107 |
for filename in glob.glob(json_pattern): |
| 108 |
with open(filename) as f: |
| 109 |
design = json.load(f) |
| 110 |
|
| 111 |
for module in design['modules'].values(): |
| 112 |
for cell in module.get('cells', {}).values(): |
| 113 |
primitive_counts[cell['type']] += 1 |
| 114 |
|
| 115 |
|
| 116 |
return dict(sorted(primitive_counts.items(), key=lambda x: x[1], reverse=True)) |
| 117 |
|
| 118 |
|
| 119 |
def generate_summary(pdfs, primitive_name: str) -> str: |
| 120 |
"""Generate markdown summary using Ollama.""" |
| 121 |
|
| 122 |
doc_sections = [] |
| 123 |
for reader in pdfs: |
| 124 |
outline = get_outline_tree(reader) |
| 125 |
matches = find_sections_in_outline(outline, rf"^[0-9\.]+ +{primitive_name}$") |
| 126 |
if matches: |
| 127 |
pages = [reader.pages[match['page']].extract_text() for match in matches] |
| 128 |
doc_sections.append(pages) |
| 129 |
|
| 130 |
doc_context = "\n\n".join( |
| 131 |
"\n".join(pages) |
| 132 |
for pages in doc_sections |
| 133 |
) |
| 134 |
|
| 135 |
description = "" |
| 136 |
if doc_context: |
| 137 |
prompt = f""" |
| 138 |
{doc_context} |
| 139 |
|
| 140 |
Summarizing the functionality of the Gowin {primitive_name} primitive. |
| 141 |
Stick to the provided facts and do not make assumptions. |
| 142 |
Write only the requested paragraph and nothing else. |
| 143 |
""" |
| 144 |
print(prompt) |
| 145 |
response = ollama.generate( |
| 146 |
model='llama3.1:8b', |
| 147 |
prompt=prompt, |
| 148 |
) |
| 149 |
description = escape_markdown(response["response"]) |
| 150 |
print(description) |
| 151 |
return description |
| 152 |
|
| 153 |
|
| 154 |
def escape_markdown(text): |
| 155 |
return text.replace('_', '\\_') |
| 156 |
|
| 157 |
def format_bits(bits): |
| 158 |
if isinstance(bits, list): |
| 159 |
if len(bits) == 1: |
| 160 |
return "1" |
| 161 |
else: |
| 162 |
return str(len(bits)) |
| 163 |
return "1" |
| 164 |
|
| 165 |
def get_default_param_value(value): |
| 166 |
if isinstance(value, str) and all(c in '01' for c in value): |
| 167 |
decimal_value = int(value, 2) |
| 168 |
return f"{decimal_value} (0b{value})" |
| 169 |
return value |
| 170 |
|
| 171 |
def generate_module_doc(module_name, module_data, supported, pdfs): |
| 172 |
module_doc = [] |
| 173 |
|
| 174 |
module_doc.append(generate_summary(pdfs, module_name)) |
| 175 |
|
| 176 |
module_doc.append("\n") |
| 177 |
if supported: |
| 178 |
module_doc.append("This device is supported in Apicula.") |
| 179 |
else: |
| 180 |
module_doc.append("This device is not yet supported in Apicula") |
| 181 |
|
| 182 |
|
| 183 |
if module_data.get('ports'): |
| 184 |
module_doc.append("## Ports\n") |
| 185 |
module_doc.append("| Port | Size | Direction |") |
| 186 |
module_doc.append("|------|------|-----------|") |
| 187 |
|
| 188 |
for port_name, port_data in sorted(module_data['ports'].items()): |
| 189 |
size = format_bits(port_data['bits']) |
| 190 |
direction = port_data['direction'] |
| 191 |
module_doc.append(f"| {escape_markdown(port_name)} | {size} | {direction} |") |
| 192 |
module_doc.append("\n") |
| 193 |
|
| 194 |
|
| 195 |
if module_data.get('parameter_default_values'): |
| 196 |
module_doc.append("## Parameters\n") |
| 197 |
module_doc.append("| Parameter | Default Value |") |
| 198 |
module_doc.append("|-----------|---------------|") |
| 199 |
|
| 200 |
for param_name, param_value in sorted(module_data['parameter_default_values'].items()): |
| 201 |
default_value = get_default_param_value(param_value) |
| 202 |
module_doc.append(f"| {escape_markdown(param_name)} | {default_value} |") |
| 203 |
module_doc.append("\n") |
| 204 |
|
| 205 |
|
| 206 |
module_doc.append("## Verilog Instantiation") |
| 207 |
module_doc.append("```verilog") |
| 208 |
|
| 209 |
|
| 210 |
instance = [] |
| 211 |
|
| 212 |
|
| 213 |
if module_data.get('parameter_default_values'): |
| 214 |
instance.append(f"{module_name} #(") |
| 215 |
param_list = [] |
| 216 |
for param_name in sorted(module_data['parameter_default_values'].keys()): |
| 217 |
param_list.append(f" .{param_name}({param_name})") |
| 218 |
instance.append(",\n".join(param_list)) |
| 219 |
instance.append(f") {module_name.lower()}_inst (") |
| 220 |
else: |
| 221 |
instance.append(f"{module_name} {module_name.lower()}_inst (") |
| 222 |
|
| 223 |
|
| 224 |
if module_data.get('ports'): |
| 225 |
port_list = [] |
| 226 |
for port_name in sorted(module_data['ports'].keys()): |
| 227 |
port_list.append(f" .{port_name}({port_name})") |
| 228 |
instance.append(",\n".join(port_list)) |
| 229 |
|
| 230 |
instance.append(");") |
| 231 |
module_doc.append("\n".join(instance)) |
| 232 |
module_doc.append("```\n") |
| 233 |
|
| 234 |
return "\n".join(module_doc) |
| 235 |
|
| 236 |
def process_json_file(json_data, stats, pdfs, output_dir): |
| 237 |
|
| 238 |
os.makedirs(output_dir, exist_ok=True) |
| 239 |
|
| 240 |
|
| 241 |
for module_name, module_data in sorted(json_data['modules'].items()): |
| 242 |
|
| 243 |
supported = module_name in stats |
| 244 |
doc = generate_module_doc(module_name, module_data, supported, pdfs) |
| 245 |
|
| 246 |
|
| 247 |
filename = os.path.join(output_dir, f"{module_name}.md") |
| 248 |
with open(filename, 'w') as f: |
| 249 |
f.write(doc) |
| 250 |
|
| 251 |
def main(): |
| 252 |
|
| 253 |
output_dir = "../apicula.wiki" |
| 254 |
|
| 255 |
|
| 256 |
with open('prims.json', 'r') as f: |
| 257 |
data = json.load(f) |
| 258 |
|
| 259 |
stats = analyze_primitives('examples/himbaechel/*-synth.json') |
| 260 |
|
| 261 |
pdfs = [] |
| 262 |
for pdf_path in Path("~/Documents/gowin/").expanduser().glob("*.pdf"): |
| 263 |
pdfs.append(pypdf.PdfReader(pdf_path)) |
| 264 |
|
| 265 |
|
| 266 |
process_json_file(data, stats, pdfs, output_dir) |
| 267 |
print(f"Documentation generated in {output_dir}/") |
| 268 |
|
| 269 |
if __name__ == "__main__": |
| 270 |
main() |